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.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章