get Sub String and handle null value - Java java.lang

Java examples for java.lang:String Substring

Description

get Sub String and handle null value

Demo Code


public class Main{

    public static void main(String[] argv){
        int start = 2;
        int num = 4;
        String str = "java2s.com";
        System.out.println(getSubString(start,num,str));
    }/*  w ww .  j a va 2s. c om*/

    public static String getSubString(int start, int num, String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        if (start < 0) {
            start = 0;
        }
        if (start > length) {
            start = length;
        }
        if (num < 0) {
            num = 1;
        }
        int end = start + num;
        if (end > length) {
            end = length;
        }
        return str.substring(start, end);
    }

}

Related Tutorials