There are two ways to create String. These are:
Here test1 and test2 are pointing to the same Object. How?? The answer is - The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool.
1. Using String literals
2. Using new keyword
2. Using new keyword
But what is the difference between these two approaches. Lets take an example:
String test1 = "Ramesh"; String test2 = "Ramesh"; String test3 = new String("Ramesh"); System.out.println("test1 == test2 : "+ (test1 == test2)); // true System.out.println("test1 == test3 : "+ (test1 == test3)); // false
If we see test1 and test2 results to true and test1 and test3 results to false on comparing with == operator.
Reason: As I discussed in my previous post Mystery of equals() and == in Java, == operator always checks for the reference equality i.e if two references are pointing to the same object the result of comparison will be true.
Here test1 and test2 are pointing to the same Object. How?? The answer is - The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool.
Now what is String Pool??
String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.
intern method() - A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. Thejava.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added. In continuation to the previous example,do the following changes and you will see that test1 and test3 are pointing to the same object.
System.out.println("test1 == test3 : "+ (test1 == test3.intern())); // true