ADVERTISEMENTS

How to swap two numbers in java

Java is also known for its use of the object-oriented programming (OOP) paradigm.There are multiple ways to swap the values of two variables in java :

  • Using a temporary variable
  • Using arithmetic operations

The following example will explain you about both ways of swaping a number in java :

Using a temporary variable: This is a common approach in which a temporary variable is used to store the value of one of the variables before swapping.

public class swapNumbersWithTempVar {

    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        // Swap with Temporary number
        int temp = a;
        a = b;
        b = temp;
        System.out.println("--Swaped Values--");
        System.out.println("A number = " + a);
        System.out.println("B number = " + b);
    }
}

 

Using arithmetic operations: This approach uses addition and subtraction to swap the values of two variables without the use of a temporary variable.

public class swapNumbersWithArthmetiOps {

    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        // Airthmetic Operation
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println("--Swaped Values--");
        System.out.println("A number = " + a);
        System.out.println("B number = " + b);
    }
}

Java is used for developing mobile apps, web applications, games, and other software. It is known for its "write once, run anywhere" (WORA) principle, which means that Java code can be run on any device that has a Java Virtual Machine (JVM) installed. You can learn java from our Java Tutorials and Java Examples

ADVERTISEMENTS