Tuesday, September 8, 2015

Java program to swap two numbers

This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below.

Swapping using temporary or third variable


import java.util.Scanner;   
class SwapNumbers { 
public static void main(String args[]) { 
int x, y, temp; 
System.out.println("Enter x and y"); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt();   
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);   
temp = x; 
x = y; 
y = temp;   
System.out.println("After Swapping\nx = "+x+"\ny = "+y); 
} 
}
Output of program:


Swapping without temporary variable

import java.util.Scanner;   
class SwapNumbers { 
public static void main(String args[]) { 
int x, y; 
System.out.println("Enter x and y"); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt();   
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);   
x = x + y; 
y = x - y; 
x = x - y;   
System.out.println("After Swapping\nx = "+x+"\ny = "+y); 
} 
}
Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc.

Related Posts:

  • Java methods Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will… Read More
  • 10 Major Differences Between C And JAVA Here are the major differences between C And JAVA. 1. JAVA is Object-Oriented while C is procedural. Different Paradigms, that is. Most differences… Read More
  • Java while loop Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. … Read More
  • Comparing C++ and Java Many developers already have experience with an object-oriented programming language like C++. As you make the transition to Java, you will encounter… Read More
  • Using multiple classes in Java program Java program can contain more than one i.e. multiple classes. Following example Java program contain two classes: Computer and Laptop. Both classes h… Read More

0 Comments:

Post a Comment