Calculator Interactive Good Links
 Calculator Interactive Good Links

# String Equality

## Some surprises for string equality

Many programmers are sometimes suprised by Java's behavior re: string equality

### Example 1

Run the following code to see for yourself
```public static  void main(String[] args) {
String s0="a";
String s1 ="a";
String s2 ="b";
String s3 ="ab";
if((s1 + s2)==s3){
System.out.println("s1+s2 = s3");}

else{ System.out.println((s1+s2) +" does not equal " +s3);}
if(s1 == s2){
System.out.println(s1+" = " +s2);}
else if(s1 != s2)
System.out.println(s1+" != " +s2);

if(s1 == s0){
System.out.println("s1 = s0");}
else if(s1 != s0)
System.out.println("s1 != s0");
}

```

#### Example: concatating strings and string equality

```public static  void main(String[] args) {
String str1= "A";
String str2 ="B";
String str3 = "AB";
System.out.println("str1 = "+str1);
System.out.println("str2 = "+str2);
System.out.println("str3 = "+str3);
System.out.println("******assing str1+= str2 ******");
str1+= str2;
System.out.println(" now str1 = "+str1);
if(str3 == str1){System.out.println("str3 =str1");}
else{System.out.println("str3 !=str1");}
}

```
OUTPUT IS
```str1 = A
str2 = B
str3 = AB
******assing str1+= str2 ******
now str1 = AB
str3 !=str1```
The problem is that both strings, str1 & str3, refer to different string objects. And although both of these objects have the same letters, they are not the same object and therefore the comparison above does not work
##### string.equals to the rescue!
The program below changes only one line!
```public static  void main(String[] args) {
String str1= "A";
String str2 ="B";
String str3 = "AB";
System.out.println("str1 = "+str1);
System.out.println("str2 = "+str2);
System.out.println("str3 = "+str3);
System.out.println("******assing str1+= str2 ******");
str1+= str2;
System.out.println(" now str1 = "+str1);
if(str3.equals(str1))
{System.out.println("str3 =str1");}
else{System.out.println("str3 !=str1");}
}

}```
OUTPUT
```str1 = A
str2 = B
str3 = AB
******assing str1+= str2 ******
now str1 = AB
str3 =str1```