Swap two numbers without using temporary variable
public class swap1 {
public static void main(String[] args) {
float first = 18.0f, second = 64.5f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
first = first - second;
second = first + second;
first = second - first;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
When you run the program, the output will be:
--Before swap--
First number = 18.0
Second number = 64.5
--After swap--
First number = 64.5
Second number = 18.0
BUILD SUCCESSFUL (total time: 3 seconds)
public class swap1 {
public static void main(String[] args) {
float first = 18.0f, second = 64.5f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
first = first - second;
second = first + second;
first = second - first;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
When you run the program, the output will be:
--Before swap--
First number = 18.0
Second number = 64.5
--After swap--
First number = 64.5
Second number = 18.0
BUILD SUCCESSFUL (total time: 3 seconds)