Knowledge Walls
John Peter
Pune, Maharashtra, India
Swap two numbers using one line/statement in JAVA
13990 Views
JAVA Example to Swap numbers without third Variable
public class SampleSwap {
    public static void main(String args[]) {
        int x = 10;
        int y = 20;
              
        y = (x+y) - (x=y);
        System.out.println("X = "+x+"; Y = "+y);
    }
}
How it works? 
Expressions are executing left to right.

Initially value is
x = 10; y = 20;

So.
    y = (x+y) - (x=y);
    y = (30) - (x=y);
    y = (30) - (20);  [Assign x=20; and taking this x value for expression]
    y = 10;

Now value is
x = 20; y = 10;
Previous Topics
Previous lessons of current book.
Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details