Java Learning Notes-Passing Function Parameters

There are two terms that describe how parameters can be passed to a function in a programming language.One trem is called "call by value" and the other is called "call by reference".The first term means that the function gets the value of passed parameter,which is a copy of caller provides parameter,and the function can not modify the value store in the variable. In contrast,the term of "call by reference" means that the function gets the location of the variable that caller providers.Thus,the function can modify the value stored in a variable passed by reference.However,in Java programming language,there are always uses the first method,that is "call by value".That means the function always gets a copy of parameter value,Thus the function can not modify the contents of the value passed to it.And there are two kinds of function parameters,primitive types and Object references  in Java programming language,which would be illustarted by a program and a picture.

Example 1:Passing a primitive types.

public class solution {
	public static void main(String[] args) {
		int x=1;
		System.out.println(x);
		func(x);
		System.out.println(x);
	}
	public static  void func(int x) {
		x++;
	}
}
output:
       1
       1

In this example,user passed a primitive parameter to  method "func()",as a result of,Java language always use "call by value",the variable x in "func()" is a copy of variable x in main function.Although,we changed the value of x,it can not change the value of x in main function,which we real want to modify.Because,when the function "func()" is excuted ,the value x would be released.

 Example 2:Passing a object reference

public class solution {
	public static void main(String[] args) {
		StringBuffer str=new StringBuffer("hello");
		System.out.println(str);
		func(str);
		System.out.println(str);
	}
	public static void func(StringBuffer str){
		str.append("world");
	}
}
output:
        Hello
        Helloworld

In this example,we passed a String object to function "func()",as the same reason of  last example.The function "func()" gets a copy of the object reference,and both the original and the copy refer to the same object.Thus,when we change the contents of "str" in func(),the "str" in main function would be changed as well.And,it is noticeable that it will return the object's reference in Java language,and the JVM would not destory the returned object in called funtion.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值