Click here to Skip to main content
13,768,845 members
Rate this:
 
Please Sign up or sign in to vote.
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 2:12am
Updated 24-Nov-17 2:56am
Rate this: bad
 
good
Please Sign up or sign in to vote.

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.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

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()
  Permalink  
Comments
Afzaal Ahmad Zeeshan 24-Nov-17 10:42am
   
5ed. This is the solution.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01-2016 | 2.8.181116.1 | Last Updated 24 Nov 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100