*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String doubt 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 "String doubt" Watch "String doubt" New topic
Author

String doubt

Sajid Moinuddin
Ranch Hand

Joined: Mar 19, 2005
Posts: 85
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

Joined: Dec 31, 2004
Posts: 961
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

Joined: Sep 17, 2004
Posts: 123
Here JVM is creating two different string objects that's why == is returning flase.


SCWCD 1.4, SCJP 1.4
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[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 ]

"I'm not back." - Bill Harding, Twister
Bhalotia Kunal
Greenhorn

Joined: May 16, 2005
Posts: 9
what is the intern keyword mean here.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
intern() is not a keyword - it's defined in the String API.
Sajid Moinuddin
Ranch Hand

Joined: Mar 19, 2005
Posts: 85
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

Joined: Nov 15, 2004
Posts: 1026


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.


Servlet Spec 2.4/ Jsp Spec 2.0/ JSTL Spec 1.1 - JSTL Tag Documentation
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String doubt
 
Similar Threads
Why is this output ??
toString() Method
object Reference Equality
==, why is it so ?
== comparison