0

Consider the following code:

public class Office {
    int room;
    Office(int room) {
        this.room = room;
    }
}

class Test {
  public static void F2(Office o1, Office o2) {
      o2 = o1;
      o2.room = 63;
  }
  public static void main(String[] args) {
      Office labOffice = new Office(130);
      Office commonOffice = new Office(275);
      F2(labOffice, commonOffice);
      System.out.println(labOffice.room + ", " + commonOffice.room);
  }
}

Inside method F2, after setting o2.room to 63, shouldn't both o1.room and o2.room become 63? Why does printing still give me 275 for commonOffice?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • because o2, in the scope of your method F2, is now pointing to o1. Java passes by reference value. More details: http://javadude.com/articles/passbyvalue.htm – Taylor Sep 27 '16 at 20:51
  • "both o1.room and o2.room will become 63" No this is not the case. with `o2 = o1` you are just setting the reference of `o2` to point to `o1`, hence the original value of o2 gets lost. When you set `o2.room = 63`, you just overwrite `o2`'s room value, but `o1` remains untouched. – gmazlami Sep 27 '16 at 20:53
  • No, the original value of o1 gets lost, because you set it with `o2.room = 63`. The original value of o2 is still available in `commonOffice` – devnull69 Sep 27 '16 at 20:58
  • @Reena Deng is it clear for you now or still confusing even considering the linked duplicate thread? – devnull69 Sep 27 '16 at 21:03

0 Answers0