Tuesday, May 12, 2020

java puzzlers from oca part 7


In this part of the Java Puzzlers from OCA series, I will show multiple ways of defining Strings and potential surprises related to that. Two basic types of creating Strings are creation with new keyword, and by just using the string literal.
String strWithNew = new String("hey");
String strWithLiteral = "ho";
As Strings are frequently used JVM uses a string pool and use the values in it so it won't have to create new objects for same values again and again. So seeing that the object address of same string literals are same should not be a surprise.
public class Puzzler {

    public static void main(String[] args) {

        String s1 = "myString";
        String s2 = "myString";

        System.out.println(s1 == s2); // true
    }
}
Ok then, this should be the same also right?
public class Puzzler {

    public static void main(String[] args) {


        String s1 = new String("myString");
        String s2 = new String("myString");

        System.out.println(s1 == s2);
    }
}
Not really. This will print "false". So if I create a new string with literal "myString" it is placed in the string pool. If I create it with new keyword then it's not searched in the pool, and when it's created it's also not placed in the string pool.
public class Puzzler {

    public static void main(String[] args) {


        String s1 = new String("myString");
        String s2 = new String("myString");
        String s3 = "myString";
        String s4 = "myString";

        System.out.println(s1 == s2);
        System.out.println(s2 == s3);
        System.out.println(s3 == s4);
        System.out.println(s1 == s4);
    }
}
I hope you can guess what happens above. s1 creates a new string and does not put it in the pool, s2 does the same thing. s3 takes a look to string pool does not see myString and creates it and places in the pool. s4 says "ah ok it is in the pool". So if we count how many strings are created, it is 3 and if we count what's placed in the pool it's 1 (myString). false, false, true, false are what's printed to the console.