可以使用第三個變量來實現兩個變量的值互換,也可以通過數學運算來實現。以下是兩種方法的示例代碼:
方法一:使用第三個變量進行值互換
```java
int a = 5;
int b = 10;
int temp;
System.out.println("Before swapping: a = " + a + ", b = " + b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping: a = " + a + ", b = " + b);
```
方法二:通過數學運算進行值互換
```java
int a = 5;
int b = 10;
System.out.println("Before swapping: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
```
上述兩種方法都可以實現兩個變量的值互換,你可以根據自己的喜好選擇其中一種方法。