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的基礎資料型別 (Elementary Data Type),定義如下:
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