Java - Write code to do safe substring, without exception

Requirements

Write code to do safe substring, without exception

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        int length = 2;
        System.out.println(substr(str, length));
    }//from w  ww.  ja va  2  s .  co m

    public static String substr(String str, int length) {
        if (str == null) {
            return str;
        }
        if (length < str.length()) {
            return str.substring(0, length);
        }
        return str;
    }
}

Related Exercise