Initializing int array

I didn't understand why I1.array[0]=555 is? I only want to change arr[0]

Intar I1 = new Intar(10);

int [] arr = I1.array;

        arr[0]=555;

public class Intar {

    int length;
    int [] array;


    public Intar(int lengt){

        length=lengt;
        array=new int[lengt];
        Random ran =new Random();

        for(int i=0; i<length; i++){

            array[i]= ran.nextInt(100);

**When I use System.out.println before and after arr[0]=555 **

I1.array [11, 57, 77, 74, 50, 62, 1, 11, 23, 27] 
arr      [11, 57, 77, 74, 50, 62, 1, 11, 23, 27] 
After arr[0]=555
I1.array [555, 57, 77, 74, 50, 62, 1, 11, 23, 27] 
arr      [555, 57, 77, 74, 50, 62, 1, 11, 23, 27]

Upvotes: 0

Views: 68

Answers (2)

James
James

Reputation: 1289

Intar I1 = new Intar(10);

Creates an Intar object, using the constructor public Intar(int lengt), this then initilizes the fields of the Intar object to be an array of 10 random numbers, and a length = 10.

When you write

int [] arr = I1.array;

You are telling arr to reference the object stored in I1's field called array (the array of 10 randomly generated numbers). So when you then set arr[0]=555 you are also setting I1.array's 0th element to be 555 as well.

What you have to understand is I1.array hold a reference to the array which is stored in the Intar object. And now arr is referencing the same object as I1.array is referencing.

For example:

public class Foo {

    int val;
    public Foo(int val){
        this.val = val;
    }
    int getVal(){
        return this.val;
    }

}

Then we can do this:

public static void main(String[] args) {
    Foo a,b;

    a = new Foo(5);
    b = a;
    b.val = 5;
    System.out.println(a.getVal());
}

5 will be the output as b now references a, and we changed the value of b thus we changed the value of a.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

int [] arr = I1.array; does not copy the array, it just assigns the reference to the l1.array to arr. You could use Arrays.copyOf(int[], int) to make a copy like

int[] arr = Arrays.copyOf(l1.array, l1.array.length);

Upvotes: 5

Related Questions