java 值傳遞

來源:互聯網
上載者:User

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

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.