Swap Two Integers in Java: 2 Methods Explained

You can swap the values of two integers by using a third variable, or you can use bitwise operations to swap the values of two integers.

Swap the values of two integers using a third variable.

int a = 10;
int b = 20;

int temp = a;
a = b;
b = temp;

System.out.println("a = " + a); // 输出:a = 20
System.out.println("b = " + b); // 输出:b = 10

Swap the values of two integers using bitwise operations.

int a = 10;
int b = 20;

a = a ^ b;
b = a ^ b;
a = a ^ b;

System.out.println("a = " + a); // 输出:a = 20
System.out.println("b = " + b); // 输出:b = 10

Both of these methods can achieve swapping the values of two integers, the specific choice between them depends on personal preference and practical situation.

bannerAds