How to Build a Tic Tac Toe Game in Java: Step-by-Step Guide for Beginners

May 30, 2025

How to Build a Tic Tac Toe Game in Java: Step-by-Step Guide for Beginners
How to Build a Tic Tac Toe Game in Java: Step-by-Step Guide for Beginners
Read: The Advantages of After-School Coding Programs for Teens
Read: What is the Right Age to Start Coding?
Read: The Ultimate Guide to Choosing the Best After-School Program for Your Kids in 2025
Read: Why Every Teenager Should Learn Coding: Top Benefits for Teens and Parents
Read: What is the Most Popular After-School Activity?
Read: The Advantages of After-School Coding Programs for Teens
Read: What is the Right Age to Start Coding?

If you’re learning Java and want a fun way to practice your coding skills, building a Tic Tac Toe game is a fantastic project! It’s simple enough to understand but also helps you get comfortable with key programming concepts like arrays, loops, conditionals, and user input.

In this blog post, I’ll walk you through how to create a console-based Tic Tac Toe game in Java. By the end, you’ll have a working game where two players can take turns and the program will detect wins or ties.

What is Tic Tac Toe?

Tic Tac Toe is a classic 2-player game played on a 3x3 grid. Players take turns placing their symbol — usually “X” or “O” — on an empty cell. The first to get three in a row (horizontally, vertically, or diagonally) wins. If all cells fill up without a winner, it’s a draw.

It’s a great beginner project because:

  • The rules are simple and easy to implement.

  • You can practice array manipulation and game logic.

  • You get to work with user input and display output.

Planning Our Java Tic Tac Toe Game

Before jumping into code, let’s outline what our program needs to do:

  1. Display the board — a 3x3 grid showing current moves.

  2. Take turns — alternate between Player X and Player O.

  3. Get user input — ask players where they want to place their symbol.

  4. Validate moves — ensure players choose empty cells and valid positions.

  5. Check for a winner — after each move, check if a player has won.

  6. Check for a draw — if all cells are filled and no winner, declare a tie.

  7. Repeat until the game ends.

The Java Code: Step-by-Step

Here’s a simple, clear Java program to play Tic Tac Toe in the console:

import java.util.Scanner;

public class TicTacToe {

    static char[][] board = new char[3][3];
    static char currentPlayer = 'X';

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        initializeBoard();

        boolean gameEnded = false;

        while (!gameEnded) {
            printBoard();

            System.out.println("Player " + currentPlayer + ", enter your move (row and column: 1 1 for top-left):");
            int row = scanner.nextInt() - 1; // subtract 1 to convert to 0-based index
            int col = scanner.nextInt() - 1;

            if (isValidMove(row, col)) {
                board[row][col] = currentPlayer;

                if (hasWon(currentPlayer)) {
                    printBoard();
                    System.out.println("Player " + currentPlayer + " wins! Congratulations!");
                    gameEnded = true;
                } else if (isBoardFull()) {
                    printBoard();
                    System.out.println("It's a tie!");
                    gameEnded = true;
                } else {
                    // Switch player
                    currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
                }
            } else {
                System.out.println("Invalid move! The cell is either occupied or out of bounds. Try again.");
            }
        }

        scanner.close();
    }

    // Initialize board with empty spaces
    public static void initializeBoard() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                board[i][j] = ' ';
            }
        }
    }

    // Print the current state of the board
    public static void printBoard() {
        System.out.println("-------------");
        for (int i = 0; i < 3; i++) {
            System.out.print("| ");
            for (int j = 0; j < 3; j++) {
                System.out.print(board[i][j] + " | ");
            }
            System.out.println();
            System.out.println("-------------");
        }
    }

    // Check if the move is valid
    public static boolean isValidMove(int row, int col) {
        if (row < 0 || col < 0 || row >= 3 || col >= 3) {
            return false;
        }
        return board[row][col] == ' ';
    }

    // Check if the player has won
    public static boolean hasWon(char player) {
        // Check rows
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == player &&
                board[i][1] == player &&
                board[i][2] == player) {
                return true;
            }
        }

        // Check columns
        for (int j = 0; j < 3; j++) {
            if (board[0][j] == player &&
                board[1][j] == player &&
                board[2][j] == player) {
                return true;
            }
        }

        // Check diagonals
        if (board[0][0] == player &&
            board[1][1] == player &&
            board[2][2] == player) {
            return true;
        }

        if (board[0][2] == player &&
            board[1][1] == player &&
            board[2][0] == player) {
            return true;
        }

        return false;
    }

    // Check if the board is full (tie condition)
    public static boolean isBoardFull() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    return false;
                }
            }
        }
        return true;
    }
}

How the Code Works

Let’s break down the main parts so you understand what’s happening:

1. Board Initialization

The board is a 3x3 2D char array initialized with spaces ' ' to represent empty cells.

static char[][] board = new char[3][3];

We fill it with spaces using initializeBoard().

2. Printing the Board

The printBoard() method draws the board with nice separators so players can see the current state after each move.

3. Player Input and Move Validation

In the main loop, we ask the current player to input a row and column (1-3). We subtract 1 to convert that to zero-based array indices.

Then, isValidMove() checks if the position is inside the board and unoccupied.

4. Making Moves and Checking Game Status

If the move is valid, we update the board. Then:

  • Use hasWon() to see if the current player has won by checking all rows, columns, and diagonals.

  • Use isBoardFull() to detect ties if no empty cells remain.

If the game continues, switch the player and repeat.

5. Game End

If someone wins or the board is full, the game announces the result and ends.

How You Can Improve This Tic Tac Toe Game

Now that you have a working Tic Tac Toe game, here are some ways you could expand it:

  • Add input error handling: Prevent the program from crashing if users enter invalid data (like letters).

  • Create a graphical user interface (GUI): Use Java Swing or JavaFX to build a visual Tic Tac Toe board instead of the console.

  • Add a single-player mode: Let the player compete against a computer opponent with basic AI.

  • Track scores: Keep score over multiple rounds.

  • Enhance UI: Print row and column labels to make it easier to select positions.

Why Build Tic Tac Toe?

Tic Tac Toe is more than just a simple game — it’s a perfect project to sharpen your programming fundamentals. You’ll practice:

  • Using arrays and loops

  • Handling user input and validating it

  • Implementing game logic with conditionals

  • Structuring your program with methods

  • Debugging and testing your code

And the best part? You get a fun, interactive project that you can play with and show off!

If you’re new to Java or programming in general, building games like Tic Tac Toe is a fantastic way to learn. It’s approachable but also introduces you to important concepts that will help you tackle bigger projects later.

Try running the code above, see how it works, and then experiment by adding your own features. Coding is all about experimenting, breaking things, and fixing them — and each step you take brings you closer to becoming a confident programmer.

Read: Coding for 9-Year-Olds: A Parent’s Guide to Getting Started
Read: Why Every Teenager Should Learn Coding: Top Benefits for Teens and Parents
Read: What is the Most Popular After-School Activity?
Read: The Advantages of After-School Coding Programs for Teens
Read: What is the Right Age to Start Coding?
Read: The Ultimate Guide to Choosing the Best After-School Program for Your Kids in 2025

Pinecone Coding Academy's Kids Coding Classes and Camps

At Pinecone Coding Academy, we are passionate about making coding accessible and enjoyable for kids aged 8-17. Our program is designed to inspire and equip young learners with the skills they need to thrive in the digital world.

Click here to discover a coding class that matches your teen's or child's interests.

What We Offer:

  • Engaging Curriculum: Our courses introduce students to popular programming languages like Python, JavaScript, and HTML/CSS, laying a strong foundation for future learning.

  • Hands-On Projects: Students participate in project-based learning, creating real applications that they can showcase, from interactive games to personal websites.

  • Mentorship and Support: Our experienced instructors provide guidance, helping students navigate challenges and discover their coding potential.

  • Community Connection: By joining Pinecone, students become part of a vibrant community of peers, fostering collaboration and friendship as they learn.

More blogs

The secret to getting ahead is getting started

Our free session gives your child the chance to ignite their curiosity and excitement for coding, guided by our talented instructors. It's a fantastic opportunity to explore the world of programming in a fun and engaging environment!

The secret to getting ahead is getting started

Our free session gives your child the chance to ignite their curiosity and excitement for coding, guided by our talented instructors. It's a fantastic opportunity to explore the world of programming in a fun and engaging environment!

The secret to getting ahead is getting started

Our free session gives your child the chance to ignite their curiosity and excitement for coding, guided by our talented instructors. It's a fantastic opportunity to explore the world of programming in a fun and engaging environment!