I really don't understand this concept at all. Look at the following code:
When I run the code, the message actually prints out! I thought the equality operator tests only if 2 references refer to the same object? I clearly thought that the JVM will create 2 different strings in this scenario. After a while, I thought that maybe it's because the JVM searches the String Pool and realize that it can reuse the same string for the second reference, that's why the if statement becomes true.
BUT, what about this:
Now the message doesn't come out! What is happening?
What if there's a question asking me how many String objects are created altogether in a snippet of code? If there are identical strings in the code snippet, how do I know if the JVM will search the String Constant Pool? For example, this code snippet is from my study guide:
So according to the code above, how many String objects are created? Is it 3 or 4? It can be 4 because the first line may create 2 strings, one for variable x, and one for the method argument. But it can also be 3 because if the JVM reuses the same String object from the String Constant Pool, then only 1 String object is created for the first line.
Or am I being paranoid here, since the String Constant Pool may not be playing a part here. Haha! [ January 13, 2005: Message edited by: Liang Anmian ]
Current Status:<br /> <br />SCJP 1.4<br />SCJD (in progress)
String literals in your source code will only be created once and in one place: the constant string pool.
So, "String" == "String" ... will make only one actual String in the constant string pool, which is why the equality operator returns true. I didn't read your whole post. Hopefully you were still asking about the same thing further down.