• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings

 
sreedhar meda
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello everybody,
here i have a doubt regarding strings. i got an instance
where i instantiated strings.
here are the following two statements.
String s1 = "Hello";
String s2 = new String(s1);
here when i used if statement as follows, i got the result
that they are unequal.
if(s1==s2) resulted in Unequal, where as
if(s1.equals(s2)) resulted in Equal.
Also, if i use the if statement as below,
s1 = "Hello"
s2 = "Hello"

if(s1==s2) then, the result is Equal.
what is the difference in both the initializations?
viz, s2="Hello" and s2= new String(s1);
kindly help me!
with warm regards,
sreedhar

 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sreedhar -
String is a special case class that allows for both static initialization and object creation. The lanugage permits this behavior to improve performance. s1 therefore contains the same value as s2; however, each reference sees that value at a different location in memory.
That brings us to the difference between the == operator and the equals() method. The equality operator is actually overloaded. When it's used to compare primitives, it solves the test for equal value. When it's used to compare references, it solves the test for same location in memory.
The equals() method is first defined in java.lang.Object, and by default it performs a == on two object references. In String, however, equals() is overridden so that it compares two String objects only for their content. Thus (s1 == s2) is false unless they point to the same object, but s1.equals(s2) is false only if the values don't match.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is probably useful to add that two Strings literals with the same value actually share the same String object. This is safe because Strings are immutable.
This is not true for dynamically created Strings.
This is why == gives different results depending on how you initialise your variables.
- Peter
 
ravinder thirumala
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As we now that strings are treated as a immutable ,if we use equals(),it means that we are equating the contents of String
objects
But when we use == it means that we are testing the
references of the objects,if they are equal than it results in true ,as u are equating to the same string ,which means we are
storing stirng and same reference is passed to both objects,
but if u ar using "new" a new object is created
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic