Example & Tutorial understanding programming in easy ways.

Can we compare String using == operator? What is risk?

As discussed in previous String question, You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn't have corresponding primitive type and not participate in autoboxing. Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform character based comparison. equals() return true if two String points to same object or two String has same contents while == operator returns true if two String object points to same object but return false if two different String object contains same contents. That explains why sometime it works and sometime it doesn't. In short always use equals method in Java to check equality of two String object.

In the example below, two Java String objects are declared and initialized with the same string values and an if statement is used to determine if the strings are equivalent.

Example : (bad code)

String str1 = new String("Hello java");

String str2 = new String("Hello java");

if (str1 == str2) {

System.out.println("str1 == str2");

}

However, the if statement will not be executed as the strings are compared using the "==" operator. For Java objects, such as String objects, the "==" operator compares object references, not object values. While the two String objects above contain the same string values, they refer to different object references, so the System.out.println statement will not be executed. To compare object values, the previous code could be modified to use the equals method:
 

Example: (Good Code)

if (str1.equals(str2)) {

System.out.println("str1 equals str2");

}

Read More →