Swap two numbers using java. Java swapping program.
In this article you will learn how to swap two numbers using third variable or without using third variable.
To understand this example you should have knowledge about
Java datatypes,
Java operator.
Using third variable.
Approach :-1
class Swapno{
public static void main(String[] args) {
int n1=15,n2=25,temp;
System.out.println("Befor swapping n1 = "+n1+" n2= "+n2);
temp=n1;
n1=n2;
n2=temp;
System.out.println("After swapping n1 = "+n1+" n2= "+n2);
}
}
Output :-
Befor swapping n1 = 15 n2= 25
After swapping n1 = 25 n2= 15
Not using third variable
Approach :-2
public class Swapno{
public static void main(String[] args) {
int n1=15,n2=25;
System.out.println("Befor swapping n1 = "+n1+" n2= "+n2);
n1=n1-n2;
n2=n1+n2;
n1=n2-n1;
System.out.println("After swapping n1 = "+n1+" n2= "+n2);
}
}
Output :-
Befor swapping n1 = 15 n2= 25
After swapping n1 = 25 n2= 15
Tags:
Swap two numbers in java
Swap two in java
Swapping in java
Java program to swap two numbers.
Java swapping program
Java swap
Swap in java
0 K comment
Post a Comment