Results 1 to 4 of 4
Thread: String == String
- 12-17-2011, 11:30 PM #1
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 183
- Rep Power
- 5
String == String
This is weird.
So, I was teaching somebody how to use Java and I had essentially said if you compare two strings with == they are not necessarily equal even if they have the same value. So...
String str1 = "text";
String str2 = "text";
System.out.println(str1 == str2);
This printed out true.
...WHAT? Does == now evaluate based on .equals rather than the reference or something? Or am I missing something here...
- 12-17-2011, 11:38 PM #2
Banned
- Join Date
- Dec 2011
- Posts
- 143
- Rep Power
- 0
Re: String == String
The compiler knows that a constant cannot change. So it creates only on copy of "text" in memory.
Try this..
String str1 = "text";
String str2 = new String("text");
This also..
String str1 = "text";
String str2 = str1 + "";
System.out.println(str1 == str2);
I guess it all depends on how clever the compiler is.Last edited by 2by4; 12-17-2011 at 11:59 PM.
- 12-17-2011, 11:42 PM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Re: String == String
That's right, if you mean by "have the same value" that they are made up of the same characters in the same order.if you compare two strings with == they are not necessarily equal even if they have the same value
Your example is not inconsistent with that. Two strings made up of ... (equals() for short) may or may not be ==. If you want an example that prints false, try
In the example you tried the strings were interned.Java Code:String str1 = new String("text"); String str2 = new String("text");
- 12-17-2011, 11:42 PM #4
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 183
- Rep Power
- 5
Similar Threads
-
how to compare one string with another dynamic length pattern string?
By ravi.josih53 in forum New To JavaReplies: 11Last Post: 08-15-2011, 10:12 AM -
Binary-algorithm -> Insert String to sorted String-ArrayList
By Muskar in forum Advanced JavaReplies: 12Last Post: 11-26-2010, 08:33 AM -
Test for all empty Strings in LinkedHashMap<String,ArrayList<String>
By albertkao in forum New To JavaReplies: 1Last Post: 11-04-2010, 06:53 PM -
The constructor Person(String, String, Date) is undefined
By fh84 in forum New To JavaReplies: 7Last Post: 11-03-2009, 02:18 AM -
Using java.util.Scanner to search for a String in a String
By Java Tip in forum Java TipReplies: 0Last Post: 11-20-2007, 04:59 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks