This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array Help" Watch "Array Help" New topic

Array Help

Hamraj Kulshreshtha
Ranch Hand

Joined: Oct 06, 2007
Posts: 31
Why the result of the below code is false??

import java.util.*;
class Test
public static void main(String[] args)
int[] a = new int[]{1};
int[] b = new int[]{1};

SCJP 1.5 91%
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
As you know every arrays is an object of Array class and not Arrays [Arrays is an utility class].When you invoke a.equals(b) it invokes the equals() method of Object class which returns true if both the references refer to same object otherwise returns false.
int[] a = new int[]{1};
int[] b = new int[]{1};
Here a and b refer to two different objects and hence returns false.
Hope this clears the answer.

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074

Originally posted by Deepak Jain:
As you know every arrays is an object of Array class and ...

This is not entirely correct. An array is an object, but it is not an instance of a class named Array. An array is not an instance of any class in the Java API; the class for arrays is a special class that is built-in in the JVM.

Anyway, that special class does not have an overridden equals() method, so the default equals() method of class Object is used. That version of equals() just compares the objects with ==, and == only returns true if the two arguments on both sides refer to the exact same object. You obviously have two arrays, so == returns false.

If you want to compare the contents of two arrays, you'll have to loop through the arrays and compare the elements one by one. You could also use one of the utility methods in the class java.util.Arrays:

[ January 10, 2008: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
It is sorta covered in the JavaRanch Style Guide.
subject: Array Help
Similar Threads
Doubt in Array Declaration
Inquisition Question
Array/Constructor Problem
arrays equals() confusion
equals() doubt