Understanding Equality in Java: The == vs .equals() Debate

·

In Java, equality can be checked using == and .equals(). Understanding the difference is crucial. The == operator compares references, meaning it checks if two objects point to the same memory location. On the other hand, the .equals() method compares the actual content of objects.

For example, with primitive types like int, == compares values directly. But with objects like Strings, == compares references, and .equals() compares the content. Here’s an example:

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // false
System.out.println(str1.equals(str2)); // true
            

In this code, == returns false as both str1 and str2 point to different memory locations. However, .equals() returns true as the content of both Strings is the same. Knowing when to use each is key for writing correct Java programs.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *