Java – == operator VS equals() method | Code Factory


Index Page : Link

Donate : Link

Medium Link : Link

Applications : Link

String :

package com.example.string;

public class Test {
	public static void main(String... args) {
		String s1 = new String("Code Factory");
		String s2 = new String("Code Factory");
		System.out.println(s1 == s2); // false
		System.out.println(s1.equals(s2)); // true
	}
}

StringBuffer :

package com.example.string;

public class Test {
	public static void main(String... args) {
		StringBuffer sb1 = new StringBuffer("Code Factory");
		StringBuffer sb2 = new StringBuffer("Code Factory");
		System.out.println(sb1 == sb2); // false
		System.out.println(sb1.equals(sb2)); // false
	}
}

  • == Operator always meant for reference/address comparison
  • equals() method meant for content comparison but StringBuffer and StringBuilder not overridden equals() method, they use Object class‘s equals() method. So equals() method in StringBuffer and StringBuilder used for reference/address comparison.

Equality operator(==)

  • We can apply equality operators for every primitive types including boolean type. we can also apply equality operators for object types.
package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class Test {
	public static void main(String... strings) {
		// integer-type
		System.out.println(10 == 20);

		// char-type
		System.out.println('a' == 'b');

		// char and double type
		System.out.println('a' == 97.0);

		// boolean type
		System.out.println(true == true);
	}
}

Output:

false
false
true
true
  • If we apply == for object types then, there should be compatibility between arguments types (either child to parent or parent to child or same type). Otherwise we will get compile time error.
package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class Test {
	public static void main(String... strings) {
		Thread t = new Thread();
		Object o = new Object();
		String s = new String("GEEKS");

		System.out.println(t == o);
		System.out.println(o == s);

		// Uncomment to see error
		//System.out.println(t == s);
	}
}

Output:

false
false
//CE: Incompatible operand types Thread and String

One thought on “Java – == operator VS equals() method | Code Factory”

Leave a comment