Swap Logic 2 in Java

Table of Contents

Swap Logic 2 in Java

Compile and Run the following code with Command-Prompt Or download Notepad++

For Compilation javac Sample.java

For Execution java Sample

import java.util.Scanner;
class Sample
{
  public static void main(String[] args)
  {
    int x,y;//Without using third variable
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the value of x");
    x = sc.nextInt();
    System.out.println("Enter the value of y");
    y = sc.nextInt();
    System.out.println("Before swapping x= "+x+"and y ="+y);
    x = x + y;
    y = x - y;
    x = x - y;
    System.out.println("After swapping x= "+x+"and y ="+y); 
  }
}
Previous Swap Logic 1 in Java
Next Fibonacci Series in Java

Leave a Reply