For the whole game the king walks one square at a time, in any of eight directions, and never onto a square an enemy piece attacks. Then once, if he has kept his right to it, he takes a two-square stride sideways and a rook jumps over him. The Laws say this plainly in Article 3.8: the king has two ways of moving, an ordinary step to an adjoining square, and castling.
Here is the second one, four moves into an Italian Game.
8
7
2
a
b
c
d
e
h 1 Queenside it is the same idea in the other direction: the king e1 to c1, again two squares, and the rook a1 to d1, three. Both count as a single move, and both are king moves, which is why you always touch the king first.
The five conditions
Castling is legal only when all of these hold. Neither the king nor that particular rook has moved at any point in the game. Every square between them is empty. The king is not in check right now. The square he crosses is not attacked. And the square he lands on is not attacked.
Two things on that list are not conditions, and beginners get both wrong. The rook is allowed to be attacked, and going queenside the rook is allowed to cross an attacked b1. Only the king’s three squares matter. And a king that was checked ten moves ago may still castle, as long as he never actually moved.
What this rule is not
It is not a get-out clause. You may not castle while in check, so a two-square hop is never an answer to a check. The three answers are the same three they always were: move, block, capture.
It is also not a free pass past the king’s ordinary law. The square he crosses and the square he lands on both have to be safe, because a king may never move into check, and castling does not suspend that for one turn.
If you want the mechanics in full, with the diagrams and the special cases, read what castling is and then the castling rules. If you want to see how often the two-square move decides a game, play through some castling puzzles: a startling number of tactics finish with O-O or O-O-O as the key move.