Wednesday, February 25, 2015

Why Array doesn't have Class file? Still we can create an array object without class file also

Hi,

I would like to let you know about arrays in java.

I have observed so many developers, when I ask to solve below problem they get confused and tell the wrong answer.

int[] a={1, 2, 3};
int[] b={1, 2, 3};

System.out.println(a.equals(b));
O/P= ?

They say true as answer which is a wrong answer.

Immediately I will ask them for explanation. They say both arrays are have same content so JVM checks for content to check the equality.

Then the next question will be what is the use of equals() method....

Explanation why the answer is false:

If we observe the java API. There is no direct class file to create object of type Array.

Whenever you execute above statements JVM internally creates a memory space based on its size and returns the reference to you. It means that there is no class to create object using new operator.

And if you check that object is the instance of Object class. It will show true.

It means, as per java standards any object you create for any class that objects parent object will be always Object only.

Here any kind of array created by JVM is the single level object in hierarchy of the object view. It means the immediate supper class always will be Object only.

You know what is there in Object class's equals() method..

And here in array object there is no implementation for equals() method. If the implementation is really there then we would have the class to create object.

So, whenever you execute above statements there will be two different objects even though they have same content in it and equals() method will be called of Object class object which will check for hashcode equality...

That's why you get false as output. :)

Hint: There is a separate assertion method available in junit to check the equality of two arrays...

Please give your feedback: nagarjuna.lingala@gmail.com