File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes String query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String query" Watch "String query" New topic
Author

String query

pankaj kapoor
Greenhorn

Joined: Sep 22, 2005
Posts: 17
String s = new String("abc");
String b = new String("abc");
if(s==b )
System.out.println("equal");

String s1 = "abc";
String b1 = "abc";
if(s1==b1 )
System.out.println("equal String");

In the above code s1==b1 prints "equal String"
while s==b does not print "equal"

could anyone explain to me the reason for this .
Thanks in advance
Craig Tyler
Ranch Hand

Joined: Jan 15, 2006
Posts: 52
== tests if the objects being compared are actually the same object. In your example, s and b are different objects with the same contents, so while they pass the equals() test because they have the same contents, they produce false when using ==.

s1 and b1 both refer to the same object in the string literal pool, so they pass both == and equals().
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

"new" will create to new objects, that is why "==" returns false.

However, using "=" will get an existing object from the pool, or create a new one if it does not exist. There is already a String whose value is "abc", so it will return the same reference to that String. Same reference, means that "==" will return true.


[My Blog]
All roads lead to JavaRanch
 
 
subject: String query
 
Similar Threads
equals() Question
Regd. Strings...
String equality
Can any one please tell the reason for the String related question.. given here
Confusion on the topic of String constant table ?