String concatenation ambiguity











up vote
0
down vote

favorite












I have the following simple piece of java code where I am trying to understand how string concatenation in java works using '+' operator.



public class Problem {

public static void main(String... args){

String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object

System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false

}
}


str4 is the resultant of 2 string literals (ab and c) and str5 is of references to the 2 string literals (str2 and str3). In both the cases, java will be calling StringBuilder class to perform the concatenation.



And I believe it should result in creating 2 different StringBuilder objects in java heap space.



If my understanding is correct, why str1 == str4 returns true ? Can some one please help in getting this clear to me ?



Regards,
Maneesh Sharma










share|improve this question
























  • Possible duplicate of What is the difference between “text” and new String(“text”)?.
    – Tim Biegeleisen
    Nov 11 at 3:37















up vote
0
down vote

favorite












I have the following simple piece of java code where I am trying to understand how string concatenation in java works using '+' operator.



public class Problem {

public static void main(String... args){

String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object

System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false

}
}


str4 is the resultant of 2 string literals (ab and c) and str5 is of references to the 2 string literals (str2 and str3). In both the cases, java will be calling StringBuilder class to perform the concatenation.



And I believe it should result in creating 2 different StringBuilder objects in java heap space.



If my understanding is correct, why str1 == str4 returns true ? Can some one please help in getting this clear to me ?



Regards,
Maneesh Sharma










share|improve this question
























  • Possible duplicate of What is the difference between “text” and new String(“text”)?.
    – Tim Biegeleisen
    Nov 11 at 3:37













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have the following simple piece of java code where I am trying to understand how string concatenation in java works using '+' operator.



public class Problem {

public static void main(String... args){

String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object

System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false

}
}


str4 is the resultant of 2 string literals (ab and c) and str5 is of references to the 2 string literals (str2 and str3). In both the cases, java will be calling StringBuilder class to perform the concatenation.



And I believe it should result in creating 2 different StringBuilder objects in java heap space.



If my understanding is correct, why str1 == str4 returns true ? Can some one please help in getting this clear to me ?



Regards,
Maneesh Sharma










share|improve this question















I have the following simple piece of java code where I am trying to understand how string concatenation in java works using '+' operator.



public class Problem {

public static void main(String... args){

String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object

System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false

}
}


str4 is the resultant of 2 string literals (ab and c) and str5 is of references to the 2 string literals (str2 and str3). In both the cases, java will be calling StringBuilder class to perform the concatenation.



And I believe it should result in creating 2 different StringBuilder objects in java heap space.



If my understanding is correct, why str1 == str4 returns true ? Can some one please help in getting this clear to me ?



Regards,
Maneesh Sharma







string concatenation string-literals






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 8:34









marc_s

566k12610921245




566k12610921245










asked Nov 11 at 3:12









Maneesh

448




448












  • Possible duplicate of What is the difference between “text” and new String(“text”)?.
    – Tim Biegeleisen
    Nov 11 at 3:37


















  • Possible duplicate of What is the difference between “text” and new String(“text”)?.
    – Tim Biegeleisen
    Nov 11 at 3:37
















Possible duplicate of What is the difference between “text” and new String(“text”)?.
– Tim Biegeleisen
Nov 11 at 3:37




Possible duplicate of What is the difference between “text” and new String(“text”)?.
– Tim Biegeleisen
Nov 11 at 3:37












1 Answer
1






active

oldest

votes

















up vote
0
down vote













It depends on how the compiler and jvm will optimize this. Only if both variables are optimized to point to the same adress, the evaluation will be true. In general, using == to compare strings is not reliable. Use the 'equals' method instead.






share|improve this answer





















  • So the output of the above program may differ for different JVMs, is that correct ?
    – Maneesh
    Nov 11 at 11:32










  • I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
    – Pascal Ludwig
    Nov 11 at 12:30






  • 1




    One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
    – Pascal Ludwig
    Nov 11 at 12:32












  • Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
    – Maneesh
    Nov 11 at 13:25










  • While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
    – Maneesh
    Nov 12 at 8:36











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245535%2fstring-concatenation-ambiguity%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













It depends on how the compiler and jvm will optimize this. Only if both variables are optimized to point to the same adress, the evaluation will be true. In general, using == to compare strings is not reliable. Use the 'equals' method instead.






share|improve this answer





















  • So the output of the above program may differ for different JVMs, is that correct ?
    – Maneesh
    Nov 11 at 11:32










  • I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
    – Pascal Ludwig
    Nov 11 at 12:30






  • 1




    One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
    – Pascal Ludwig
    Nov 11 at 12:32












  • Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
    – Maneesh
    Nov 11 at 13:25










  • While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
    – Maneesh
    Nov 12 at 8:36















up vote
0
down vote













It depends on how the compiler and jvm will optimize this. Only if both variables are optimized to point to the same adress, the evaluation will be true. In general, using == to compare strings is not reliable. Use the 'equals' method instead.






share|improve this answer





















  • So the output of the above program may differ for different JVMs, is that correct ?
    – Maneesh
    Nov 11 at 11:32










  • I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
    – Pascal Ludwig
    Nov 11 at 12:30






  • 1




    One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
    – Pascal Ludwig
    Nov 11 at 12:32












  • Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
    – Maneesh
    Nov 11 at 13:25










  • While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
    – Maneesh
    Nov 12 at 8:36













up vote
0
down vote










up vote
0
down vote









It depends on how the compiler and jvm will optimize this. Only if both variables are optimized to point to the same adress, the evaluation will be true. In general, using == to compare strings is not reliable. Use the 'equals' method instead.






share|improve this answer












It depends on how the compiler and jvm will optimize this. Only if both variables are optimized to point to the same adress, the evaluation will be true. In general, using == to compare strings is not reliable. Use the 'equals' method instead.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 at 3:20









Pascal Ludwig

6311614




6311614












  • So the output of the above program may differ for different JVMs, is that correct ?
    – Maneesh
    Nov 11 at 11:32










  • I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
    – Pascal Ludwig
    Nov 11 at 12:30






  • 1




    One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
    – Pascal Ludwig
    Nov 11 at 12:32












  • Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
    – Maneesh
    Nov 11 at 13:25










  • While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
    – Maneesh
    Nov 12 at 8:36


















  • So the output of the above program may differ for different JVMs, is that correct ?
    – Maneesh
    Nov 11 at 11:32










  • I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
    – Pascal Ludwig
    Nov 11 at 12:30






  • 1




    One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
    – Pascal Ludwig
    Nov 11 at 12:32












  • Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
    – Maneesh
    Nov 11 at 13:25










  • While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
    – Maneesh
    Nov 12 at 8:36
















So the output of the above program may differ for different JVMs, is that correct ?
– Maneesh
Nov 11 at 11:32




So the output of the above program may differ for different JVMs, is that correct ?
– Maneesh
Nov 11 at 11:32












I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
– Pascal Ludwig
Nov 11 at 12:30




I'm not 100% sure about the specification for this. But in practice, yes. The address of new variables should be treated as nondeterministic.
– Pascal Ludwig
Nov 11 at 12:30




1




1




One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
– Pascal Ludwig
Nov 11 at 12:32






One more note: The jvm may optimize immutable objects (especially strings) by pointing their variables to the same address. But you don't have control over that. Also, I imagine searching the occupied address space for an equal object is expensive. I don't know in which cases it could do these optimizations.
– Pascal Ludwig
Nov 11 at 12:32














Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
– Maneesh
Nov 11 at 13:25




Thank you Pascal for the additional info ! I am still wondering if I am given the above problem as an objective question, what my guess should be ? If I go by the explanations so far I came across how string concatenation works, my answer would be false for str1 == str4 but is not the case :) !
– Maneesh
Nov 11 at 13:25












While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
– Maneesh
Nov 12 at 8:36




While browsing I found an article in stackoverflow where one of the comments mentioned the following.. if you simply write "ab" + "c", Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time. If any of the strings is a variable and cann't be determined by compiler, it will have a different resultant hash code
– Maneesh
Nov 12 at 8:36


















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245535%2fstring-concatenation-ambiguity%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine