1 package cspuzzles; 2 3 class MyInt{ 4 int anInt; 5 } 6 7 public class Post003 { 8 void Method01(int x){ 9 x = 10; 10 } 11 12 void Method02(MyInt m){ 13 m.anInt = 15; 14 } 15 16 void Method03(MyInt m){ 17 m = new MyInt(); 18 m.anInt = 20; 19 } 20 21 public static void main(String[] args){ 22 Post003 p = new Post003(); 23 MyInt m = new MyInt(); 24 m.anInt = 5; 25 System.out.println(m.anInt); 26 p.Method01(m.anInt); 27 System.out.println(m.anInt); 28 p.Method02(m); 29 System.out.println(m.anInt); 30 p.Method03(m); 31 System.out.println(m.anInt); 32 } 33 }The key is understanding passing primitive values vs. object references.
The code prints:
5
5
15
15
In line 26, a copy of the value of m.anInt is passed. Therefore, line 9 is modifying just a copy of the original value and when the control returns to line 28, the original value has not changed (i.e., the value of m.anInt is still 5).
In line 28, we are passing a copy of the object reference. In other words, variable m in main and variable m in Method02 are different variables, but both refer to the same object. Given said that, line 13 modifies the object created in main and line 29 prints, as expected, the new value of m.anInt.
Now for the bonus part. In line 16, variable m refers to the same object as the variable m in main. But after executing line 17, variable m in Method03 refers to a new object, that's why line 18 is not modifying the original object in main.
What do you think about Java mechanisms to pass parameters? Let's hear your opinion in the comments.
No comments:
Post a Comment