Menu
Learn Coding Online – CodingPanel.com
  • Technologies
    • .NET Core
    • Angular
    • ASP.NET
    • C
    • C#
    • C++
    • Java
    • JavaScript
    • JSON
    • Kotlin
    • Node.js
    • PHP
    • Python
    • React
    • SQL
  • Topics
    • Algorithms
    • Computer Networking
    • Computer Science
    • Design Patterns
    • Software Design
    • Software Engineering
    • Web Development
  • Interview Questions
    • C# Interview Questions
  • Learn
    • My Learning
    • Data Structure
    • Programming
  • Test your Skills
Learn Coding Online – CodingPanel.com

Swapping 2 numbers using Java

Posted on November 16, 2020April 7, 2021 by CodingPanel Editor

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);
  }
}

Output

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.

Related posts:

  1. Print Prime Numbers from 1 to N in Java
  2. Remove vowels from a string using Java
  3. Get IP address, computer name and MAC address using Java
  4. Examples of ArrayList in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Blog Authors

avatar for Asha S.Asha S. (4)

IT specialist Veteran

avatar for CodingPanel EditorCodingPanel Editor (40)

Blog Hero

avatar for Feras SFeras S (5)

Software Engineer

©2021 Learn Coding Online – CodingPanel.com | Powered by WordPress & Superb Themes