Wednesday, 11 February 2026

Tutorial on Java program for swapping 2 integers

Swapping 2 integers with temporary variable



Swapping Technique:

If there are two variables with some integer values and needed to swap variable a's value in variable b and b's value to a

Swapping two integers with temporary variable is as easy 10 lines of code. It does not include any mathematical operations.


Example:


If variable a has value 10 and variable b has value 20, the algorithm, supposed to swap values in such a way, that variable a will have value 20 and variable b will have 10.

int a = 10; // variable a has 10 as a value

int b = 20; // variable b has 20 as a value


Code



package com.allabtjava.alg;


/**

* @author Nagasharath K

*/

public class Swap_With_Temp {

public static void main(String[] args) {

int a = 10;

int b = 20;

System.out.println("Variable a has " + a + "and b has " + b + "before swapping");

int temp = 0;

temp = a;

a = b;

b = temp;

System.out.println("After swapping variable a has " + a + " and b has " + b);

}


}


Output:


Variable a has 10 and b has 20 before swapping

After swapping variable a has 20 and b has 10



Swapping 2 integers without temporary variable

Now, let us swap 2 integers without the help of temporary variable.

This is possible by storing the difference between variable a and variable b and do the simple
mathamatical operation as done in the below program


Example:


package com.allabtjava.alg;


/**

* @author NAGASHARATH K

*/

public class Swap_Without_Temp {


public static void main(String[] args) {

int a = 70;

int b = 50;

System.out.println("Variable a has " + a + " and b has " + b + " before swapping");

int c = b - a;

a = a + c;

b = b - c;

System.out.println("After swapping variable a has " + a + " and b has " + b);

}


}



Output:


Variable a has 70and b has 50 before swapping

After swapping variable a has 50 and b has 70



Monday, 9 February 2026

Snake Game - Just for fun..!

Snake Game

SUDOKU - Just for fun!

Sudoku Game

On the launch of an application user is presented with three options: Easy, Medium and Hard. Easy has 30 numbers on board, medium has 50 and hard option will have only 20 numbers on board. Once the difficulty is selected user will be presented with a Sudoku board. Below the board there will be numbers which one can select to fill the blank spaces on the board. Note that only the correct number can be placed on the specific spot. Once the user fills all the blank spots on the board, means he has correctly solved the puzzle.

Tutorial on Java program for swapping 2 integers

Swapping 2 integers with temporary variable Swapping Technique: If there are two variables with some integer values and needed to swap varia...