• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object & String

 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
program is

class MyClass4
{
public static void main(String args[])
{

Object obj1 = "SCJP";

Object obj2 = new String("SCJP");

System.out.println(obj1.equals(obj2));
}
}

output for the above program is "true".

can any one explain me.
 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because, the method called is the equal() method in the String class.
This results in equality of obj1 and obj2 as both contain the same string "SCJP".
 
Prasad Shindikar
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals() method always checks for "meaningfully equivalent" objects
since obj1 and obj2 both contain the same string "SCJP" these objects are meaningfully equivalent.

Hence the answer is true.
If at all you do obj1 == obj2 then you will get the answer as false.
This is because == operator checks the object references.
 
Rakesh Ne
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Rami Reddy question basically is "why is String class equals method is called ?"

Or

How does the JVM know that String class equals needs to be called rather then Object class equals (which plainly checks for equality of reference)
 
Srinivasan thoyyeti
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is basic overriding principle in Java
where Base class is Object and Child is String.
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A fast question,

When we say:


"some value" is placed in the String constant pool, but what about when we say:


Is "some value" placed in the pool too ?

Thanks in advance ...
 
Srinivasan thoyyeti
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes. We are just storing String reference in Object reference. thats it.
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot ...

Good luck ...
 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it. thansk all..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic