Java program to swap the given numbers using only two variables
KW.java
importjava.util.Scanner;classKW{publicstaticvoidmain(Stringargs[]){floata,b;Scannersc=newScanner(System.in);System.out.println("———————————————————————————————————————————");System.out.println("Program to swap the given numbers");System.out.println("———————————————————————————————————————————");System.out.print("a = ");a=sc.nextFloat();System.out.print("b = ");b=sc.nextFloat();System.out.println("——————————————————————————");System.out.println("After swapping...");System.out.println("——————————————————————————");a+=b;b=a-b;a-=b;System.out.println("a = "+a+"\nb = "+b);System.out.println("———————————————————————————————————————————");}}
Output
kodingwindow@kw:~$ javac KW.java kodingwindow@kw:~$ java KW
———————————————————————————————————————————
Program to swap the given numbers
———————————————————————————————————————————
a = 10
b = -0.25
——————————————————————————
After swapping...
——————————————————————————
a = -0.25
b = 10.0
———————————————————————————————————————————
kodingwindow@kw:~$
Java program to swap the given numbers using three variables
KW.java
importjava.util.Scanner;classKW{publicstaticvoidmain(Stringargs[]){floata,b,c=0;Scannersc=newScanner(System.in);System.out.println("———————————————————————————————————————————");System.out.println("Program to swap the given numbers");System.out.println("———————————————————————————————————————————");System.out.print("a = ");a=sc.nextFloat();System.out.print("b = ");b=sc.nextFloat();System.out.println("——————————————————————————");System.out.println("After swapping...");System.out.println("——————————————————————————");c=a;a=b;b=c;;System.out.println("a = "+a+"\nb = "+b);System.out.println("———————————————————————————————————————————");}}
Output
kodingwindow@kw:~$ javac KW.java kodingwindow@kw:~$ java KW
———————————————————————————————————————————
Program to swap the given numbers
———————————————————————————————————————————
a = 25
b = -3.1428
——————————————————————————
After swapping...
——————————————————————————
a = -3.1428
b = 25.0
———————————————————————————————————————————
kodingwindow@kw:~$
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.
Dear User, We are grateful for your interest in the KodingWindow Android app. We intend to soon make it available on the Google Play Store. Currently, you need to install apk manually. Would you like to get the app? Minimum Requirement(s): Android 10