java 值傳遞

JAVA面試題解惑系列(五)——傳了值還是傳了引用?

 

java中的變量類型:

基本類型變量:包括char、byte、short、int、long、float、double、boolean。 
引用類型變量:包括類、接口、數組(基本類型數組和對象數組)。 

當基本類型的變量被當作參數傳遞給方法時,JAVA虛擬機所做的工作是把這個值拷貝了一份,然後把拷貝後的值傳遞到了方法的內部。方法執行完畢後,局部變量的生命週期就結束了。

當引用型變量被當作參數傳遞給方法時,JAVA虛擬機也是拷貝一份這個變量所持有的引用,然後把它傳遞給JAVA虛擬機爲方法創建的局部變量,從而這兩個變量指向了同一個對象。

 

《The Java Programming Language》2.6.5. Parameter Values一節:All parameters to methods are passed "by value." In other words, values of parameter variables in a method are copies of the values the invoker specified as arguments.。。。。。You should note that when the parameter is an object reference, it is the object reference not the object itself that is passed "by value." Thus, you can change which object a parameter refers to inside the method without affecting the reference that was passed. But if you change any fields of the object or invoke methods that change the object's state, the object is changed for every part of the program that holds a reference to it. 

 

 

 

補充:String類型

String不是java的基本數據類型,定義如下:

public final class String extends Object implements Serializable, Comparable<String>, CharSequence 

 

它們的值在創建之後不能改變。 

 

以下代碼:

public class Test {

 public static void oprator(String test) {
  test.replace('A', 'E');
  test.toLowerCase();
 }

 public static void main(String[] args) {
  String str = "BEA";
  oprator(str);
  System.out.println(str);
 }
}

 

輸出的是BEA

 

 

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