Table of Contents
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.
1 2 3 4 5 6 7 |
public class MyClass { public static void main(String[] args) { private int count=0; } } |
When you run javac Command, you will get below error.
/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.
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
1 2 3 4 5 6 7 8 9 10 |
public class MyClass { public static void main(String[] args) { public static int count() { return 0; } } } |
When you run javac Command, you will get below error.
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.
1 2 3 4 5 6 7 8 9 10 11 |
public class MyClass { public static void main(String args[]) { int count=0; public static void myMethod() { System.out.println("My method"); } } |
/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.
That’s all about illegal start of expression. I hope you will be able to solve the issue with the help of this post.