Think it in terms of memory: Lets analyse your first program -
In mainx
, fyeah
is an array of int
s , so its a reference ( or a pointer if I may ). This reference points to a location in heap memory where the actual array of int
s is stored. Lets say at address 100. Located contiguously from here are three ints ( lets say beginning at address 100 , 104 and 108 respectively are 2 ,3 and 4 ).
Now you call your method smth
and pass the reference. Within the method , there is another reference ( of an int
array type ) named fyeah
. This fyeah
is quite distinct from fyeah
reference in the mainx
method. Now , when you call smth
and pass the fyeah
from mainx
, the fyeah
within the smth
method is initialized to point to the same location ( ie memory address 100 )
When you access the 0 element of fyeah
and assign it a value of 22 , it reaches out to the memory location of 100 and writes this value 22 there. When you come back in your mainx
method , the fyeah
reference is still referring to memory address 100. But the value present at that location is now 22. So you get that value when you access the first element from fyeah
in mainx
.
Now , your second program. Your mainx
method declares an int
( not an array , but a simple int
) and set it to 5. This fyeah
variable is created on stack not on the heap. The value of 5 is stored on the stack. Now you call smth
and pass this variable. Within the method smth
, you again declare an int
variable , fyeah
by name ( as a formal method argument ). Again this is distinct from the fyeah
of the mainx
method and this fyeah
is also created on stack.This variable will be initialized to a value of 5, copied over from the fyeah
you passed to smth
as argument. Note now that there are two distinct copies on fyeah
variables , both on stack , and both a value of 5. Now you assign the fyeah
in smth
a value of 22. This will not affect the fyeah
of the mainx
method,so when you return to mainx
and access fyeah
, you see 5.