devxlogo

Use Object.equals(), not ==, for Logical Comparison

Use Object.equals(), not ==, for Logical Comparison

One of the most common gotchas for beginning Java programmers involves comparing Objects, especially Strings, with the == operator. Every Object in Java has a unique location in the Java Virtual Machine’s memory. The == operator returns true if the two handles on the left and right sides refer to the same location in memory. The function Object.equals() is intended to return true if two handles refer to logically equivalent instances. In the most basic case, this function works by comparing the value of each of the data fields of the two instances and returning true only if they’re all equivalent. You should override Object.equals() in your own classes to provide more robust logic:

 public class StringCompare{	public static void main(String[] args){		If(args[0] == "test"){			System.out.println(args[0] + " == "test"");		}else{			System.out.println(args[0] + " != "test"");		}		if(args[0].equals("test")){			System.out.println(				args[0] + ".equals("test") == true");		}else{			System.out.println(				args[0] + ".equals("test") == false");		}	}} 
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist