0

I am trying to understand why output value is changed in case of Array and not in case of object.

public class SameClass {
  private Integer a;
  private Integer b[];
  public SameClass(Integer a) {
    this.a=a;
  }
  public SameClass(Integer a, Integer b[]) {
    this.a=a;
    this.b=b;
  }
  public static void main(String args[]) {
    Integer a = new Integer(5);
    Integer b[] = {2,5};
    // create two different objects
    SameClass sam = new SameClass(a);
    SameClass samB = new SameClass(a,b);
    //change values in local variables
    a=7;
    b[0]= 8;
    //print values 
    System.out.println(sam.a);
    System.out.println(samB.b[0] + " " + samB.a);
  }
}

Output of this code is :

5
8 5
JensS
  • 1,151
  • 2
  • 13
  • 20
msj003
  • 96
  • 7

1 Answers1

2
//change values in local variables
a=7;
b[0]= 8;

Your comment is wrong: you didn't change the value in the local variable b. You changed the value of a slot in the array which b is pointing to, and the same array is referenced from your object. This is why a = 7 has no effect on your object, but b[0] = 8 does.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436