Click here to Skip to main content
15,896,915 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is the code::
String x="a";
    String xy=x+"b";
    String ab="ab";


As the strings got assigned with string literals and can be created in the string constant pool.
String x="a";  // "a" will be created in the constant pool referenced by x
    String xy=x+"b"; // this will be computed in Runtime and created in the constant pool with value as ab referenced by xy
    String ab="ab";  //this will be created in the constant pool referenced by ab


but while executing System.out.println(xy==ab) it is returning as false.
As both of them("ab") are created in the string constant pool which in turn should return true.Am i missing anything?

What I have tried:

my understanding is that when ever a string is to be created it should go and first check in the string constant pool if not exists it will create the string else it will give the reference of the existing string.
Posted
Updated 24-Nov-17 1:56am

Quote:
Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
-- Strings (The Java™ Tutorials)[^] => xy and ab are of two different string objects.
Next,
== checks for reference equality (pointing to the same object)[^] => ab==xy returns false.
For value equality check, go for
.equals()
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 24-Nov-17 10:42am    
5ed. This is the solution.
Quote:
String xy=x+"b"; // this will be computed in Runtime and created in the constant pool with value as ab referenced by xy
The above remark is incorrect. The concatenation operator creates a new string object.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900