Java program to swap two numbers without using third variable

  • on February 4, 2019
  • Likes!
Hello friends! Welcome to my blog
Here we discuss how to swap two numbers in java language and there are two methods to swap two numbers in java

1. swap two numbers without using third variable in java.

2. swap two numbers with using third variable in java.

See Example below

Swap two numbers without temp in java

import java.util.Scanner;
public class swap_without {
    public static void main(String[] args) {
       int a ,b;
        Scanner in = new Scanner(System.in);
        System.out.println(“Enter the two number”);
        a=in.nextInt();
        b=in.nextInt();
        System.out.println(“Number before Swap:n a=”+a+”n b=”+b);
        a=a+b;
        b=a-b;
        a=a-b;
        System.out.println(“Number After Swap:n a=”+a+”n b=”+b);
    }
}
Enter the two number
4
6
Number before Swap:
 a=4
 b=6
Number After Swap:
 a=6
 b=4

Swap two numbers in java

import java.util.Scanner;
public class swap {
    public static void main(String[] args) {
        int a ,b;
        Scanner in = new Scanner(System.in);
        System.out.println(“Enter the two number”);
        a=in.nextInt();
        b=in.nextInt();
        System.out.println(“Number Before Swap:n a=”+a+”n b=”+b);
        int temp=a;
        a=b;
        b=temp;
        System.out.println(“Number After Swap:n a=”+a+”n b=”+b);
 
    }
}
Enter the two number
4
7
Number Before Swap:
 a=4
 b=7
Number After Swap:
 a=7
 b=4

I make this programming and hope you are like the post if are you like the post you can please comment and Share the post to reach more people.
If any doubt about this java programming code or input & output please comment below
If you have another question about Java programming send an email by contacting us form are given on the page right side.
I am Try to Help in your Programming Language by Programming Shortcuts

Please share your experience about this post,
Thank You!

Article Categories:
Programs in java

Leave a Reply

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