Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Raveendra Mutyala
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic