Category: String

Comparing Strings in Java

How to compare two Strings in Java?

To compare two Strings in Java use the .equals() method of the String Class.
Don’t use == to compare Strings, you might get unexpected results.

String hello  = "Hello";
String hello2 = "Hello";
String hello3 = new String("Hello");
String world  = "World";
		
//Objects default hashCode
System.out.println( System.identityHashCode(hello)   );     //366712642
System.out.println( System.identityHashCode(hello2)  );     //366712642
System.out.println( System.identityHashCode(hello3)  );     //1829164700
System.out.println( System.identityHashCode("Hello") );     //366712642
System.out.println( System.identityHashCode("World") );     //2018699554

//Comparing with .equals 
// .equals method compares the actual string characters
System.out.println(  "Hello".equals(hello)   );     //true 
System.out.println(  hello.equals(hello2)    );     //true
System.out.println(  hello.equals(hello3)    );     //true
System.out.println(  hello.equals(world)     );     //false
System.out.println(  "Hello".equals("World") );     //false

//comparing with ==
// == compares the reference values
System.out.println(  hello == hello2     );    //true
System.out.println(  hello == hello      );    //true
System.out.println(  hello == hello3     );    //false
System.out.println(  hello == "Hello"    );    //true
System.out.println(  "Hello" == "Hello"  );    //true

The .equals() method is case sensitive, whereas the .equalsIgnoreCase() is not case sensitive.

//Case Sensitive
System.out.println( "Hello World".equals("hELlo WOrlD")            );    //false
//Case Insensitive 
System.out.println( "Hello World".equalsIgnoreCase("hELlo WOrlD")  );    //true
Filed under: Java, StringTagged with: ,