Saturday 24 August 2019

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,

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

After Swapping, a = 20 and b = 12

2) Swapping two string variables without using temporary variable

package com.example.demo;

public class SwapStrings {
        public static void main(String[] args) {
               String var1 = "Java";
               String var2 = "PHP";
               var1 = var1 + var2;
               var2 = var1.substring(0, var1.length() - var2.length());
               var1 = var1.substring(var2.length());
               System.out.println("After swapping, var1 - "+var1+" var2 - "+var2);

After swapping, var1 - PHP var2 - Java

Related Posts:-
1) Sort a binary array using one traversal in Java
2) Java program to find second largest number in an array
3) Write a Java program to print the Floyd's triangle
4) Java Program to check the given number is a palindrome or not
5) Java program to print the first n prime numbers
6) Java Program to find the Missing Number in an Array
7) Java Code to Print the Numbers as Pyramid - Examples

No comments:

Post a Comment