2015-02-06 77 views
0

爲什麼我得到的輸出等於5?我期待6,因爲在「addthenumber(x);」之後線,該方法被稱爲,我在想的是該方法執行計算和5變成6.所以sysout應該打印6,但它是如何5?通過方法更改變量

public class CodeMomkeyPassingvalue 
{ 
    public static void main(String[] args) 
    { 
     int x = 5; 
     addthenumber(x); 
     System.out.println(x); 
    } 

    private static void addthenumber(int number) 
    { 
     number = number+1; 
    } 
} 

輸出:

5 
+0

的技術解釋爲什麼http://stackoverflow.com/questions/40480/is-java-pass-by-reference-或傳遞值 – 2015-02-06 07:20:59

+0

因爲5傳遞給函數,而不是x。 – immibis 2015-02-06 07:30:13

回答

0

下面代碼

{ 

     int x = 5; // declare x = 5 here 

     addthenumber(x); // calling function, passing 5 

catch is here - 參數值傳遞,而不是通過引用。 x本身不傳遞,只有x的值傳遞給方法。

 System.out.println(x); // printing same x value here, ie 5 

    } 

私有靜態無效addthenumber(INT數){

number = number + 1; // 1 added to number locally, and is referencing inside method only. 


} 
+0

感謝所有三個人爲我清理它。現在我明白了這個概念。我很困惑,因爲早些時候我被告知,當相同的變量稍後被賦予不同的值時,程序流程中的變量「can」的值會改變。 – Jboy 2015-02-06 08:15:41

6

方法的參數是按值傳遞,而不是由參考。這意味着不是變量本身,而只是將變量的值傳遞給方法。

方法addthenumber中的變量numbermain方法中的變量x不是相同的變量。當您更改number的值時,它對main中的變量x沒有任何影響。

0

Java遵循call by value範例,所以在調用函數中值不會改變。如果您想要在添加1後更改該值,則必須將其返回;

public static void main(String[] args) 
{ 
    int x = 5; 
    x = addthenumber(x); 
    System.out.println(x); 
} 

private static int addthenumber(int number) 
{ 
    return number+1; 
}