Api String

substring(int offset)

As per the API, it says, "this method returns a new String, which is a subset of this string." There will be an IndexOutOfBoundsExpression if in case, the argument being passed is -ve. In case of two offsets (start, end), the usual conditions to be met, otherwise the exception is thrown.

If the substring contains all characters (which is NOT actually a substring), it seems to be returning the SAME String and NOT the new String. In case of String's references being compared in the if loop, this helps.

Reference -> a JavaRanch thread titled Java Strings:


if("String".substring(0,6) == "String")            
        System.out.println("substring Equal");     
        System.out.println("substring Not Equal");

The output to the above code is :

substring Equal

Because of the above said reason. Since the substring being extracted is having the same set of characters as that of the base string, it does NOT return a new string. Thereby the same string is compared, and the result is TRUE!


toString() method does NOT throw a NPE (NullPointerException) when being used in SOP for a null String. Why so? Important Point to Note!

Look at the code given below (from the thread)

class test {
   void m(Object x) {
   void m(String x) {
       x.toString();     //NPException   --1
       System.out.print(x);  //OK        --2
    public static void main(String[] args) {
            new test().m(null);

The actual question from the OP (Original Poster) was :

I suppose at 2 also, System.out.print() uses toString(). How come only at
1 there is exception while at 2 it is not ?

The good explanation given by one of the bartenders "Jesper Young" was below.

The printf() method does not directly call toString() on the object; instead, it uses String.valueOf(x).

String.valueOf(…) first checks if the object is null, and if so, it returns the string "null", otherwise it returns x.toString(). See the API documentation of String.valueOf(…).

The API for String.valueOf() method is

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.