0

I would like to understand what array = array actually does.

Why does editing data1 leads to data2 being changed later on in the process?

String[][] data1 = new String[5][1];
String[][] data2 = new String[1][1];

data1[0][0] = "Test 1";
data2 = data1;

//Prints "Test 1"
System.out.println(data2[0][0]);

data1[0][0] = "NEW";

//Prints "NEW"
System.out.println(data2[0][0]);
3
  • 1
    data2 = data1;. Both data2 and data1 refer to the same array (new String[5][1]) Commented Jul 24, 2018 at 17:50
  • I haven't done Java in a long time but I think this only works because the data type for both are the same. If let's say data2 wasn't a 2-dimensional array of strings then data2 = data1 will error out. Commented Jul 24, 2018 at 17:52
  • This is easier to understand in the C language where an array is actually the address of the first element of the array. data2 = data1 actually make both variables point to the same array. Commented Jul 24, 2018 at 17:58

3 Answers 3

1

In Java, the array name actually holds the starting address of the array (similar to c/c++). The array index is the offset form the starting address.

So, when you use array2 = array1, you are essentially telling the compiler:

"Let array2 hold the same address as array1"

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation. So to solve to problem I should just manually copy the array right?
@X3Gamma read pritam's answer
Except that both are refences which aren't addresses.
1
data2 = data1;

At 4th line, you order that data1 will refer to where data2 refer to from now on. So, both references refer to same object. Any modification by using one of the references will be seen by each other. That's what = operator actually does in Java. Technically, it is reference copying in this way.

2 Comments

Questions like this show that operator overloading is a bad idea. Glad Java doesn't have it.
@M.leRutte It depends. Just because one needs to be careful when overloading operators doesn't mean that operator overloading is a bad thing; it just means that one should do it with care and only where it makes sense. That's my two cents at least.
0

As already mentioned in the previous answers that it refers to the same location when you use the = operator, changes are reflected in both.

If you don't want that then you should use clone the arrays. You can refer this answer on how to do it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.