Rodrigo Gomez
Rodrigo Gomez

Reputation: 133

Confirm Java Copy By Value

Question on variable placement and confirming a copy is performed.

@org.junit.Test
public void question() {
    int c[] = new int[]{0};
    /*Questions:
     * 1.) Is j in the stack?
     * 2.) When assigning j, is a copy of the value c[0] performed?*/
    int j = c[0];
}

Upvotes: 0

Views: 162

Answers (3)

high-voltage
high-voltage

Reputation: 153

Java is always pass by value. What it means is when X = Y then X gets the value of Y. If it's the case of primitives like int then value is copied as primitives are available as values directly. If it's the case of objects then references to objects are copied as objects are available via references only.

Upvotes: 1

Daniel B.
Daniel B.

Reputation: 2601

Yes, the result of of c[0] is copied into the j variable, because int is a primitive type, and is copied by value. If you were to use the Integer class, the reference would be copied and not the value itself.

Upvotes: 1

Java only ever copies values. Sometimes those values are references to objects, but here the value is an int primitive. The value for j is on the stack because it's a local variable (as is the value for c, which is a reference to an array that is itself located on the heap but will soon be garbage-collected).

Upvotes: 3

Related Questions