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 Can any one please tell the reason for the  String related question.. given here 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 "Can any one please tell the reason for the  String related question.. given here" Watch "Can any one please tell the reason for the  String related question.. given here" New topic
Author

Can any one please tell the reason for the String related question.. given here

Raveendra Mutyala
Greenhorn

Joined: Sep 10, 2005
Posts: 13
String a="abc";
String b="abc";
String c= new String("abc");
String d= new String("abc");
if (a==b)
{System.out.println(" a and b are equal");
}
else System.out.println(" a and b are not equal");
if (b==c)
{System.out.println(" b and c are equal");
}
else System.out.println(" b and c are not equal");
if (c==d)
{System.out.println(" c and d are equal");
}
else System.out.println(" c and d are not equal");
if ("abc"=="abc")
{System.out.println(" abc and abc are equal");
}
else System.out.println(" abc and abc are not equal");

output:
a and b are equal
b and c are not equal
c and d are not equal
abc and abc are equal..
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

There is a difference between the == operator in the language and the equals() method that is available in every class.

The == operator is a reference test. When you test two object references with ==, you are asking if the two references point to the same object in memory. String a and String b could both have "abc" as their content but be located in different parts of memory. If they are, the test returns true. If not, the test returns false, even though the content in memory is the same.

To test for equal content among String object references, use the equals() method instead.


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

Now: here's an additional thing.

Java allows String object to have internal references in 'static memory' if they are not instantiated. That is, if you write:

as you did above, the compiler will silently put one "abc" in memory at runtime and make both a and b point to that one copy.

If you instantiate them like so:

you then force the compiler to allocate these spaces at runtime as separate entities.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can any one please tell the reason for the String related question.. given here
 
Similar Threads
what is the ouptut and how..
Exception
equals method
equals method in Object class
== and equals in String Class