Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string comparison is not working when concatenated with number

Tags:

java

My question to java folks is, when I am comparing two strings

imageName=new String[20];    
....    
imageName[1]="img1";  
imageName[2]="img1";  

if(imageName[1]==imageName[2])  
{  
 ////  codes  
}

it works perfectly, but when I am making the string through number concatenation it's not working

imageName=new String[20];  
int j=1,k=1;  
imageName[1]="img"+j;  
imageName[2]="img"+k;

 if(imageName[1].toString()==imageName[2].toString())     
        {  
           ////  codes  
        }  

it's not working though the values of j and k are the same

Thanks in advance for your solution

like image 804
user1595652 Avatar asked Nov 22 '25 16:11

user1595652


2 Answers

You should use String.equals when comparing two Strings:

if (imageName[1].equals(imageName[2])
like image 130
Dan W Avatar answered Nov 25 '25 05:11

Dan W


You shouldn't compare strings with ==, but instead use the .equals method: imageName[1].equals(imageName[2]).

== compares the pointers for equality, so it'll be true if both variables represent the exact same instance in memory. In the first case, it's the case because Java pools String literals for performance. But in your second case, you're getting two distinct heap-allocated objects, which, despite their content is identical, are two distinct objects nonetheless.

like image 27
Romain Avatar answered Nov 25 '25 04:11

Romain