Thursday, 13 September 2007

Arrays In Java

Continuing Reading Java Language Specification turned to section Arrays

First Primary Concept to Remember~Learn~Recall:
In the Java programming language arrays are objects.

Can you predict the output of the following program?

public static void main(String[] args) {
int ia1[] = { 1, 2 };
int ia2[] = ia1.clone();
System.out.print((ia1 == ia2) + " ");
ia1[1]++;
System.out.println(ia2[1]);
System.out.println(ia1[1]);
}
}

Output:
false 2 3

Reason:
The components of the arrays referenced by ia1 and ia2 are different variables. (In some early implementations of the Java programming language this example failed to compile because the compiler incorrectly believed that the clone method for an array could throw a CloneNotSupportedException.)


Always remember superClass of an Array Class is java.lang.Object as known Arrays are Objects in Java.

For Example:
public static void main(String[] args) {
int[] ia = new int[3];
System.out.println(ia.getClass());
System.out.println(ia.getClass().getSuperclass());
}

Prints:
class [I
class java.lang.Object

where the string "[I" is the run-time type signature for the class object "array with component type int".
which is a special class for arrays of type int.

Do we know a clone of a multi dimensional array is shallow??

For Example:
public static void main(String[] args) throws Throwable {
int ia[][] = { { 1 , 2}, null };
int ja[][] = ia.clone();
System.out.print((ia == ja) + " ");
System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
}

Output:
false true

Reason:
As said,A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.showing that the int[] array that is ia[0] and the int[] array that is ja[0] are the same array.

Hope this explanation helps and please advice and suggest if any.

3 comments:

Unknown said...

In your first example you write as output.

false 2 1

Am I missing something? I think the output should be

false 2
3

Anonymous said...

No marcel, you're right...

Just goes to show...if you write convoluted examples, you make mistakes...

I hate things like this, where people try to show you something...make it hard on purpose, and THEN get it wrong...

JP said...

marcel,

You are right.Sincere apologies for this.Will try not to repeat again.

Thanks
Prashant