user2635439
user2635439

Reputation:

Is array of primitives assigned to variable as an Object (by reference) or by value?

I am writing a class of Polygon and after thinking about it I decided to use arrays of x and y values and save the dots.

This led me to think, out of laziness, about this:

int[] x, y;
x = y = new int[NUM];

I know that arrays are classes and not considered as primitive so what will happen here?

On one hand, x and y are arrays of primitive so the array is partially considered as primitive. So it may copy the values to a new array, like normal int:

int x, y;
x = y = 5;

But if it is not primitive then x and y will point to the same place in the memory and will have the same variable. When you edit one, the second will be edited too.

MyClass x, y;
x = y = new MyClass(value);

So, my question is, which one of the following ideas is right?

Upvotes: 2

Views: 119

Answers (4)

hagrawal7777
hagrawal7777

Reputation: 14658

on one hand, x and y are arrays of primitive so the array is partial considered as primitive so it may copy the values to a new array, like normal int:

You are correct in "arrays of primitive" but not in "partial considered as primitive". Array is an array, there is no partial or complete. The way you have defined, it is an array of primitives which means that a heap space will be assigned where primitive int values will be stored.

but if it is not primitive than x and y will point to the same place in the memory and will have the samevariable, when you edit one, the second will be edited too.

It is, so later part of this statement is correct that "same place in memory"

Hope this helps!

Upvotes: 2

Nick Volynkin
Nick Volynkin

Reputation: 15099

In Java array of anything is an object, including array of primitives.

Both x and y will point to the same array object. To instantiate them as different objects, use

x = new int[n];
y = new int[n];

A good way to determine if something in Java is an object or not is to try calling a method on it.

new int[1].toString(); //legal
1.toString(); //illegal

But a better way is to know that actually anything but single primitives is an object. :)

Upvotes: 3

Michael0x2a
Michael0x2a

Reputation: 64028

According to the Java spec, section 4.3.1 an object is formally defined as "a class instance or an array", which means that arrays will not be treated as primitives and will always use reference semantics.

Upvotes: 3

Jesper
Jesper

Reputation: 206796

This will indeed create only one array, and make x and y refer to that one array:

int[] x, y;
x = y = new int[NUM];

If you want two arrays for the x and y values, then create two arrays:

int[] x = new int[NUM];
int[] y = new int[NUM];

Upvotes: 1

Related Questions