JAVA中的swap怎么写,交换a,b的值
时间: 2024-10-09 12:08:45 浏览: 28
Java 交换两个变量的数值实现方法
5星 · 资源好评率100%
在Java中,`swap`函数通常用于交换两个整型变量的值,而不需要创建额外的临时变量。以下是使用`swap`方法交换变量`a`和`b`的值的简单实现:
```java
public class Main {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.println("Before swapping: a = " + a + ", b = " + b);
// Call the swap method
swap(a, b);
System.out.println("After swapping: a = " + a + ", b = " + b);
}
/**
* The swap function takes two integers and swaps their values in-place.
*/
public static void swap(Integer a, Integer b) {
a = a ^ b; // XOR operation to swap without using a temporary variable
b = a ^ b; // After this step, a holds the original value of b
a = a ^ b; // And after this, a holds the original value of a (now swapped with b)
}
}[^1]
阅读全文