0

I have an array in Java that is filled with data. What I want to know is, if I do something like this:

int[] array = new int[2];
array[0] = 0;
array[1] = 1;

//other statements...

array[1] = array[0];

and if I change the value of array[1] again, will the value of array[0] change as well? Thanks!

1
  • No, because ints are primitives, not pointers to objects Commented Mar 5, 2013 at 1:42

1 Answer 1

3

and if I change the value of array[1] again, will the value of array[0] change as well?

No. This statement:

array[1] = array[0];

Just copies the value of the second element into the first element. It's just as if you had two separate variables:

int x = 10;
int y = x;
// Further changes to x don't affect y

The same is also true - but more subtly - if you have an array of references, e.g.

StringBuilder[] builders = new StringBuilder[10];
builders[0] = new StringBuilder("Original");
builders[1] = builders[0];
builders[0] = new StringBuilder("Hello");
System.out.println(builders[1]); // Prints Original

The last assignment statement doesn't change the value of builders[1]... but if instead we'd written:

builders[0].append("Foo");
System.out.println(builders[1]); // Prints OriginalFoo

then the values of builders[0] and builders[1] haven't changed - they still refer to the same object - but the contents of that object have changed, hence the output in the final line.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.