aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toString() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toString() method" Watch "toString() method" New topic
Author

toString() method

mahesh deshpande
Greenhorn

Joined: Oct 26, 2000
Posts: 19
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

Joined: Feb 14, 2001
Posts: 234
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


sona<br />SCJP
Boris Gertsberg
Greenhorn

Joined: May 01, 2001
Posts: 1
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toString() method