• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt in String ==

 
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator




What is not working according to my expectations is below
i thought both if's will be evaluated to true and S.O.P s will be printed.But to my surprise, both if conditions turned out to be false.

Why i thought true?
The reason being ,since all three string references are initiated with value "nice", i thought the concept of string constant pool will come into picture, and therefor t1 ,t2 and t3 will refer to same object on heap.However i see this is not how it works.Can anyone please back it up with some reason

Thanks
 
Ranch Hand
Posts: 125
Postgres Database BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Maan Suraj wrote:



What is not working according to my expectations is below
i thought both if's will be evaluated to true and S.O.P s will be printed.But to my surprise, both if conditions turned out to be false.

Why i thought true?
The reason being ,since all three string references are initiated with value "nice", i thought the concept of string constant pool will come into picture, and therefor t1 ,t2 and t3 will refer to same object on heap.However i see this is not how it works.Can anyone please back it up with some reason

Thanks



t1==t3, both of them live in the string pool. But t2 lives in the heap.
Now here is the big secret to everything "==" related in java, (excluding primitives) is that == between Objects is "just comparisons between memory addresses". Java books struggle to avoid using the term "pointer", but actually this is what "references" really are. Pointers to structures in memory, just like good old C.
The above program, first creates a String in the pool "nice" and makes s1 point to this address in the pool. You can imagine the pool as a special segment in the heap. Then it uses s2=new("nice"). This first tries to see if "nice" is in the pool, and it finds it there, then it STILL makes a new object in the heap (because of the new, and assigns the value "nice" to it. "New" always makes a new structure in the heap. (which in strict terms has a different address space than the String pool). The third string s3="nice" works in the same way . finds "nice" in the pool and makes s3 point there. So seen as pointers, s1 and s3 point to the same address in the string pool (therefore bit-wise have the same value), whereas s2 point to a different address in the heap.
Hope that helps!
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The t2 reference refers to a new String object on the heap. Remember whenever you do a new Something(), the JVM will put a new Object on the heap. t1 and t3 on the other hand, are just references pointing towards the String object in the String-pool of JVM. You can test the remaining comparison in your code i.e. t1==t3 which willl surely resolve to true.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Just wanted to add that if you want to compare the contents of the string then you might want to use "equals".
You might want to test the above code using equals and that tests to true in both cases.

if (t1.equals(t2)) {
System.out.println("t1");
}

if (t1.equals(t3)) {
System.out.println("t3");
}


Joe.
 
Maan Suraj
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks everyone for explaining it this well
 
Ranch Hand
Posts: 47
Eclipse IDE Debian Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Joe Okelly wrote: Hi,
Just wanted to add that if you want to compare the contents of the string then you might want to use "equals".
You might want to test the above code using equals and that tests to true in both cases.


Joe.


hi joe,

equals() is overridden in String class. equals() method with return true only if two references refer to the same object and have same value. so, in your code, first if test will fail as 't1' and 't2' do not refer to the same object. second if test will return true as 't1' and 't3' refer to the same String(which is in the String pool) .

cheers

cheers
 
Ranch Hand
Posts: 281
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Chaitanya Kidambi wrote:

Joe Okelly wrote: Hi,
Just wanted to add that if you want to compare the contents of the string then you might want to use "equals".
You might want to test the above code using equals and that tests to true in both cases.

Joe.


hi joe,

equals() is overridden in String class. equals() method with return true only if two references refer to the same object and have same value. so, in your code, first if test will fail as 't1' and 't2' do not refer to the same object. second if test will return true as 't1' and 't3' refer to the same String(which is in the String pool) .

cheers

cheers



Hi Chaitanya, Joe is correct.

t1.equals(t2) is absolutely 'true' for the values String t1="nice"; String t2=new String("nice");

This is the best and the correct way to compare two string values.
 
Joe Okelly
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
I found the topic interesting so i did some research (googled the topic).

The explanation I found wish to share :

The equals()
method compares two objects for equality and returns
true
if they are equal. The
equals()
method provided in the
Object
class uses the identity operator (
==
) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The
equals()
method provided by
Object
tests whether the object references are equal—that is, if the objects compared are the exact same object.
To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the
equals()
method. Here is an example of a
Book
class that overrides
equals()
:

public class Book {
...
public boolean equals(Object obj) {
if (obj instanceof Book)
return ISBN.equals((Book)obj.getISBN());
else
return false;
}
}
Consider this code that tests two instances of the
Book
class for equality:
Book firstBook = new Book("0201914670"); //Swing Tutorial, 2nd edition
Book secondBook = new Book("0201914670");
if (firstBook.equals(secondBook)) {
System.out.println("objects are equal");
} else {
System.out.println("objects are not equal");
}
This program displays
objects are equal
even though
firstBook
and
secondBook
reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number.
You should always override the
equals()
method if the identity operator is not appropriate for your class.


Hope this helps,

Joe.





 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Chaitanya Kidambi wrote:Hi,
equals() is overridden in String class. equals() method with return true only if two references refer to the same object and have same value. so, in your code, first if test will fail as 't1' and 't2' do not refer to the same object. second if test will return true as 't1' and 't3' refer to the same String(which is in the String pool) .



The documentation contradicts this statement:
http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#equals%28java.lang.Object%29

But if we want to talk about the implementation let's look at the code and get it straight.

First we compare object references. If they are the same we return true.
If not, we continue:

If the parameter is an instance of String:
If the Strings have equal length:
Perform a really ugly iteration that compares the characters at each index:
If the comparison evaluates the characters as unequal, we return false.

If we get through the iteration, we return true.

If we come out of the above block then one of our conditions was not met
and we return false.
 
Ranch Hand
Posts: 394
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Guys,
the documentation effectively sumarises it all in two lines:


equals() method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.


I want to add that the SAME occurs with primitive wrappers -at LEAST the ones I tested-.

Regards

Ikpefua
 
Chaitanya Kidambi
Ranch Hand
Posts: 47
Eclipse IDE Debian Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dennis Deems wrote:

Chaitanya Kidambi wrote:Hi,
equals() is overridden in String class. equals() method with return true only if two references refer to the same object and have same value. so, in your code, first if test will fail as 't1' and 't2' do not refer to the same object. second if test will return true as 't1' and 't3' refer to the same String(which is in the String pool) .



The documentation contradicts this statement:
http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#equals%28java.lang.Object%29



firstly i would like to say sorry for my wrong understanding of equals() method in String and wrapper classes. i am totally confused about equals() method now.
so, equals() method in String and wrapper classes will return true if the values are same. in general if we dont override equals() method, then two instances of the same class type cant be equal.
for example:


but for strings and wrapper types it would return true if both instances have same values. am i right ?. i again apologise for the mistake
thanks a lott
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chaitanya, I think you understand it correctly now.
 
Chaitanya Kidambi
Ranch Hand
Posts: 47
Eclipse IDE Debian Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dennis Deems wrote:Chaitanya, I think you understand it correctly now.



Thanks Dennis Deems
 
Ikpefua Jacob-Obinyan
Ranch Hand
Posts: 394
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Chaitanya,
IMHO you did not make any 'GRAVE' mistake in this thread, your analysis about the equals() is correct in general terms, it simply does NOT apply to Strings and primitive Wrappers.

The equals() method in class 'Object' according to the OFFICIAL DOCUMENTATION is defined as follows:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).



Now this does NOT apply to Strings and primitive wrappers simply because the equals() method is overridden in those classes, however if you instantiate objects of your class and invoke the equals() method inherited from class Object, to compare their respective reference variables, the result will ALWAYS be false.

Regards

Ikpefua
 
reply
    Bookmark Topic Watch Topic
  • New Topic