Java Program to swap two numbers

In this example, we are giving a program to swap two numbers.


To swap two numbers:

  1. # To swap two numbers
  2. public class SwapNumbers {
  3. public static void main(String[] args) {
  4. float first = 7.5f, second = 3.9f;
  5. System.out.println("Before swapping:");
  6. System.out.println("First number = " + first);
  7. System.out.println("Second number = " + second);
  8. float temporary = first;
  9. first = second;
  10. second = temporary;
  11. System.out.println("After swapping:");
  12. System.out.println("First number = " + first);
  13. System.out.println("Second number = " + second);
  14. }
  15. }

Output:

Before swapping:
First number = 7.5
Second number = 3.9
After swapping:
First number = 3.9
Second number = 7.5