This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Behaviour of + in case of String literals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Behaviour of + in case of String literals" Watch "Behaviour of + in case of String literals" New topic
Author

Behaviour of + in case of String literals

Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
Hi! Every body ,
can anybody please explain the reason behind the following behaviour in case of String literals

String s1="Hello"
if(s1=="He"+"llo") System.out.println("equals");
else
System.out.println("not equals");
Prints TRUE


String s1="Hello"
String s2="He";
String s3="llo"
if(s1=s2+s3) System.out.println("equals");
else
System.out.println("not equals");
Prints not equals

Please clarify .
Thanks in advance

Jolly
Anoobkumar Padmanabhan
Ranch Hand

Joined: Aug 08, 2007
Posts: 103
Hi

Are you familiar with teh difference between "==" and .equals method and the String pool concept?

In you example, the operation is ==. ie, you just comparing the references. since you has given
String s1="Hello",
it will take a String "Hello" from the String pool and returns the refence to that String only.

In the first comaprison, you comapre it with another String in pool, "He"+"llo", which will give the same String object, and returns a true.

In the second case, you compare the SAString with the resultant object of a String manipulation,+. it will conacatenate a String object and return another object, that is newly created, not simply returns a refernce from pool. so th operation will return false.


For more clarrification, please do the function with
String s1=new String("Hello");
Then both the comparisons will return false.

Or try with .equals, other than ==. then the comaprisons will return true.
[ September 22, 2008: Message edited by: anoobkumar padmanabhan ]

Thanks<br /> <br />Anoobkumar<br />SCJP 1.5
Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
Hi! Anoob,

Thanks for the reply.
Actually i am pretty comfortable with == and equals().

But the thing which needs clarification is in the behaviour of == in String literals.

if(s1=="He"+"llo") System.out.println("equals");

As the resulting string after concatenation is the same as already present in the literal pool .so the resulting string starts referring to the same s1 String.

But why is this not applicable to the next code snippet

String s1="Hello"
String s2="He";
String s3="llo"
if(s1==s2+s3) System.out.println("equals");

Please clarify

Regards
Jolly
Anoobkumar Padmanabhan
Ranch Hand

Joined: Aug 08, 2007
Posts: 103
Hi

the statement, s1==s2+s3, will operate on two string object and create a new String object. it wont simply returns the refernce of the same string from the pool. thats y the comparison fails in this case.
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

This is what happens,
When you perform "he" + "llo", a new String literal is created and stored in the String Pool and not on the heap.

so when you perform s1=="he"+"llo" it returns true.

In the second case,

s2+s3 creates a new object on the Heap.

and == operator checks for References and not the value. So the second if prints not equal.

If you want to check whether the String Objects are meaningfully equal then use equals() method. The equals method has been overloaded in String class such that

s1 = new String("Hi");
s2 = new String("Hi");

s1.equals(s2) --This will print True.


Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
Hi! ,


It means that when we are using + with String literals directly ("ab"+"c"),resulting String is created in the literal pool not on HEAP

while in case of using + to concatenate references to String literals
resulting String will be created on the HEAP

please correct me if i am wrong

Regards

Jolly
vidhya suvarna
Ranch Hand

Joined: Aug 28, 2008
Posts: 148
Jolly, i too had a similar doubt and came across the thread posted by you.

anoobkumar, in the below code
String s="String".replace('t','T'); //1
String s1="String".replace('t','T');//2
(s == s1) --> returns false

is it true that replace() will create a new String object? But line 1&2 makes s1&s refer to that object so in that case wont s==s1 be true..

kindly help!!
[ September 22, 2008: Message edited by: vidhya suvarna ]

SCJP 1.4 - 88%<br />SCWCD 1.5 - Preparing
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

Consider this case

String str = "Hello"; //1
String str1 = new String("Hi"); //2

This is what happens. In Case 1, a String Literal "Hello" is created and stored in the pool. And str points to this Literal in the pool.

In case 2, a String Literal "Hi" is created in the pool, and also One Object is Created on the heap.
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
Originally posted by vidhya suvarna:

String s="String".replace('t','T'); //1
String s1="String".replace('t','T');//2
(s == s1) --> returns false

is it true that replace() will create a new String object? But line 1&2 makes s1&s refer to that object so in that case wont s==s1 be true..

kindly help!!

[ September 22, 2008: Message edited by: vidhya suvarna ]



String.replace(char,char) returns a new String reference. the original String stays the same as String is immutable. Hence you get 'false' on comparing.


Thanks and Regards
vidhya suvarna
Ranch Hand

Joined: Aug 28, 2008
Posts: 148
Thanks Satya.
Santhi Bharath
Ranch Hand

Joined: Jun 03, 2008
Posts: 75
you can find more here

http://www.coderanch.com/t/270217/java-programmer-SCJP/certification/equals-method-operator


thanks and regards<br />Santhi Bharath<br />SCJP 5.0, SCWCD 5.0
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18139
    
  39

Originally posted by Jolly tiw:
Hi! Every body ,
can anybody please explain the reason behind the following behaviour in case of String literals

Please clarify .


First of all, keep in mind that you should not depend on this -- it is *not* in the specification whether the compiler should (specifically should not) place something into the pool.

Anyway, in the first case, the compiler is able to calculate the resultant string during compile time, and hence, treat the assignment as a straight assignment to a string literal. (with the result)

In the second case, the compiler is not able to do so, because the strings are not compile time constants. Hence, the string must be calculated during runtime, which doesn't intern the string (by default).

BTW, for the second case, if the two strings were final, then the compiler is able to calculate the resultant string, as it is a compile time constant, and you will get "equals".

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anoobkumar Padmanabhan
Ranch Hand

Joined: Aug 08, 2007
Posts: 103
Hi vidhya suvarna

As in you code,
String s="String".replace('t','T'); //1
String s1="String".replace('t','T');//2

Keep in mind that a string operation will result ina String object, not a simple literal. this is the answer for your question. ie, here you will get two String objects, refernced by s and s1. so the operation, s==s1 will certainly result in false.
vidhya suvarna
Ranch Hand

Joined: Aug 28, 2008
Posts: 148
Thanks anoob that does answer my query.
Anjani Pandey
Greenhorn

Joined: May 04, 2013
Posts: 1



String str = "Hello"; //1
String str1 = new String("Hi"); //2

This is what happens. In Case 1, a String Literal "Hello" is created and stored in the pool. And str points to this Literal in the pool.

chander shivdasani wrote:Consider this case In case 2, a String Literal "Hi" is created in the pool, and also One Object is Created on the heap.

I am having some doubt In case 2, if String Literal "Hi" is created in the pool as well then reference variable str1 will refer to string object in heap or string literal in the pool?
Sivakumar P Annamalai
Greenhorn

Joined: Jun 14, 2013
Posts: 2

In the first case a String literal is created on the pool, so the condition evaluates to true.

In the second case a new String object is created on the heap, so the condition evaluates to false.
Elier Rguez
Greenhorn

Joined: Jun 27, 2013
Posts: 22
Maybe this piece of code can clarify some doubts. It looks that when you create a String in runtime (String str7 = "Hel"+ s), it creates automatly a new String object instead of a reference to a String in the pool. Am I right?



Output:

str7 is computed at runtime.
str8 is created by using string constant expression.
str7 == str8 is false
str7.equals(str8) is true
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Behaviour of + in case of String literals
 
Similar Threads
String(==)
Question on Strings and String pool
Equality Operator "=="
String problem
String.valueOf()