Friday, 22 April 2016

java - Why String Pool behaves differently for literals and variables?

When I concat 2 strings with (+) operator using double quotes and compare with other string literal with same value it result as true .. but when I concat 2 string variables and compare gives false ? why this happens ?



As per my knowledge when we concat strings with (+) operator JVM returns new StringBuilder(string...).toString() which creates a new String instance in heap memory and one reference in String pool . if that is true how is it returning true in one scenario and false in other?



1st scenario :



    String string1 = "wel";

String string2 = "come";
string1 = string1 + string2; //welcome

String string3 = "welcome";
System.out.println(string3 == string1); // this returns false but have same hashcode


2nd scenario :



    String string4 = "wel" + "come";

String string5 = "wel" + "come";
System.out.println(string4 == string5); // this returns true


Can someone help me on this ?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...