Swap two numbers without using third variable in java

In this article we learn how to swap two numbers without using third variable in java.

Step 1: Lets open the notepad and write the following code:
Lets try to find the error in this program. if we write the small ‘s’ on the place of capital ‘S’.

//code
class demo
{
public static void main(string arg[])
{
System.out.println(“Before swapping”);
int x=10;
int y=20;
System.out.println(“value of x:”+x);
System.out.println(“value of y:”+y);
system.out.println(“After swapping”);
x=x+y;
y=x-y;
x=x-y;
System.out.println(“value of x:”+x);
System.out.println(“value of y:”+y);
}
}
Step 2: Name it as “swap.java”and save the file in any location i saved at “c:/app”.

Step 3: Open command prompt(press window + R and write cmd and hit ok).

1

Step 4: Go to “c:/app” by using command prompt.

5

Step 5: Now write the following code for checking my java file is compiling or not.
javac swap.java

8

 

My java file is not compile successfully. because there are two error in this program.

So, let me write the program in a right way. and see the output.

//code
class demo
{
public static void main(String arg[])
{
System.out.println(“Before swapping”);
int x=10;
int y=20;
System.out.println(“value of x:”+x);
System.out.println(“value of y:”+y);
System.out.println(“After swapping”);
x=x+y;
y=x-y;
x=x-y;
System.out.println(“value of x:”+x);
System.out.println(“value of y:”+y);
}
}
Step 6: Now write the following code for checking my java file is compiling or not.
javac swap.java

6

My java program compiled successfully.
Step 7: write the following code in command prompt. prees enter and see the output.
java demo
// demo is a class name which is written in my “swap.java” file.
output

7

 

Happy coding.

Tags: , ,