6

Swap two variables without using third variable in Java

 2 years ago
source link: http://adnjavainterview.blogspot.com/2019/08/swap-two-variables-without-using-third-variable-in-java.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Swap two variables without using third variable in Java

         In the current post, we will discuss/write a code to swap two variables without using third/temporary variable. The below first example is to swap two integers without using third integer variable, second example is to swap two string variables without using third variable.

1) Swapping two integers without using temporary variable

SwapIntegers.java,

package com.example.demo;

public class SwapIntegers {
 
       public static void main(String[] args) {
  
                int a = 12;
                int b = 20;
                a = a + b;
                b = a - b;
                a = a - b;
                System.out.println("After Swapping, a = " +a+" and b = "+b);
      }
}

Output:-
After Swapping, a = 20 and b = 12

2) Swapping two string variables without using temporary variable

SwapStrings.java


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK