Java record-32-value exchange
1. Implement the exchange of two variable values:
public static void main(String[] args) { int a = 3; int b = 5; int temp = a; a = b; b = temp; System.out.println(a); System.out.println(b); System.out.println("----------------"); a = a + b; b = a - b; a = a - b; System.out.println(a); System.out.println(b); }
The code above implements two methods when swapping values of a and B variables: one is to use temporary variables, and the other is to use addition and subtraction of two variables without using temporary variables. 2.
public class SwapTest2 { public static void change(char[] cs, char c){ cs[0] = 'C'; c = 'D'; } public static void swap(char[] cs){ char temp = cs[0]; cs[0] = cs[1]; cs[1] = temp; } public static void main(String[] args) { char[] ch = {'A','B'}; swap(ch); System.out.println(ch); change(ch, ch[1]); System.out.println(ch); }}
Java is the value transfer. For an array, the first address of the array is passed. Array can be used for value exchange.