To swap two variables in Java, you can use a temporary variable to hold the value of one of the variables before swapping. Here's an example Java program that swaps the values of two variables:
public class SwapVariables { public static void main(String[] args) { int a = 5; int b = 10; System.out.println("Before swapping: a = " + a + ", b = " + b); int temp = a; a = b; b = temp; System.out.println("After swapping: a = " + a + ", b = " + b); } }
In this program, we declare two integer variables a
and b
with initial values of 5 and 10 respectively. We then print out the values of a
and b
before swapping.
We then declare a temporary variable temp
to hold the value of a
. We then assign the value of b
to a
, and finally assign the value of temp
(which is the original value of a
) to b
.
Finally, we print out the values of a
and b
after swapping.
When we run this program, the output should be:
Before swapping: a = 5, b = 10 After swapping: a = 10, b = 5
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.