-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?

2
  • You do not copy it. X and y points to the same array Commented Jul 19, 2022 at 5: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. Commented Jul 19, 2022 at 7:18

1 Answer 1

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 

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

1 Comment

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;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.