Results 1 to 4 of 4
Thread: String object comparison issue
- 01-19-2011, 05:30 AM #1
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
String object comparison issue
Hi all,
Here goes my piece of code
/****************************/
class Simple1 {
public static void main (String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Hello";
String s4 = new String(s3);
System.out.println(s1==s2);
System.out.println(s3==s4);
}
}
/****************************/
I know that (s3==s4) will give false since s3 and s4 are different objects even though their contents are same.
But for (s1==s2) i get true. Could anyone please give a reasoning.
Ain't s1 and s2 different objects too?
Shouldn't this comparison also return false?
- 01-19-2011, 06:06 AM #2
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
your assumption is true on all Objects but not in String.
All strings we created in a java program are stored in a location called string literal pool. when a new String is created it check whether pool contains same, and if found new object reference is assigned with that same reference.
also note this is the reason behind immutability of string
- 01-19-2011, 06:10 AM #3
No, there are not really different objects. Have you heard of String pooling?
What happens is, Strings are basically IMMUTABLE objects. When you create a String like,
A String object "Hello" gets created on the heap. Now if you try to create another String with same value "Hello", there won't be another String object creation, but your new String reference would refer to the ONLY "Hello" created on the heap.Java Code:String s1 = "Hello";
That's why when you do s1 == s2, they both actually refer to the ONLY same value String present on the heap. And that's why it returns true.
Hope that's clear enough,
GoldestJava Is A Funny Language... Really!.gif)
Click on * and add to member reputation, if you find their advices/solutions effective.
- 01-19-2011, 06:18 AM #4
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
Thanks jomy and goldest,
Searched more about string literal pool. Now understood the concept.
For others who still have the doubt, this link may help
What is String literal pool?
Similar Threads
-
String to String Comparison being ignored
By leonsbuddydave in forum New To JavaReplies: 4Last Post: 01-07-2011, 12:25 AM -
String Comparison
By evant8950 in forum Java AppletsReplies: 6Last Post: 04-22-2009, 08:11 AM -
Object Comparison!
By sajdutt in forum Advanced JavaReplies: 6Last Post: 05-23-2008, 01:48 PM -
String comparison
By abhiN in forum New To JavaReplies: 2Last Post: 04-09-2008, 04:47 AM -
String comparison
By sireesha in forum New To JavaReplies: 1Last Post: 12-18-2007, 12:16 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks