How To Swap The Values Of Two Variables In Java

I wrote an article on tricks to learn Java quickly, one of the tricks is to know and understand how to solve some problems using java.

One of the problems is swapping the values of variables and that is what you will see in this article.

I will like to show you the code before the explanation, read and try to understand each line of code if you can.

int a = 20;

int b = 30;

int c;

c = a;

a = b;

b = c;

System.out.println(“a = “+a+” b = “+b);

I declared an integer variable named ‘a’ and gave it a value 20. Same thing for b.

int a = 20;

int b = 30;

If you notice, c does not have a value yet.

int c;

Why?

The aim of this program is to swap the value of two variables, see it like when you want to swap the content in two buckets.

Let say two buckets are filled with water,  bucket a contains salt water and bucket b contains sugar water.

   int a = 20;

        int b = 30;

And you want to put the sugar water into bucket a and the salt water into bucket b.

The easiest solution is to get a third bucket which will be empty. Let call it bucket c.

  int c;

So you will pour the salt water in bucket a into bucket c.

c = a;

Now bucket a will be empty.

You then pour the sugar water in bucket b into bucket a.

a = b;

Now bucket b will be empty.

You then pour the salt water in bucket c into bucket b.

b = c;

The problem is solved. We have successfully exchanged the content of bucket a and b

The two buckets are the two variables I declared at the start of the program.

The last part of the program displays the value of the swapped variables to the screen.

System.out.println(“a = ” +a+ ” b = ” +b);

I hope you understand this short tutorial. Please tell me anything you don’t understand in the comment box below.

I would love to see your questions.

How To Swap The Values Of Two Variables In Java

Share via
Copy link
Powered by Social Snap