How do you swap two numbers without using third variable in java?
Swapping numbers without using a third variable is a three-step process that’s better visualized in code:
b = b + a; // now b is sum of both the numbers
a = b – a; // b – a = (b + a) – a = b (a is swapped)
b = b – a; // (b + a) – b = a (b is swapped)
The following example code shows one way to implement the number swap method:
public class SwapNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(“a is ” + a + ” and b is ” + b);
a = a + b;
b = a – b;
a = a – b;
System.out.println(“After swapping, a is ” + a + ” and b is ” + b);
}
}
The output shows that the integer values are swapped:
Output
a is 10 and b is 20
After swapping, a is 20 and b is 10
Why Choose Us
- 100% non-plagiarized Papers
- 24/7 /365 Service Available
- Affordable Prices
- Any Paper, Urgency, and Subject
- Will complete your papers in 6 hours
- On-time Delivery
- Money-back and Privacy guarantees
- Unlimited Amendments upon request
- Satisfaction guarantee
How it Works
- Click on the “Place Your Order” tab at the top menu or “Order Now” icon at the bottom and a new page will appear with an order form to be filled.
- Fill in your paper’s requirements in the "PAPER DETAILS" section.
- Fill in your paper’s academic level, deadline, and the required number of pages from the drop-down menus.
- Click “CREATE ACCOUNT & SIGN IN” to enter your registration details and get an account with us for record-keeping and then, click on “PROCEED TO CHECKOUT” at the bottom of the page.
- From there, the payment sections will show, follow the guided payment process and your order will be available for our writing team to work on it.