How to use the swap function in Java?

In Java, you can use a temporary variable to swap the values of two variables. Here is an example code:

public class SwapExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        
        System.out.println("交换前:");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        
        // 使用临时变量交换a和b的值
        int temp = a;
        a = b;
        b = temp;
        
        System.out.println("交换后:");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

When running the above code, the output will be:

交换前:
a = 10
b = 20
交换后:
a = 20
b = 10

Please note that the exchange here is achieved by copying the value of the variables, not by directly exchanging the references of the variables.

bannerAds