Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following code compile without error?

Tags:

java

arrays

I am new to java and trying to understand the following. The length of the arrays is not same. The code still executes without any errors. I dont understand why. If someone could clarify.

public class Practice {
    public static void main(String[] args){

        int [][] a = {{1,2,3},{4,5}};
        a[0] = a[1];
    }
}
like image 996
Jeff Benister Avatar asked Aug 06 '15 07:08

Jeff Benister


2 Answers

a[0] and a[1] are both int arrays (i.e. their type is int[]), so one can be assigned to the other, regardless of the lengths of the current arrays they are referring to.

Your code is not very different from the following code :

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

Or from this code :

Object a = ...
Object b = ...
a = b;

In both cases (as in your original code) you are changing the value of a reference type variable to refer to a different object.

like image 116
Eran Avatar answered Nov 09 '22 22:11

Eran


You can assign a different-sized array to an array (a[0] = a[1]) in the same way you can re-assign an array variable like this:

int[] x = new int[5];
x = new int[6];

So, since this is allowed, there's no problem to assign a[1] to a[0].

In the end, it's just a change of the reference that the initial array holds.

like image 35
Konstantin Yovkov Avatar answered Nov 09 '22 23:11

Konstantin Yovkov