It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in String object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in String object" Watch "doubt in String object" New topic
Author

doubt in String object

darshan karle
Greenhorn

Joined: May 09, 2008
Posts: 28
hi all,

i got this question from the site:http://www.angelfire.com/or/abhilash/Main.html. i am pasting the question below

if(" String ".trim() == "String")

System.out.println("Equal");

else

System.out.println("Not Equal");


can any body tell me why it is printing "Not Equal". i thought it should print "Equals" because in the left side one String object is created immediately i am applying trim on it.in the right side another object is created with the same value.as per my knowledge String objects are created in String pool.java is smart enough that if it finds two string literal with same name it will create one String object and pass same reference to both variables.but why it is printing false. please comment on this.

regards
darshan
SaurabhSri Sri
Ranch Hand

Joined: May 01, 2008
Posts: 43
Hi Darshan,

Did you run this stuff at your end. If not, please do run. Its giving me "Equal" in output.

Thanks


Regards
SaurabhSri (SCJP 1.5)
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
I'm running this with eclipse (vs 1.4), it gives me "Not Equal".

(just info)


Java hobbyist.
darshan karle
Greenhorn

Joined: May 09, 2008
Posts: 28
hi sri,

for me it is giving "Not Equals". Observe the If statement carefully.
in the first literal there is a space inside double quote.

regards
darshan
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

Hi,

trim() method returns a new object,please check String class implementation in src.zip in java installation folder.


SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1



The string literals are never matched with == operator , there are two methods for this

String#equals()
String#eqaulsIgnorecase() [see doc]

When you check string equality thru this == op , this simply checks for bit pattern , not the contents !!

Hope this clarifies the things .


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

What you check is for the object reference equality through "==" operator. The trim() works perfectly as there are spaces to trim and as a result trim calls the "substring()" method which intern returns a new string. That's the reason you get two different Strings and they are NOT equal!


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
Originally posted by Sagar Rohankar:


The string literals are never matched with == operator , there are two methods for this

String#equals()
String#eqaulsIgnorecase() [see doc]

When you check string equality thru this == op , this simply checks for bit pattern , not the contents !!

Hope this clarifies the things .


This question is not about equality of the content of the strings, but moreso about how Java treats strings in memory.



This prints true.

It's looking like trim() allocates the returned string object with new. Is there anyway we can verify this? How can we get an overview of the constant pool?
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Hi Sagar,
Is it advised not to compare String literals with = =.
Any if below code gives true


Then what is wrong with issue posted by Darshan?
Can you be bit precise regarding your suggestion.


Thanks & Regards
Sidharth Pallai
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
Originally posted by Sidharth Pallai:
Hi Sagar,
Is it advised not to compare String literals with = =.
Any if below code gives true


Then what is wrong with issue posted by Darshan?
Can you be bit precise regarding your suggestion.


For real world issues, you really really should compare strings with the equals() method, unless you intentionally want to compare references and not string content.

Comparing string content using the == operator is not the way to go.

Consider:



This prints "false", while the string content is true, for example, because a and b refer to explicitly allocated different objects.
darshan karle
Greenhorn

Joined: May 09, 2008
Posts: 28
hi all,
some people are going out of track.here i am not checking the content of the string.i want to know why more than one object is created.in the left side as ramesh told after creating string object trim is applied .since string is immutable new object is created.now string object contain value without space.
in the right side again i am creating string literal and comparing with left side literal.right side literal has same value as left side.as per my knowledge if two string literal have same value then there is only one object exist. why two objects exist here.....???

regards
darshan
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by Ronald Schild:

This prints "false", while the string content is true, for example, because a and b refer to explicitly allocated different objects.


That's because of the explicit invocation of 'new' in both the statements.
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Hi Ronald,
Your code must print false, because you have created two separate String objects that refer to different allocations that everyone knows would return false when compared with ==.
Though == comparision is not a real world approach,but i wish to know the consequences of it when compared to the way the post is concerned about.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by darshan karle:
hi all,
as per my knowledge if two string literal have same value then there is only one object exist. why two objects exist here.....???



That's true. It is because one object is getting created dynamically at runtime due to trim(). But the other literal "String" is created during the compile time itself.

Does that help?
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by Sidharth Pallai:

Though == comparision is not a real world approach,but i wish to know the consequences of it when compared to the way the post is concerned about.


Yes, the strings are in general compared for their content equivalent rather than their reference equivalent. That's why they say better to compare with equals() method rather than equals operator (==).

The post is actually concerned about whether invoking the trim() method would return a new object or not. That decides the output! The same holds good with most of the methods in String, StringBuffer classes. Have a careful look at substring() method for example.
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Thank you Raghavan,
Am totaly agreed with you. Java sources clearly says about it, "Methods like trim() and toLowerCase() always return new string objects to use; they never change the receiver string object (this is the core of "immutable" style -- the receiver object never changes).
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by Sidharth Pallai:
"Methods like trim() and toLowerCase() always return new string objects to use;


Not always Sidharth. Be careful. That's what i have asked you to carefully look at the substring() for example.

Try running the following code snippet for a better understanding.



The output what you should be getting is :

darshan karle
Greenhorn

Joined: May 09, 2008
Posts: 28
raghav please not no object is created at compile time and i think i got answer for the question.and i agree with ronald.

see trim implicitly calling substring() method .i checked substring() source code.in IF condition if the condition fails they are creating NEW object from the heap using new keyword not in the string pool .so in the left side i got a object from the heep. and in the right side object is created in string poll.so in the pool there is only one object with value "string".thats why it is returning false and printing "NotEqual".

please comment on this

regards
darshan
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by darshan karle:
raghav please not no object is created at compile time and i think i got answer for the question.and i agree with ronald.



That's true dharshan. What i meant to say was "an entry was placed in the String Literal Pool during the compile time itself". It holds good for all String literals being enclosed within double quotes!
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
Originally posted by Raghavan Muthu:


That's because of the explicit invocation of 'new' in both the statements.


That's what I was explaining in my post.

I was giving this example to point out that equals() is preferred over == when comparing string content, because someone asked what was wrong with using ==.

Now, I still have a bit of wishy/washy feeling when reading the API specs of the String class. I know trim() states a new object is created. But new string objects are almost always created when working with string manipulation as strings are immutable. The API does not explicitly state how the new object is allocated.



A new string object is created at line 2. But not in a way line 3 allocates the object. My issue here is that I want to know _exactly_ how string methods allocate their new strings. Is it safe to assume that when the API mentions a new object, it is allocated with new?

Fun:



After line 2 has executed, a string object with the content "Hello" is eligible for garbage collection.

After line 3 has executed, 6 or 7 string objects exist, of which 4 are referenced from the string constant pool. One string object with the content "Hello World!" is eligible for garbage collection.

After line 4 has executed, another string with the content "Hello World!" is eligible for garbage collection. No other strings are eligible for garbage collection.

Am I wrong?
[ June 26, 2008: Message edited by: Ronald Schild ]
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

After line 2 has executed, a string object with the content "Hello" is eligible for garbage collection.


No , they are returned to String constant pool .

One string object with the content "Hello World!" is eligible for garbage collection.


Only after execution of line 4.. , a referenced sting is returned to String pool and String object (created with "new" ) b, is eligible for GC..
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117


So you are saying that trim() does not allocate a string object in a way that it is not refereced by the string constant pool, but that it is in the SCP but without the rules applying that such references point to similar objects if the content is similar?

Can you explain to us then why:



Prints false, if the object allocated by the trim() is in the SCP?


Only after execution of line 4.. , a referenced sting is returned to String pool and String object (created with "new" ) b, is eligible for GC..


edited: last post explains behaviour.
[ June 27, 2008: Message edited by: Ronald Schild ]
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
Well,



gives false. I'm confused, why can there be multiple string objects with equal contant in the string constant pool?
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
Here we go

http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101083

3.10.5 String Literals

Gives the answers.

The answer to the original question:

hi all,

i got this question from the site:http://www.angelfire.com/or/abhilash/Main.html. i am pasting the question below

if(" String ".trim() == "String")

System.out.println("Equal");

else

System.out.println("Not Equal");


Prints "Not Equal" because:

Strings computed by concatenation at run time are newly created and therefore distinct.


While



prints true, because

Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
Sandeep Bhandari
Ranch Hand

Joined: Apr 16, 2004
Posts: 201
i would make it more interesting by using

if("String".trim() == "String")
System.out.println("Equals");
else
System.out.println("Not Equals");


What will be the result??


SCJP 96% | SCWCD 90%| SCJP mock exams | My SCJP blog
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

see Raghavan Muthu`s
ranch hand
Member # 122810

posted Thursday, June 26, 2008 6:21 PM

reply in the same discussion !
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

Hi,

This might help...

http://www.coderanch.com/t/268550/java-programmer-SCJP/certification/difference-between-Creating-String-object

Best regards,

- Aditya Jha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in String object
 
Similar Threads
The " == " sign is confusing....
strings
string obj confusion
explain this string method..
Java Strings