Java Examples

100+ tutorials, source code, and examples to help you develop creative and technical skills.

Java Program to swap two numbers from user input

SwapNumbers.java

/* Code From Learnoset - Learn Code Online Android App.*/
/*Download Learnoset App from PlayStore to learn coding*/

/*Java Program to swap two numbers from user input*/
import java.util.Scanner;

public class SwapNumbers {

    public static void main(String[] args) {

        int a, b; // declare 2 int type variables a, b. a and b will hold the input from user

        Scanner scanner = new Scanner(System.in); // Create an object of Scanner class

        System.out.println("Enter First Number");
        a = scanner.nextInt(); // initialize a variable with first number entered by user.

        System.out.println("Enter Second Number");
        b = scanner.nextInt(); // initialize b variable with second number entered by user.


        System.out.println("--Before swap--");
        System.out.println("First number = " + a);
        System.out.println("Second number = " + b);

        /* create another variable and name it temporary. 
		'a' variable will give its value to
		'temporary' variable because 'a' will hold the value of 'b'
		variable. and we don't want previous value of 'a' to be 
		lost or replaced by new value of 'b' variable that's why we created a 'temporary'. Once 'b'
		will give its value to 'a' variable then 'b' will get value from temporary variable*/
        int temporary = a; // here we are plassing the value to 'a' to 'temporary'. now a is ready to hold another value of 'b'

        a = b; // Here 'a' is replacing by value of 'b' and 'b' is ready to take value of 'a' from 'temporary' variable

        // Value of temporary (which contains the initial value of a) is assigned to b
        b = temporary;

        System.out.println("--After swap--");
        System.out.println("First number = " + a);
        System.out.println("Second number = " + b);
    }
}

/*----------OUTPUT----------
Enter First Number
5
Enter Second Number
10
--Before swap--
First number = 5
Second number = 10
--After swap--
First number = 10
Second number = 5
*/

Projects with Source Code + Video Tutorials

You can download our Java and Android Studio Projects with Source Code and Video Tutorials.

Login-and-Register-using-Firebase-Realtime-Database
Login and Register using Firebase Realtime Database
Sound-Recorder-App-in-Android-Studio-----------
Sound Recorder App in Android Studio
How-to-create-Modern-Login-and-Register-screen-in-Android-Studio-|-Material-UI-Design-|-Part---06
How to create Modern Login and Register screen in Android Studio | Material UI Design | Part - 06

If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com

Follow us to learn Coding and get in touch with new Technologies.