Swapping 2 numbers using Java

This Java example will swap the first variable’s value into the second variable and the second variable’s value into the first variable.

Swape two numbers in Java

public class Main
  public static void main (String args[])
    int num1 = 5, num2 = 10;

      System.out.println ("Numbers before swapping are:");
      System.out.println ("Number 1: " + num1 + ", Number 2: " + num2);

      num1 = num1 + num2;
      num2 = num1 - num2;
      num1 = num1 - num2;

      System.out.println ("Numbers after swapping are:");
      System.out.println ("Number 1: " + num1 + ", Number 2: " + num2);


Numbers before swapping are:

Number 1: 5, Number 2: 10

Numbers after swapping are:

Number 1: 10, Number 2: 5

Code Explanation

In this code snippet, you will learn how to swap two integer variables, without using a temporary variable. First, we assign the sum of the first and second variables into the first variable num1, then get the value of the first variable by subtracting the second variable num2 from the first variable num1. The last step is to get the second variable value by substruction the second variable from the first variable.

Leave a Reply

Your email address will not be published.