-2

In Java for example:

int x[] = {1,2,3,4};
    
int y[] = x;
y[0] = 100;
System.out.println(x[0]);
System.out.println(y[0]);

Output:

100
100

How can I change the values of int y without changing values of int x?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
AbDullA
  • 1
  • 2
  • You do not copy it. X and y points to the same array – Jens Jul 19 '22 at 05:38
  • Even though Java allows you to use `int x[]`, that syntax is discouraged (and IMHO a historic mistake). The general convention is to use `int[] x`, as that is far more clear and readable to most Java programmers. – Mark Rotteveel Jul 19 '22 at 07:18

1 Answers1

1

You are pointing to same array location hence updating one will update the second.

Use clone() method to create copy of the array.

    int x[] = {1,2,3,4};
    
    int y[] = x.clone();
    y[0] = 100;
    System.out.println(x[0]);
    System.out.println(y[0]);

Output :

1
100 

  
Pirate
  • 2,886
  • 4
  • 24
  • 42
  • So there's no benefit in doing what we did before? I mean what is the point of y if I say int y = x; – AbDullA Jul 19 '22 at 05:59