java - Why does creating an array from primitives copy them? -


in program

public static void main(string[] args){     int x = 1;     int y = 2;     int[] z = new int[]{x, y};     z[0] = 3;     system.out.println(x); //prints 1 } 

i expected 3 printed. 1 was. why? thought java makes copy of references, i.e. when pass refrence method, method operate reference same object. it's c++ pointers , primitive types.

so tried consult jls 10.6 , didn't find useful it. maybe i've got misunderstanding primitive types in java. clarify?

why creating array primitives copy them?

for same reason that:

int = 5; int b = a; 

...copies value of a b, without creating kind of link between a , b: value copied, not kind of reference variable.


re comment:

but when operate on reference types, reference copies, doesn't it?

yes, does, number gets copied in int scenario.

b = a (or array initializer) works exactly same way regardless of whether a , b primitive type variables or reference type variables: value in a copied b, , there no ongoing link between a , b.

the difference when you're dealing reference types, value in variable isn't actual thing, it's reference actual thing. copying reference 1 variable makes makes 2 variables refer same thing, code above makes a , b both have value 5.

consider: let's create list:

list<string> = new arraylist<string>(); 

that gives in memory:

               +----------+ a(55465)----->| list |               +----------+ 

the variable a contains value reference object. i've depicted value above 55465, never see raw value in our java code (and changes garbage collection done). it's value, other value, tells jvm find object in memory. can think of long containing memory address (that's not is, works conceptually).

now this:

list<string> b = a; 

now have in memory:

  a(55465)--+           |    +----------+           +--->| list |           |    +----------+ b(55465)--+ 

both a , b contain value refers list.

you can see how that's like:

int = 5 

gives us

 a(5) 

and then

int b = a; 

gives us

 a(5) b(5) 

values copied between variables, passed functions, etc. difference reference types value used for, how it's interpreted.

if so, java pass value in sense of copying values of primitives , references of reference types. right?

no. "pass value" , "pass reference" have specific meaning in computing: it's having reference variable, not object. pass-by-reference looks like:

// not java; java doesn't have void foo(int &a) { // fake pass-by-reference thing     = 3; }  int = 5; foo(&a); // fake pass-by-reference operator system.out.println(a); // 3 

pass-by-reference has nothing object references. thing have in common word "reference." java purely pass-by-value language.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -