Swapping the values of two variables involves the exchange of their values. For example, assume that a == 5; and b == 10; If the values of these variables were swapped, the resultant values would be: a == 10; b == 5.
Write a program to initialise two memory locations with values 10 and 5 before then swapping them without the use of a third memory location using:
// Java program to swap two numbers without using third memory location
import java.*;
class Swap {
public static void main(String a[])
{
int a = 10;
int b = 5;
a = a + b;
b = a - b;
a = a - b;
}
}
Local Variable indices: a = 10, b = 5.
Java | IJVM Assembly | IJVM ISA |
ILOAD a | 0X15 0X02 | |
{ | ILOAD b | 0X15 0X03 |
a = a + b; | IADD | 0X60 |
ISTORE a | 0X36 0X02 | |
ILOAD a | 0X15 0X02 | |
ILOAD b | 0X15 0X03 | |
b = a - b; | ISUB | 0X64 |
ISTORE b | 0X36 0X03 | |
ILOAD a | 0X15 0X02 | |
ILOAD b | 0X15 0X03 | |
a = a - b; | ISUB | 0X64 |
} | ISTORE a | 0X36 0X02 |
Output : a = 5, b = 10.
Get Answers For Free
Most questions answered within 1 hours.