# Java Code Example: tower of hanoi (recursive)

The game consists of three sticks, on which several perforated discs are placed, all of different sizes.
At the beginning, all the discs are on the left stick, arranged in order of size, with the largest disc on the bottom and the smallest on the top.
The object of the game is to move the entire stack of discs to the right stick.
However, only a smaller disc may be placed on a larger one, a larger one on a smaller one is not allowed.

In the `move` method, it first moves the `disc - 1` discs from the `from` peg to the `aux` peg using the recursive call. Then it moves the `disc` from the `from` peg to the `to` peg. Finally, it moves the `disc - 1` discs from the `aux` peg to the `to` peg using the recursive call.

In the `main` method, it calls the `move` method with `disc` equals to 4, `from` peg equals to “left”, `to` peg equals to “middle”, and `aux` peg equals to “right”.

``````public class TowerOfHanoi {
public static void move(int disc,
String from,
String to,
String aux) {
if (disc > 0) {
move(disc - 1, from, aux, to);
System.out.println("Disc " + disc + ": move from " + from + " to " + to);
move(disc - 1, aux, to, from);
}
}

public static void main(String[] args) {
move(4, "left", "middle", "rigth");
}
}``````
##### Output
``````Disc 1: move from left to rigth
Disc 2: move from left to middle
Disc 1: move from rigth to middle
Disc 3: move from left to rigth
Disc 1: move from middle to left
Disc 2: move from middle to rigth
Disc 1: move from left to rigth
Disc 4: move from left to middle
Disc 1: move from rigth to middle
Disc 2: move from rigth to left
Disc 1: move from middle to left
Disc 3: move from rigth to middle
Disc 1: move from left to rigth
Disc 2: move from left to middle
Disc 1: move from rigth to middle``````