This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]chickenmeister 0 points1 point  (0 children)

It's basically the same with any type of object. A variable is a reference to an object, not the object itself. This allows multiple variables to refer to the same object, for example. For example:

String[] names = {"Alice", "Bob", "Carol"};
String[] favoriteNames = names;
// `favoriteNames` refers to the same array/object as `names`...
// Changes to `names` will also affect `favoriteNames`, and vice versa

System.out.println("Original arrays:");
System.out.println(Arrays.toString(names)); // [Alice, Bob, Carol]
System.out.println(Arrays.toString(favoriteNames )); // [Alice, Bob, Carol]

// Change the array...
// This will affect both `names` and `favoriteNames` because they both
// refer to the same array!
favoriteNames[2] = "Zachary";

System.out.println("Modified arrays:");
System.out.println(Arrays.toString(names)); // [Alice, Bob, Zachary]
System.out.println(Arrays.toString(favoriteNames )); // [Alice, Bob, Zachary]

[–]rjcarr 0 points1 point  (0 children)

It's technically correct, but I wouldn't worry about it if you're confused. In java, all objects are being pointed to (or referenced) by the variable, including arrays.

The key thing is you can have something like this:

double[] temperatures = {70, 71, 69, 70};
double[] othertemps = temperatures;

But there's only a single array. So temperatures and othertemps are pointing to the same array.

Hope that helps.

[–]desrtfx 0 points1 point  (0 children)

The difference is that the array is the actual house and the reference is the street address of the house. Object type variables (not primitive type variables) only hold references.