Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in String object

 
darshan karle
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Darshan,

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

Thanks
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm running this with eclipse (vs 1.4), it gives me "Not Equal".

(just info)
 
darshan karle
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

trim() method returns a new object,please check String class implementation in src.zip in java installation folder.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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 .
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 227
Eclipse IDE Java Spring
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic