Consider the following:
The difference has to do with how Strings are stored in memory in java and what the == operator does. The == test simply checks to see if the two objects in question have the same bit
pattern or not. Remember that a variable contains the memory location of an object so that if two variables are set equal to each other, then they both point to the same location in memory and therefore have the same bit pattern. In java, a special section of memory is reserved as the "String pool." In this pool, java keeps a list of Strings that are created using the form
so that if I create another identical String such as
java simply sets s2 to point to the same place in memory that s1 is refering to in the String pool. This is done to save space in memory. Thats why
prints "true." Now if I create a String using the "new" key
word a new String object is created and is placed in on the heap which is in a different section of memory than the String pool. That's why
prints "false" - because s2 and s3 contain references to different sections of memory. If you want to compare the values of the actual strings themselves, you must use the String method equals() which looks not at the memory locations but instead compares the Strings themselves. Get it?
[ December 16, 2004: Message edited by: J Williams ]
[ December 16, 2004: Message edited by: J Williams ]
[ December 16, 2004: Message edited by: J Williams ]