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];
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With