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 w  w .j  av  a  2  s.c o  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