0% completed
Write a Java program to swap the values of two variables. For instance, if variable a holds the value 5 and variable b holds the value 10, after swapping, a should hold 10 and b should hold 5.
a = 5, b = 10a = 10, b = 5a and b are swapped.a = 3.14, b = 2.71a = 2.71, b = 3.14a and b are swapped.Swapping two variables using a temporary variable involves the following steps:
a and b be the two variables to be swapped.temp to hold the value of a.b to a.temp to b.a and b are now swapped.Below is the Java code that demonstrates how to swap two variables using a temporary variable.
Example 1: Swapping Integers
a is initialized to 5.b is initialized to 10.temp stores the value of a (temp = 5).a is assigned the value of b (a = 10).b is assigned the value stored in temp (b = 5).a holds 10.b holds 5.Example 2: Swapping Doubles
x is initialized to 3.14.y is initialized to 2.71.tempDouble stores the value of x (tempDouble = 3.14).x is assigned the value of y (x = 2.71).y is assigned the value stored in tempDouble (y = 3.14).x holds 2.71.y holds 3.14......
.....
.....