在 Java 應用程式中永遠不會傳遞物件,而只傳遞物件引用。因此是按引用傳遞物件。Java 應用程式按引用傳遞物件這一事實並不意味著 Java 應用程式按引用傳遞引數。以下是小編為大家搜尋整理的java通過值傳遞引數的方法是什麼,希望能給大家帶來幫助!更多精彩內容請及時關注我們應屆畢業生考試網!
呼叫一個方法時候需要提供引數,你必須按照引數列表指定的順序提供。
例如,下面的方法連續n次列印一個訊息:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
tln(message);
}
示例
下面的例子演示按值傳遞的.效果。
該程式建立一個方法,該方法用於交換兩個變數。
public class TestPassByValue {
public static void main(String[] args) {
int num1 = 1;
int num2 = 2;
tln("Before swap method, num1 is " +
num1 + " and num2 is " + num2);
// 呼叫swap方法
swap(num1, num2);
tln("After swap method, num1 is " +
num1 + " and num2 is " + num2);
}
/** 交換兩個變數的方法 */
public static void swap(int n1, int n2) {
tln("tInside the swap method");
tln("ttBefore swapping n1 is " + n1
+ " n2 is " + n2);
// 交換 n1 與 n2的值
int temp = n1;
n1 = n2;
n2 = temp;
tln("ttAfter swapping n1 is " + n1
+ " n2 is " + n2);
}
}
以上例項編譯執行結果如下:
Before swap method, num1 is 1 and num2 is 2
Inside the swap method
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After swap method, num1 is 1 and num2 is 2
傳遞兩個引數呼叫swap方法。有趣的是,方法被呼叫後,實參的值並沒有改變。