Swap Two Numbers in Java

Advertisements

Prev Tutorial Next Tutorial

Java Program to Swap two Numbers

Swapping is the process of exchange the values of two variables with each other. For example variable num1 contains 20 and num2 contains 40 after swap their values are num1 contains 40 and num2 contains 20. In below code i will show exchange values of two variable using third variable and without sing third variable.

Java Program to Swap two Numbers using third variable

import java.util.Scanner;
class Swapnumber 
{
 public static void main(String[] args) 
 {
  int a, b, c;
  Scanner s=new Scanner(System.in);
  System.out.println("Enter Value in a :");
  a=s.nextInt();
  System.out.println("Enter Value in b :");
  b=s.nextInt();
  c=a;
  a=b;
  b=c;
  System.out.println("Values in a:" +a);
  System.out.println("Values in b:" +b);
 }
}

Output

Enter Value in a : 10
Enter Value in b : 20
Value in a : 20
Value in b : 10

Java Program to Swap two numbers without using third variable

import java.util.Scanner;
class Swapnumber 
{
 public static void main(String[] args) 
 {
 int a, b;
 Scanner s=new Scanner(System.in);
 System.out.println("Enter Value in a :");
 a=s.nextInt();
 System.out.println("Enter Value in b :");
 b=s.nextInt();
 a=a+b;
 b=a-b;
 a=a-b;
 System.out.println("Values in a:" +a);
 System.out.println("Values in b:" +b);
 }
}

Output

Enter Value in a :
10
Enter Value in b :
20
Value in a : 20
Value in b : 10

Syntax to compile and run java program

Syntax

for compile -> c:/javac Swapnumber.java
for run -> c:/java Swapnumber

Explanation of Code

  • Scanner s=new Scanner(System.in): are used for receive input from keyboard.
  • nextInt(): method are used for get integer type value from keyboard.
  • System.out.println("....."): are used for display message on screen or console.

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements