Sunday, October 28, 2018

String compare java

.equals() method is used to compare Strings is Java.

String in java are immutable. whenever we try to modify the string you get a new instance. We cannot change the original string object

 This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.

When using == operator for string comparison we are not comparing the contents of the string but are actually comparing the memory address of the string objects, if they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.

== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").


Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().


public class StringCompare {
	public static void main(String[] args) {
		// These two have the same value
		System.out.println(new String("test").equals("test")); 
                // --> true
		// ... but they are not the same object
		System.out.println(new String("test") == "test");
                // --> false
		
		// ... but these are because literals are interned by
		// the compiler and thus refer to the same object
		System.out.println("test" == "test"); // --> true
		// checks for nulls and calls .equals()
		System.out.println(Objects.equals("test", new String("test"))); 
               // --> true
		System.out.println(Objects.equals(null, "test")); // --> false
	}

}


Output:
true
false
true
true
false
== handles null strings fine, but calling .equals() from a null string will cause an exception:

No comments:

Post a Comment