You're creating two different objects in the String constant pool. The equality test (==) only returns true when two object references are pointing to the same object. If you want to compare value, then use one of the String's equals() methods:
[ October 08, 2003: Message edited by: Jeff Bosch ]
Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4 all those years ago...)
Even though "hello" and "world" are string literals, you're using concatenation with a variable to put them together. When you do that, a brand new String is created. However, if you don't use the variable (as is done with s4 and s5), the compiler can perform an optimization and create a single "helloworld" string literal.
�hello� + �world� is a constant expression. final String s = �world�; �hello� + s is a constant expression. String s = �world�; �hello� + s is not a constant expression. This is how the concatenation operator works. StringBuffer sb = new StringBuffer(); sb.append(�hello�); sb.append(s); String x = sb.toString(); // a new String object is created
You can see the StringBuffer method calls in the byte codes. You can see the call to toString() that creates a new String object.
Hi Jeff. javap is a utility that comes with the SDK. It disassembles a class file. javap �c classname The �c switch prints the byte codes. You probably know where the byte codes are defined. Java Virtual Machine Spec Chapter 6. javap �private classname The �private switch prints all members of a class. This is very useful for seeing the synthetic fields the compiler adds to inner classes.