Skip to main content

How Equals and == Works in Java

The "Object" Class in Java provides a method with name "equals" which is used to test if two objects are equal. And the "==" is a operator. This operator when used for primitives, returns true if two primitive values are equal. And for Object references, this "==" operator returns true when they are referring to the same object.

The object "Object" which all other Java objects extend has an equals method which allows you to check to see if two objects are equal, which means you call equals on any object you want. Objet's implementation of equals does the following (
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values xand y, this method returns true if and only if x and y refer to the same object ( x==y has the value true ).
When you compare two instances using ==, you are actually comparing their memory addresses to see if they are references to the same object. This is usually not very useful in the normal course of programming. Whether an object is equal to another object is pretty context-specific, meaning that it depends on the types of objects that you are comparing.

Strings are a pretty straightforward case. If one string equals "abc" and another string equals "def", then if you check to see if they are equal by calling the equals method, it should return false. But if one string equals "abc" and the other string equals "abc", you don't want to compare the memory addresses of the two instances (since they will be different), but rather you want to compare the sequence of characters. Therefore, the String object override's Objet's equals method with it own implementation which simply compares the sequence of characters.
For example The following shows the use of equals() method


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
String s1 = new String("string1");
String s2 = new String("string1");
if (s2 == s1)
  System.out.print(">> We are EQUAL by ==");
else
  System.out.print(">> We are NOT EQUAL by ==");
if (s2.equals(s1))
   System.out.print(">> We are EQUAL by equals()");
else
System.out.print(">> We are NOT EQUAL by equals()");


will print the follwoing::
>> We are NOT EQUAL by == (**since we are comparing two string
object'sreference addresses)

>> We are EQUAL by equals() (** comparing the two string object's values)







Comments

  1. This is a good one , it cleared lots of doubt. But still the same holds for Java 6?

    ReplyDelete
  2. While discussing equals its important to know how to correctly override equals in Java because until you do it correctly you will confuse yourself.

    ReplyDelete

Post a Comment

Popular posts from this blog

Masking Credit Card number in Java

Sometimes we need to mask crucial information like Credit Card Numbers, CVV numbers etc before storing  or logging the information. This example mask Credit Card Number (Except last 4 Digit) from a Text which contains information along with Credit Card Number.

The following example demonstrates how we can easily mask the credit card with Matcher and Pattern Classes. This Sample Code uses Matcher and Pattern.
Pattern Used in this sample is not optimized for Credit Card Numbers, this pattern will get any numerical numbers in the String Content.  Based on the Credit Card Type a more efficient and Strict RegEx can be used to mask the Credit Card.
/**Mask the Credit card number but last four digit value **/   Pattern PATTERN = Pattern.compile("[0-9]+"); String message = content; Matcher matcher = PATTERN.matcher(message); String maskingChar = "*"; StringBuilder finalMask = new StringBuilder(maskingChar); while …

Converting Java Map to String

Java Collections framework, String manipulation etc is something that we often encounter in Development process.
For processing collections (like checking null/empty, Intersection, Disjunction) We do have some of the very use full libraries.

Some of the Collection related libraries are Apche Commons Collections and Google  Collections(Guava).

Problem Use Case

This article explains how to convert a Java Map to String(and vice versa) using different libraries and technique.

One way is to use StringBuilder(Or String) and loop though the Map and build the String by applying some sort of separator ( for key:value and entry). Here we have to take care of the null value etc.

Without Any Library
If we want to convert the map to a String with key value separator and also individual entry seperator in the resulting String, we have to write code for that. For a simple Map, we have to iterate though the map, take care of the null values etc. Following is a sample to get String built out from Map C…

Invoking EJB deployed on a remote machine

Invoking EJB deployed on a remote machineIn case we are calling remote ejb( ejb deployed on remote machines),The JNDI lookup might lookup like,Properties env = new Properties();env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");env.put(Context.PROVIDER_URL, "XX.XXX.XX.XX:1099");env.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); Context ctx = new InitialContext(env);If we are calling local ejb then we can simply create InitialContext without any parameters.Like,Context ctx = new InitialContext();