13,667,388 members
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 24-Nov-17 1:12am
Updated 24-Nov-17 1:56am

## Solution 1

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.

## Solution 2

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()`

5ed. This is the solution.

Top Experts
Last 24hrsThis month
 ppolymorphe 205 OriginalGriff 175 Jochen Arndt 165 Richard MacCutchan 110 Graeme_Grant 60
 OriginalGriff 4,227 ppolymorphe 1,802 Richard MacCutchan 1,720 Jochen Arndt 1,467 Dave Kreskowiak 853