• Post Reply Bookmark Topic Watch Topic
  • New Topic

a question about string and eqalization..  RSS feed

 
alex lotel
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have this code and i need to know what is output of it
i thought that its
false
true
true
because i thought that the equals method can spot the differnces
between the way a variable was done
if they were done in a different ways although they have
a similar values it will return us "false"
unlike the "==" method that checks only the values

appantly i was wrong and the output is
true
false
true

i dont have any clue why??
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does s==tmp return true? It is because both references point to the same object. And why is there only one object? Because the compiler interns the String object, so only one copy exists. After all, an immutable object does not need to be duplicated.
 
alex lotel
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so what is the differce between "equals" method
and "=="
??
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I strongly recommend that you download the API documentation and open it whilst writing code. You will find that many questions are answered by reading this documentation, including what the equals() method does.
 
Daniel Chemko
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== determines that the two object references point to the exact same stack/heap variable, aka their memory addresses.

The most primitive version of .equals() also does the exact same thing.

The difference is that equals can be overridden by any class and is quite often overridden. equals() is intended to ask if the objects are 'equivalent', not necessarily the same object in RAM.
 
Thyagarajan Ramanujam
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java manages a String Pool. when you initialize a string as
String n = "hai";
it will be stored in String pool.

But if the statement is
String n = new String("hai");
it will be in heap.


so the location is different but the content is same.

So .equals() method checks the content while == looks for the location
 
alex lotel
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!