ADVERTISEMENT
ADVERTISEMENT

Java - Swapping of Two Numbers without using Third Variable in Java.


IncludeHelp 07 August 2016

Swapping of Two Variables - In this example we will swap value of first variable into second variable and value of second variable into first variable.

Generally we swap values of variables by using third variable in which we assign value of first variable into temporary or third variable, and then we assign value of second variable into first variable and finally assign value of third or temporary variable into first variable.

But in this code snippet, we will learn how to swap values of two variables without using third or temporary variable, this method of swapping is really very easy and takes less memory because we do not need to declare another temporary variable for swapping.

This method contains three steps: 1) Assign sum of first and second variable into first variable, 2) get value of first variable by subtracting second number from first number and 3) Get value of second variable by subtracting second variable from first variable. Finally you will get swapped values of two variables without using third variable.

Java Code Snippet - Swapping of Two Numbers without using Third Variable

//Java - Swapping of Two Numbers without using Third Variable in Java.

public class SwapTwoNumbers
{
	  public static void main(String args[]){
		  int number1=100,number2=200;
		  
		  System.out.println("Numbers before swapping:");
		  System.out.println("number1: " + number1 +", number2: " +number2);
		  
		  //swap without using third variable
		  number1=number1+number2;
		  number2=number1-number2;
		  number1=number1-number2;

		  System.out.println("Numbers after swapping:");
		  System.out.println("number1: " + number1 +", number2: " +number2);		  
	  }
}
    
    Numbers before swapping:
    number1: 100, number2: 200
    Numbers after swapping:
    number1: 200, number2: 100

ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.