• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String doubt

 
Sajid Moinuddin
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Byte b=new Byte("124");
System.out.println(b.toString()==b.toString());

why does it prints false when
"124"=="124" gives true??!!! i mean b.toString() should come as a string literal...!!
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the same reason this is not true


Obviously new strings are been created at toString method.

Try this and you will see:


[ May 17, 2005: Message edited by: Edwin Dalorzo ]
[ May 17, 2005: Message edited by: Edwin Dalorzo ]
 
Rohan Kayan
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here JVM is creating two different string objects that's why == is returning flase.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Sajid]: i mean b.toString() should come as a string literal...!!

According to what? There was a literal involved in the construction of the Byte, but nothing says that toString() must return the same object. In fact a careful reading of the API tells is this is not allowed - toString) is required to return a new String object here. (That was probably unnecessary and even wrong for Sun to specify in the API, but it's done, and hard for Sun to change after it's been released.)
[ May 17, 2005: Message edited by: Jim Yingst ]
 
Bhalotia Kunal
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the intern keyword mean here.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
intern() is not a keyword - it's defined in the String API.
 
Sajid Moinuddin
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it...
String str1=new String("123");
String str2=new String("123");
System.out.println(str1==str2);

this prints false...i didn't know toString() also returns a new object... is there any easy way by which i can determine when strings are taken from string pool and when they are created??
sajid
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Is it because m and n get their values at runtime String objects m
and n are not placed in String Literal Pool. When intern() method is
called on them they are checked against the pool if the value is not
available then they are added to it and checked against them again and
returns true.

Am I correct here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic