== operator return true when I am comparing two string of same content but difference is of lower and upper case | Core Java Forum
V
Vikrant Posted on 14/07/2021

Hi Yogesh,

I have taken two string data type and passed the same content in two data type except there is difference of lower case in one string but

When I am comparsing two string then still == operator returning a true.

Can you explain me how comparison will works with == operators?


Y
Yogesh Chawla Replied on 15/07/2021

Hi Vikrant,

As discussed in the class, When we compare two strings using == operator, it returns true if both the string variables points toward the same java object otherwise it returns false and when we change the case in one of the String, the content differs and both == and equals returns false in that scenario unless and until we don't use equalsIgnoreCase()

Run this:

public class EqualsMethod {

public static void main(String[] args) {

String str1 = "ABC";
String str2 = "AbC";

if(str1 == str2) {
System.out.println("== works");
}else {
System.out.println("== does not work");
}

if(str1.equals(str2)) {
System.out.println("equals works");
}else {
System.out.println("equals does not work");
}

String str3 = new String("ABC");
String str4 = new String("ABC");

if(str3 == str4) {
System.out.println("== works");
}else {
System.out.println("== does not work");
}

if(str3.equals(str4)) {
System.out.println("equals works");
}else {
System.out.println("equals does not work");
}

}
}