Write a Java program to swap or exchange two numbers without using any temporary variable is a frequently asked Java interview question.
This post shows one way to solve this. Logic here is to get the sum of both the numbers in one of the variable, numbers can be swapped then by subtracting from that sum.
public class Swap { public static void main(String[] args) { int a = 7; int b = 8; System.out.println("value of a - " + a); System.out.println("value of b - " + b); // Swapping logic a = a + b; b = a - b; a = a - b; System.out.println("After swap value of a - " + a); System.out.println("After swap value of b - " + b); } }
Output
value of a - 7 value of b - 8 After swap value of a - 8 After swap value of b - 7
That's all for this topic Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment