-4

I have a bit of a difficult time wrapping my head around this so I hope you guys can help me out here. Why does a[0] get replaced with 400 in this example here

int [] a = {1, 2, 3 } ; 
int [] b = a ;
b[0] = 400 ;
System.out.println(a[0]);

while in the example here c remains 2? I just don't understand this.

int c = 2 ; 
int d = c ;
d = 1 ; 
System.out.println(c);

A short explanation as to why this is happening would be very welcome.

Slevin94
  • 1
  • 1
  • 1
  • 1
  • It's the difference between reference values (in the first case) and primitive values (second case). – Andy Turner Jun 25 '17 at 20:18
  • 1
    By the way these are two different scenarios. To be equal, the first example should have `b = {5, 6, 7}` instead of `b[0] = 400 ;`. And you would notice that it behaves the same, so `a[0]` remains `1`. – BackSlash Jun 25 '17 at 20:19
  • Reassigning a variable is different from altering an object referenced by a variable. – khelwood Jun 25 '17 at 20:46

1 Answers1

-2

In java, here the same array has two references a and b, so whatever changes you do to b reflect in a as well. You may say, a and b are two alias here for one and only one instantiated array.

Arrays are also objects and their super class is Object class in java. From the [JLS Section 4.3],

There are four kinds of reference types: class types (§8), interface types (§9), type variables (§4.4), and array types (§10).

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

Community
  • 1
  • 1
hi.nitish
  • 2,732
  • 2
  • 14
  • 21