File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes difference between string equals. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "difference between string equals." Watch "difference between string equals." New topic

difference between string equals.

sowjan kumar

Joined: Oct 09, 2004
Posts: 24
Hello All
Can anyone please explain me what is the difference between
I'm getting different answers for both of these...

Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
What objects are s2, s3 and s4? Besides, one would need to know how you have initialized/assigned values to these objects before answering your question.


Joined: Dec 01, 2004
Posts: 4
It's a test example below:

public class Test

public static void main(String[] args)
String s1="love",

run java Test,the answer both are false except the second having a space aditonal.

Good good study! <br />Day day up!<br />——————javainthinking
J Williams

Joined: Nov 13, 2004
Posts: 10
Consider the following:

The difference has to do with how Strings are stored in memory in java and what the == operator does. The == test simply checks to see if the two objects in question have the same bit pattern or not. Remember that a variable contains the memory location of an object so that if two variables are set equal to each other, then they both point to the same location in memory and therefore have the same bit pattern. In java, a special section of memory is reserved as the "String pool." In this pool, java keeps a list of Strings that are created using the form

so that if I create another identical String such as

java simply sets s2 to point to the same place in memory that s1 is refering to in the String pool. This is done to save space in memory. Thats why prints "true." Now if I create a String using the "new" key word a new String object is created and is placed in on the heap which is in a different section of memory than the String pool. That's why prints "false" - because s2 and s3 contain references to different sections of memory. If you want to compare the values of the actual strings themselves, you must use the String method equals() which looks not at the memory locations but instead compares the Strings themselves. Get it?

[ December 16, 2004: Message edited by: J Williams ]

[ December 16, 2004: Message edited by: J Williams ]
[ December 16, 2004: Message edited by: J Williams ]

"Three people cannot keep a secret." SCJP 1.4
I agree. Here's the link:
subject: difference between string equals.
It's not a secret anymore!