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'.

  1. class demo  
  2. {  
  3.     public static void main(string arg[])  
  4.     {  
  5.         System.out.println("Before swapping");  
  6.         int x=10;  
  7.         int y=20;  
  8.         System.out.println("value of x:"+x);  
  9.         System.out.println("value of y:"+y);  
  10.         system.out.println("After swapping");  
  11.         x=x+y;  
  12.         y=x-y;  
  13.         x=x-y;  
  14.         System.out.println("value of x:"+x);  
  15.         System.out.println("value of y:"+y);  
  16.     }  
  17. }  
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).



Step 4

Go to "c:/app" by using command prompt.



Step 5

Now write the following code for checking my java file is compiling or not.

  1. javac swap.java  



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.

  1. //code  
  2. class demo  
  3. {  
  4.     public static void main(String arg[])  
  5.     {  
  6.         System.out.println("Before swapping");  
  7.         int x=10;  
  8.         int y=20;  
  9.         System.out.println("value of x:"+x);  
  10.         System.out.println("value of y:"+y);  
  11.         System.out.println("After swapping");  
  12.         x=x+y;  
  13.         y=x-y;  
  14.         x=x-y;  
  15.         System.out.println("value of x:"+x);  
  16.         System.out.println("value of y:"+y);  
  17.     }  
  18. }  
Step 6

Now write the following code for checking my java file is compiling or not.

  1. javac swap.java  



My java program compiled successfully.

Step 7

Write the following code in command prompt. prees enter and see the output.

  1. java demo    
  2. // demo is a class name which is written in my "swap.java" file.  

Output



Happy coding. 

Ebook Download
View all
Learn
View all