Swap two numbers without using third variable in java
Step 1
Let's open the notepad and write the following code:
Let's try to find the error in this program. if we write the small 's' on the place of capital 'S'.
- 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);
- }
- }
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).

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

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

- 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);
- }
- }
Now write the following code for checking my java file is compiling or not.
- javac swap.java

Write the following code in the command prompt. Press enter and see the output.
- java demo
- // demo is a class name which is written in my "swap.java" file.
Output


Muhammad SiddiquiPosted Dec 21, 2019, 5:41 AM
Public class demo { int a=4; int b=3; public void run() { int a=this.b; int b=this.a; System.out.println("a=" +a+" b="+b); } public static void main(String[] args) { demo ob=new demo(); System.out.println("a="+ob.a); System.out.println("b="+ob.b); ob.run(); }
SubashPosted Sep 19, 2016, 7:47 AM
Nice
pari doostiPosted May 20, 2015, 4:41 AM
Hi,thx,Good code and one question..what does this sign "^" mean? is it power ? I'm new in java...
Nitesh KejriwalPosted May 4, 2015, 4:58 AM
Welcome to C# Corner.
Isham KhanPosted May 3, 2015, 12:25 PM
nice one
Santhakumar MunuswamyPosted May 3, 2015, 11:44 AM
Welcome
Santhakumar MunuswamyPosted May 3, 2015, 11:43 AM
Good start