January 4 2017

Java program to swap two numbers

Java program to swap two numbers

Below is the Java program to swap two numbers using temporary or third variable.

Algorithm

1.  Take the input from the user(x, y)

2.Copy the value of x to third variable (z)

z = x;

3.Copy the value of y to x

x = y;

4.Copy the value of z (where x’s value is copied) to y

y = z;

Program

package com.answersz;

import java.util.Scanner;

public class JavaProgramToSwapTwoNumbers {

 public static void main(String[] args) {

 // Java program to swap two numbers

 int x, y, z;
 Scanner s = new Scanner(System.in);

 System.out.println("Enter value fox x and y :");
 x = s.nextInt();
 y = s.nextInt();

 System.out.println("Before Swapping x : " + x + " y : " + y);
 z = x;
 x = y;
 y = z;
 System.out.println("After Swapping x : " + x + " y : " + y);
 }

}

Output


Enter value fox x and y :
10
20
Before Swapping x : 10 y : 20
After Swapping x : 20 y : 10


Copyright © 2014. All rights reserved.

Posted January 4, 2017 by answersz in category Bluej Java Programs for ICSE Class 10 and 9 Practice

Leave a Comment

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

*