How to fix illegal start of expression error in java

In this post, we will see how to fix "illegal start of expression" in java.

You will get this error while using javac command in command prompt. In eclipse or any other ide, it will give you more helpful compile time error.

There can be multiple reasons for getting this error.

Using private, public or protected modifiers inside a method

You might know that you can not use private, public or protected modifier inside a method. If you use it, you will get illegal start of expression.

When you run javac Command, you will get below error.

$javac MyClass.java
/MyClass.java:4: error: illegal start of expression
private int count=0;
^
1 error

When you use the same code in eclipse ide, you will get below error.

Illegal modifier for parameter count; only final is permitted

As you can see eclipse ide provides better information regarding this error.

Using method inside a method

You might know that you cannot have method inside another method. If you put it, you will get illegal start of expression.
Actually, it is again due to public static modifiers only

When you run javac Command, you will get below error.

$javac MyClass.java
MyClass.java:4: error: illegal start of expression
public static int count()
^
MyClass.java:4: error: illegal start of expression
public static int count()
^
MyClass.java:4: error: ‘;’ expected
public static int count()
^
MyClass.java:4: error: ‘;’ expected
public static int count()
^
4 errors

Forgot to add curly braces

If you forgot to add curly braces, you will get again get this error.

$javac MyClass.java
/MyClass.java:6: error: illegal start of expression
public static void myMethod()
^
/MyClass.java:6: error: illegal start of expression
public static void myMethod()
^
/MyClass.java:6: error: ‘;’ expected
public static void myMethod()
^
/MyClass.java:6: error: ‘;’ expected
public static void myMethod()
^
/MyClass.java:10: error: reached end of file while parsing
}
^
5 errors

but eclipse ide, you will get below error.

Syntax error, insert “}” to complete MethodBody

That’s all about illegal start of expression. I hope you will be able to solve the issue with the help of this post.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *