Java Tutorial

Java Project: Tic-Tac-Toe

A 3x3 board as a 2D array of strings. Place marks, print the grid, and detect a winner.

What you will build

Print a board, place two marks, and check a row for a winner.

Board and winner

Example

public class Main {
  static void show(String[][] b) {
    for (String[] row : b) {
      System.out.println(String.join(" | ", row));
    }
  }

  static String winner(String[][] b) {
    for (int i = 0; i < 3; i++) {
      if (!b[i][0].equals(" ") && b[i][0].equals(b[i][1]) && b[i][1].equals(b[i][2])) return b[i][0];
      if (!b[0][i].equals(" ") && b[0][i].equals(b[1][i]) && b[1][i].equals(b[2][i])) return b[0][i];
    }
    return " ";
  }

  public static void main(String[] args) {
    String[][] b = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
    b[0][0] = "X";
    b[1][1] = "O";
    b[0][1] = "X";
    b[0][2] = "X";
    show(b);
    System.out.println("winner: " + winner(b));
  }
}

Practice

  1. Compile the complete program at /java/try.
  2. Change one input value and compile again.
  3. Replace a hardcoded number with Scanner when you want typed input.

FAQ: Java Project: Tic-Tac-Toe

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java tictactoe project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java tictactoe project in this Java Java lesson (Java Project: Tic-Tac-Toe).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.