Pass Parameters to A Function

王朝学院·作者佚名  2016-05-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Pass Parameters to A FunctionAs we know, in java, a PRimitive-type variable is passed to a function by value while a Object-type variable is passed by its reference(i.e, the address to the memory where the real variable is stored).

But it should be kept in mind that the reference will never be passed back to the caller. We can just think this as a copy of reference is passed to the called method.

If the parameter alters to refer to other object in the called method, the corresponding variable(the block of memory) in the caller won't be affected. However, the memory which the parameter is pointing to gets changed in the called method, it will affect the world outside.

Here is an example to illustrate this. class TryReferncenPassBack{ // some code we are not caring about this moment int i; }

class Test{ public static void main(String [] args){ TryReferncenPassBack t = new TryReferncenPassBack(); t.i = 1; System.out.println(t.toString()); System.out.println(t.i); method1(t); System.out.println(t.toString()); System.out.println(t.i); } public static void method1(TryReferncenPassBack t){ t.i = 2; t = new TryReferncenPassBack(); System.out.println(t.toString()); t.i = 3; }}

Result:

1. TryReferncenPassBack@510bfe2c2. 13. TryReferncenPassBack@6a5c2445 // point to the new object4. TryReferncenPassBack@510bfe2c // after getting back, the reference still remains5. 2 // the original memory gets changed at line 16 instead of line 19

?2014 Alain

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航