Hi ... I thought I understood the difference between using the == operator and the equals() method with String objects but the following code has me thoroughly confused
I thought I would see:
Would someone please explain why they all came up true? Thanks
Thanks Paul. Think I've finally got it but just in case, does the following sound right:
if String objects having the same data are created using a constant expression, a string literal, a reference to an existing string, or by explicitly using the intern() method, their references will be the same
if String objects having the same data are created explicitly with the new operator or their values are computed at runtime, their references will be different
Thanks
[This message has been edited by Jane Griscti (edited September 14, 2000).]
Barbara Dyer-Bennet
Greenhorn
Joined: Sep 14, 2000
Posts: 10
posted
0
The way I read the line: System.out.println("\t Equals: s1 == s4 \t\t " + (s1 != s4)); the expression (s1 != s4) comes up as true because you have a trick in there... s1 is NOT equal to s4, so the print statement displays the word true. I hope this helps.
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
By the way, let me just add another excellent example which will clear everybody's concept about String literals: Here it goes:
produces the output: true true true true false true This example illustrates six points: Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1). Literal strings within different classes in the same package represent references to the same String object. Literal strings within different classes in different packages likewise represent references to the same String object. Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals. Strings computed at run time are newly created and therefore distinct. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents. Hope this helps all of us for the exam -sampaths77 [I added UBB CODE tags to your source code to make it more readable. Please try to use them in the future. Learn more about UBB codes - Ajith] [This message has been edited by Ajith Kallambella (edited September 15, 2000).]
Jane Griscti
Ranch Hand
Joined: Aug 30, 2000
Posts: 3141
posted
0
Thanks Barbara, Sampaths77 ... I noticed the "!=" after banging my head against the code for an hour or so Oh well, it forced me to go through the JLS on String literals so in the end I learned from it. Jane