Home › Java

error: illegal start of expression (Java) — how to fix

Main.java:7: error: illegal start of expression
    public int count = 0;
    ^
Main.java:12: error: illegal start of expression
    public static void helper() {
    ^

Quick fix: Look at the lines above the caret: close the previous method with } before the next method starts, remove public/private/static from variables declared inside a method, and check for stray semicolons or unbalanced parentheses. Auto-format (Ctrl+Alt+L in IntelliJ, Shift+Alt+F in VS Code) to spot the brace.

What it means

The Java parser expected an expression or statement and found something that can't start one, such as public, private, static, a closing brace or an operator. The real mistake is usually before the line javac points at, because the parser only notices when the next token makes no sense.

Cause 1: missing closing brace before the next method

public class Main {
    public static void main(String[] args) {
        System.out.println("hi");
    // missing }

    public static void helper() {   // error: illegal start of expression
    }
}

Because main is never closed, public static void helper() appears inside main. Add the missing }. Auto-formatting the file makes the mismatched indentation obvious; most IDEs also highlight the matching brace when the cursor is on one.

Often you'll also see class, interface, enum, or record expected near the end of the file from the same missing brace.

Cause 2: method defined inside a method

Even with correct braces, Java doesn't allow named methods inside methods:

void process() {
    int square(int x) { return x * x; }   // illegal
}

Move it to class level:

int square(int x) { return x * x; }

void process() {
    int y = square(4);
}

Or use a lambda if you need a local function: IntUnaryOperator square = x -> x * x;

Cause 3: access modifier on a local variable

void run() {
    public int count = 0;      // illegal start of expression
    private String name = "";  // same
}

Local variables can't be public, private, protected or static. Either remove the modifier, or move the declaration to the class as a field:

public class Counter {
    private int count = 0;

    void run() {
        int local = 0;
    }
}

final is allowed on locals.

Cause 4: stray or missing punctuation

int total = a + ;      // illegal start of expression
String s = "a" + + ;   // same
method(a, , b);        // empty argument

Check the line for operators without operands, doubled commas and unbalanced parentheses.

Cause 5: syntax from another language

Constructs from other languages trigger this or similar parse errors: x => x + 1 (Java uses ->), === (use == or .equals()), or default parameter values like void f(int a = 0) (overload the method instead).

Tip

Fix the first error javac reports and recompile. One missing brace can produce a dozen follow-up errors that disappear together.

Last updated 2026-12-01.