• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString() method

 
mahesh deshpande
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends
Please help me to understand this
Byte b1 = new Byte("127");
if( b1.toString()== b1.toString())
System.out.println("True");
else
System.out.println("False");
The above code returns false
Where as
"String".toString() == "String".toString()
returns True
also
"String".toString()=="String";
returns True
Another String related question
String S1 = new String( "amit");
String S3 = "arit";
String S2 = S1.replace('m','r');
System.out.println(S2==S3);
This returns false
Any help highly appreciated
 
sona gold
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by mahesh deshpande:
Hello friends
Please help me to understand this
Byte b1 = new Byte("127");
if( b1.toString()== b1.toString()) //here two different objects are created and hence the output if false
System.out.println("True");
else
System.out.println("False");
The above code returns false
Where as
"String".toString() == "String".toString()// here both the left and right operands refer to once object as strings are immutable.
and hence return true
returns True
also
"String".toString()=="String";
returns True // again the same as above . If you had used new for the right hand side operand then it would return false but here it refers to the same string object which already exists
Another String related question
String S1 = new String( "amit");
String S3 = "arit";
String S2 = S1.replace('m','r');
System.out.println(S2==S3); // here s2 and s3 are two different string objects . hence == returns false. if u use equals here this will return true
This returns false
Any help highly appreciated

 
Boris Gertsberg
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
toString() method in the first example will create a new String object for each Byte object. Operator == compares references, that is why it returns false.Two objects in the memory.
In your second example you used "String". It would be kept inside of pool of Strings and reused every time compiler sees reference to that String. So both "String" objects actually the same object in the String pool and reference comparision will return true.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic