0

PS: This question is different than others because I need to know exactly what code to write in order to prevent the variable from changing.

I have this example of code to demonstrate my problem:

float[][] one = {{0}};
float[][] two = one;
System.out.println(two[0][0]);
one[0][0] ++;
System.out.println(two[0][0]);

int three = 0;
int four = three;
System.out.println(four);
three ++;
System.out.println(four);

The output is:

0.0
1.0
0
0

For some reason, when I change float[][] 'one', 'two' automatically changes as well. However, when I performed the same task but for a different data type int, then the code works as intended.

What is causing this variable to drag the other one with it?

Why doesn't it happen for the int type?

How do I fix it?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
billschmidt626
  • 131
  • 1
  • 4
  • This can be solved by copying your values: https://stackoverflow.com/questions/5785745/make-copy-of-an-array – JoschJava Oct 08 '19 at 13:17
  • This behaviour is due to the fact that array "variables" are references to array objects. When you assign one to the other, they are both referring to the same object. On the other hand, primitive types like int hold the actual value, they are not references. – DodgyCodeException Oct 08 '19 at 13:21
  • to understand, you must understand the difference between reference semantics vs value semantics. An int is a primitive data type, meaning it's only the value. There's no way to manually take control of the pointer to the value. Arrays are Objects, meaning the variables that you assign the instantiated array to are in fact references to the memory address of the array (ie pointers). So when you assign the array `one` to `two`, you've got two references to the same array. Perhaps looking into pointers in C will help you – mistahenry Oct 08 '19 at 13:25

0 Answers0