As explained in these Stackoverflow questions: question 1 & question 2 I understand that "String literals" are interned when:
String s = "abc";
And that the JVM will create a new String object instead of using an existing one from the String Pool when:
String s = new String("abc");
However, I have a doubt after reading the following two similar statements.
- From SCJP preparation book:
When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.
- From JavaRanch:
In this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.
So if we also put a reference in nonpool memory AND in pool memory when we create an object using "new" and based on the definitions above. Shouldn't the JVM also return the same reference when we do this?:
String one = new String("test");
String two = "test";
System.out.println(one.equals(two)); // true
System.out.println(one == two); // false
Because when declaring the String literal String three = "test";
it will already exist in the pool? and therefore should return the same reference and print true? or do the previous statements mean that they will be put in pool memory but simply skipped when the new
operator is used?