Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String.valueOf()

 
Binu K Idicula
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I ve a one doubt regarding this method
public static void main(String args[]){
System.out.println(String.valueOf(1234) ==String.valueOf(1234));
System.out.println(String.valueOf("1234")==String.valueOf("1234"));
}
will print
false
true.
It seems when it is primitive value , a new string is created and if its a string(actually Object) , its toString method is invoked which returns the reference to actual string . Is this the reason why it prints the above ?
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it is
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This example helps convince one not to use "==" to
compare Strings. If the equals() method was used we would get two times true.

-Barry
[ August 09, 2002: Message edited by: Barry Gaunt ]
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, it is important to know for the exam:
String s1 = "hello";
String s2 = "hello";
System.out.println (s1==s2);
// prints true; all identical string literals are ==
String s3 = s2.toString();
System.out.println (s2==s3);
//prints true; String.toString() returns the string itself
On the other hand
String s4 = "hello";
String s5 = new String("hello");
System.out.println (s4==s5);
// prints false; s2 is not a literal
 
John Sun
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Binu K Idicula:
Hi,
I ve a one doubt regarding this method
public static void main(String args[]){
System.out.println(String.valueOf(1234) ==String.valueOf(1234));
System.out.println(String.valueOf("1234")==String.valueOf("1234"));
}
will print
false
true.
It seems when it is primitive value , a new string is created and if its a string(actually Object) , its toString method is invoked which returns the reference to actual string . Is this the reason why it prints the above ?

Also it maybe helpful to recognize that the calls made using the Object-parameter version passes in references to the same String object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic