1. Java Interview Program to Swap two numbers without using third variable in java
Output:
Output:
Output:
- package com.instaceofjava;
- public class SwapTwoNumbers {
- public static void main(String[] args) {
- int number1=20;
- int number2=30;
- System.out.println("Before Swapping");
- System.out.println("Value of number1 is :" + number1);
- System.out.println("Value of number2 is :" +number2);
- number1=number1+number2;
- number2=number1-number2;
- number1=number1-number2;
- System.out.println("After Swapping");
- System.out.println("Value of number1 is :" + number1);
- System.out.println("Value of number2 is :" +number2);
- }
- }
- Before Swapping
- Value of number1 is :20
- Value of number2 is :30
- After Swapping
- Value of number1 is :30
- Value of number2 is :20
2. Java Program to Swap two numbers by using division and multiplication.
- package com.instaceofjava;
- public class SwapTwoNumbers {
- public static void main(String[] args) {
- int number1=20;
- int number2=30;
- System.out.println("Before Swapping");
- System.out.println("Value of number1 is :" + number1);
- System.out.println("Value of number2 is :" +number2);
- number1=number1*number2;
- number2=number1/number2;
- number1=number1/number2;
- System.out.println("After Swapping");
- System.out.println("Value of number1 is :" + number1);
- System.out.println("Value of number2 is :" +number2);
- }
- }
Output:
- Before Swapping
- Value of number1 is :20
- Value of number2 is :30
- After Swapping
- Value of number1 is :30
- Value of number2 is :20
3. Java Program to Swap two integers by using bit wise operators
- package com.instaceofjava;
- public class SwapTwoNumbers {
- public static void main(String[] args) {
- int number1=2;
- int number2=4;
- System.out.println("Before Swapping");
- System.out.println("Value of number1 is :" + number1);
- System.out.println("Value of number2 is :" +number2);
- number1=number1^number2;
- number2=number1^number2;
- number1=number1^number2;
- System.out.println("After Swapping");
- System.out.println("Value of number1 is :" + number1);
- System.out.println("Value of number2 is :" +number2);
- }
- }
- Before Swapping
- Value of number1 is :2
- Value of number2 is :4
- After Swapping
- Value of number1 is :4
- Value of number2 is :2
1) and 2) doesn't work for all valid integers.
ReplyDeleteTake for 1) the following numbers: 1 and Integer.MAX_VALUE
Take for 2) the following numbers: any integer and 0
3) Could work
The first method is working fine with large values.
DeleteI have tested with Integer.MAX_VALUE-20 and Integer.MAX_VALUE using JRE 1.8.0
Calculation :
x = x + y
= 2147483627 + 2147483647
= -22
y = x - y
= -22 - 2147483647
= 2147483627 (don't know how JVM calculated this)
x = x - y
= -22 - 2147483627
= 2147483647 (don't know how JVM calculated this)
I am trying to figure out how JVM calculates it. If someone knows the calculation logic. Please explain.
you Still trying ??
Delete