How to fix "illegal start of expression" error in Java

The "illegal start of expression" error is a compile time error when the compiler finds an inappropriate statement in the code. The java compiler, javac, compiles your source code from top to bottom, left to right and when it sees something inappropriate at the start of an expression, it throws "illegal start of expression" error. The most common reason of this is a missing semi-colon. You might know that every statement in Java ends with a semicolon, but if you forget one, you won't get an error that there is a missing semi-colon at the end of statement because the compiler doesn't know the end. When compiler checks the next statement it sees illegal start because an earlier statement was not terminated. The bad part is that you can get tens of "illegal start of expression" error by just omitting a single semi-colon or missing braces, as shown in the following example.

public class Main {

  public static void main(String[] args) {
    count();
  

  public static int count() {
    return 0;
  }

}

If you compile this program you will be greeted with several "illegal start of expression" error as shown below:



$ javac Main.java
Main.java:7: error: illegal start of expression
  public static int count() {
  ^
Main.java:7: error: illegal start of expression
  public static int count() {
         ^
Main.java:7: error: ';' expected
  public static int count() {
               ^
Main.java:7: error: ';' expected
  public static int count() {
                           ^
Main.java:11: error: reached end of file while parsing
}
 ^
5 errors

And the only problem is a missing braces in main method, as soon as you add that missing closing curly brace in main method the code will work fine and all these error will go away, as shown below:

How to fix "illegal start of expression" error in Java


The error message is very interesting, if you look at the first one, you will find that error is in line 7 and compiler complaing about public keyword but actual problem was in line 5 where a closing brace is missing. From compiler's view, public should not come there becase its an invalid keyword inside a method in Java, remember without closing braces main() is still not closed, so compiler think public keyword is part of the main() method.

Though, when you compile the same program in Eclipse, you get different error because it's compiler is slightly differnet than javac but the error message is more helpful as you can see below:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete MethodBody

at Main.main(Main.java:4)


In short, the "illegal start of expression" error means compiler find something inappropriate, against the rules of Java programming but the error message is not very helpful. For "illegal start of expression" errors, try looking at the lines preceding the error for a missing ')' or '}' or missing semicolon. Also remember, a single syntax error somewhere can cause multiple "illegal start of expression" error. Once you fix the root cause, all error will go away. Which means always recompile once you fix an error, don't try to make multiple changes without compilation.

Other Java troubleshooting guides you may like:
  • How to fix "variable might not have been initialized" error in Java? (solution)
  • Could not create the Java virtual machine Invalid maximum heap size: -Xmx (solution)
  • How to fix class, enum, or interface expected error in Java? (solution)
  • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory (solution)
  • Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java (solution)
  • Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg' (solution)
  • java.lang.OutOfMemoryError: Java heap space : Cause and Solution (steps)
  • How to avoid ConcurrentModificationException while looping over List in Java? (solution)


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

37 comments:

  1. thanks this really helped alot

    ReplyDelete
  2. System.out.println("I'm fine.";) What I'm I missing

    it should look like (I'm fine). on the display

    ReplyDelete
    Replies
    1. your semicolon is inside the parentheses, and if you want to see the parentheses you will have to put it inside the " " cause it only prints whats inside those

      Delete
  3. here is my program please tell what is the mistake...


    class marks
    {
    void main(int a)
    {
    if (a>40)
    System.out.println("pass");
    }
    else
    {
    System.out.println("fail");
    }
    }

    ReplyDelete
    Replies
    1. couple of mistakes, first 1. class is not close with "}" which is missing
      2. syntax of main method is not correct, if you really intent to use main() method

      Delete
  4. // whats the mistakes?
    // Java program to Draw a
    // Smiley using Java Applet
    import java.applet.*;
    import java.awt.*;
    import java.util.*;

    class Rextester
    {
    public static void main(string[] args)
    {
    public class Rextester extends Applet {
    public void paint(Graphics g)
    {
    // Oval for face outline
    g.drawOval(80, 70, 150, 150);
    // Ovals for eyes
    // with black color filled
    g.setColor(Color.BLACK);
    g.fillOval( 120, 120, 15, 15);
    g.fillOval(170, 120, 15, 15);
    // Arc for the smile
    g.drawArc(130,180,50,20,180,180);
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. you are declaring a class inside a static method, that cannot be public.

      Delete
    2. S would be capital in main(String args[])

      Delete
  5. Hi, may I know what is the mistakes?

    public class Recognizer {
    public static void main(String[] args)
    {
    private static final int MAXN=10;
    private static final int MAXNUM=9;
    private static final int[][][][] count=new int[MAXN][MAXN][2][MAXNUM+1];
    private static final int[] count2=new int[MAXNUM+1];
    private static final double[][][][] po=new double[MAXN][MAXN][2][MAXNUM+1];
    private static final double[] po2=new double[MAXNUM+1];


    public static double[] recognize(boolean[][] input)
    {
    double[] result=new double[MAXNUM+1];
    for (int i=0;i<=MAXNUM;i++)
    {
    result[i]=1;
    for (int j=0;j<MAXN;j++)
    for (int k=0;k<MAXN;k++)
    if (input[j][k])
    result[i]*=po[j][k][1][i];
    else
    result[i]*=po[j][k][0][i];
    result[i]*=po2[i];
    }
    return result;
    }
    }
    }

    ReplyDelete
  6. Guys can you help me? What the wrong mistake in my code :(

    public class BubbleSort {
    public String version()
    { return "1.2.02";}
    static void BubbleSort(int[] angka) {
    for (int i = 0; i < angka.length; i++) {
    for (int j = 0; j < angka.length-1; j++) {
    if (angka[j]>angka[j+1]){
    int temp = angka [j];
    angka [j] = angka[j+1];
    angka[j+1] = temp;

    }

    }
    }
    main(String[] .class); {
    int [] angka=(9);

    for (int i = 0; i < angka.length; i++){
    System.out.print(angka[i]+" ");
    }
    };
    System.out.println("");
    BubbleSort(angka);
    for (int i = 0; i < angka.length; i++){
    System.out.print(angka[i]+" ");
    });
    }
    }

    ReplyDelete
  7. import java.io.*;
    import java.util.*;
    class calci{
    int a,b,c,d,e,f,g;{
    Scanner cal= new Scanner(System.in);
    System.out.println("Enter the first number :");
    a = cal.nextInt();
    System.out.println("Enter the second number :");
    b = cal.nextInt();

    public static int add()
    {
    c=a+b;
    System.out.println("Addition of 2 numbers is"+c);
    return c;
    }

    public static void sub()
    {
    d=a-b;
    System.out.println("Subtraction of 2 numbers is ="+d);
    return d;
    }
    public static int mul()
    {
    e=a*b;
    System.out.println("Multiplication of 2 numbers is ="+e);
    return e;
    }

    public static int div()
    {
    f=a/b;
    System.out.println("Division of 2 numbers is ="+f);
    return f;
    }

    public static int mod()
    {
    g=a%b;
    System.out.println("Modulo of 2 numbers is ="+g);
    return g;
    }
    }
    }



    class calculator_2{
    public static void main(String [] args){
    int ch;
    System.out.println("1.ADDITION \n2.SUBTRACTION \n3.MULTIPLICATION \n4.DIVISION \n5.MODULO");
    calci obj=new calci();
    Scanner in =new Scanner(System.in);
    System.out.println("Enter Your Choice :\t");
    ch = in.nextInt();

    switch(ch)
    {
    case 1: obj.add();
    break;
    case 2: bj.sub();
    break;
    case 3: obj. mul();
    break;
    case 4: obj.div();
    break;
    case 5: obj.mod();
    break;
    default :System.out.println("option not avilable");
    break;
    }
    }
    }

    ReplyDelete
  8. My program is showing error in public static void

    ReplyDelete

  9. 1
    public class temperature
    2
    {
    3
    public static void main(String []args)
    4
    {
    5
    double tempC,tempF;
    6
    if(choice==0)
    7
    {
    8
    tempC = 37;
    9
    tempF = (tempC*1.8F)+32;
    10
    System.out.println("temperature in farenheit is " +tempF);
    11
    }
    12
    else if (choice==2)
    13
    {
    14
    tempF = 98.4;
    15
    tempC = (tempF-32)/1.8F;
    16
    System.out.println("farenheit in temperature is " +tempC);
    17
    }
    18
    else
    19
    System.out.println("enter 1 for-C-to -F and 2 for F-to -C conversion");
    20
    }
    21
    }
    22

    23

    This code is editable. Click Run to Compile + Execute
    Line 7: error: illegal start of expression
    if(choice = =0 )
    ^
    Line 13: error: illegal start of expression
    else if (choice = = 2)
    ^
    2 errors



    what are the mistakess in this?

    ReplyDelete
    Replies
    1. because you have not declared the "choice" variable before using it. Just declare choice at the first line of main method like int choice = 0 it will work.

      like
      int choice=0;

      double tempC, tempF;

      if (choice == 0)

      {

      Delete
  10. import java.util.Scanner;
    class salpha{
    public static void main(String args[]){
    Scanner b=new Scanner(System.in);
    System.out.println("enter size");
    int n;
    n=b.nextInt();
    for(int i=0;i<=n;i++){
    for(int j=0;j<=n;j++){
    if(( i==0||i==n)&& i!=0 ||i==0 &&j!=0 && j!=n||)


    System.out.print("*");
    else

    System.out.print(" ");




    }
    System.out.println();

    }
    }
    }

    IT WAS SHOWING MISTAKE AT IF ILLEGAL START OF EXPRESSION

    ReplyDelete
  11. You can also get this for the -> Symbol in removeIf.. When using Java version < 8...

    ReplyDelete
    Replies
    1. absolutely true, and the judging system of my university uses Java 1.8...

      Delete
  12. public static void main(String [] args){
    System.out.println("your art goes here");
    System.out.println("across many lines");
    }
    . ________ .
    System.out.println(" /\\ / \\ \\\\ \\ / \\");
    System.out.println(" / \\ / . \\ _____ \\ ____ \\ / . \\");
    System.out.println("/ | \\ \\ / / \\___\\ / / | | \\ | / / \\___\");
    System.out.println("| | \\ | | | / / \\ | | | | | |");
    System.out.println("| | \\ | | | / /_____ | | | | | |");
    System.out.println(" | |____| | \\ | | / / | | | | | |");
    System.out.println(" | ______ | | | /_____ / | | | | | |");
    System.out.println(" | | | | | | / / | | | | | |");
    System.out.println("| | | | | | ___ / / | | / | | | "); __");
    System.out.println("| | | | \\ \\./ / / / | |__/ | \\ \\./ /");
    System.out.println("/ \\ / \\ \\ / / / / / \\ /");
    System.out.println("\\./ \\./ \\./ / /________/ \\./ ");}


    can i know he error in that program

    ReplyDelete
  13. /* Leap year __________
    ____________ Created by Sourav Dutta*/

    import java.util.Scanner ;

    public class Program
    {
    public static void main(String[] args) {
    public static boolean isLeapYear(int year) {
    year=1600;

    if (year % 4 != 0) {
    return false;
    }
    else if (year % 400 == 0) {
    return true;
    }
    else if (year % 100 == 0) {
    return false;
    }
    else {
    return true;}


    }}}

    ReplyDelete
    Replies
    1. Nice one Sourav, but you can optimize the logic by using switch statement, it would be much cleaner to read.

      Delete
  14. Can you help me on this program

    import java.util.Scanner;
    public class DemoVariables
    {
    int entry;
    Scanner keyBoards = new Scanner(System.in);
    System.out.print("Enter an integer");
    entry = keyBoard.nextInt();

    public static void main(String[] args)
    {
    System.out.print("The other entry is");
    System.out.println("anotherEntry");
    System.out.println(entry + " plus " +
    anotherEntry + " is " + ( entry + anotherEntry));
    System.out.println(entry + " minus " +
    anotherEntry + " is " + (entry - anotherEntry));
    System.out.println(entry + " times " +
    anotherEntry + " is +(entry * anotherEntry));
    System.out.println(entry + " divided by " +
    anotherEntry + " is " + (entry / anotherEntry));
    System.out.println("The remainder is" +
    (entry % anotherEntry));
    }
    }


    ReplyDelete
  15. Code:
    import java.io.*;
    class SwitchMethod{
    public static void main(String[] ar) throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter a Choice of Your Number From 1 to 4 :");
    int ch = Integer.parseInt(br.readLine());
    SwitchMethod sm= new SwitchMethod();
    switch(ch){
    case 1:
    void add() throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter First Value:");
    int x = Integer.parseInt(br.readLine());
    System.out.print("Enter Second Value:");
    int y = Integer.parseInt(br.readLine());
    int z = x+y;
    System.out.println(" Sum of " +x+ " and " +y+ " is: " +z);
    sm.add();
    }
    break;
    case 2: sm.sub();
    break;
    int sub() throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter First Value:");
    int a = Integer.parseInt(br.readLine());
    System.out.println("Enter Second Value:");
    int b = Integer.parseInt(br.readLine());
    int c = a-b;
    return c;
    int res = sm.sub();
    System.out.println("Sum:"+res);
    }
    case 3: sm.mul(a,b);
    break;
    void mul(int x,int y) throws IOException{
    int z = x*y;
    System.out.println("Multiplying " +x+ "*" +y+ "is:" +z);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter First Value:");
    int a = Integer.parseInt(br.readLine());
    System.out.println("Enter Second Value:");
    int b = Integer.parseInt(br.readLine()); mp.mul(a,b);
    }
    case 4: int div(int x,int y) throws IOException{
    int z = x/y;
    return z;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter First Value:");
    int a = Integer.parseInt(br.readLine());
    System.out.print("Enter Second Value:");
    int b = Integer.parseInt(br.readLine());
    int res = sm.div(a,b);
    System.out.println("Sum: " +res);
    }
    break;

    default: System.out.println("Wrong Choice");
    }
    }
    }

    ReplyDelete
  16. Command Prompt:
    SwitchMethod.java:10: error: illegal start of expression
    void add() throws IOException{
    ^
    SwitchMethod.java:10: error: ';' expected
    void add() throws IOException{
    ^
    SwitchMethod.java:10: error: not a statement
    void add() throws IOException{
    ^
    SwitchMethod.java:10: error: ';' expected
    void add() throws IOException{
    ^
    SwitchMethod.java:23: error: ';' expected
    int sub() throws IOException{
    ^
    SwitchMethod.java:23: error: not a statement
    int sub() throws IOException{
    ^
    SwitchMethod.java:23: error: ';' expected
    int sub() throws IOException{
    ^
    SwitchMethod.java:36: error: illegal start of expression
    void mul(int x,int y) throws IOException{
    ^
    SwitchMethod.java:36: error: ';' expected
    void mul(int x,int y) throws IOException{
    ^
    SwitchMethod.java:36: error: expected
    void mul(int x,int y) throws IOException{
    ^
    SwitchMethod.java:36: error: ';' expected
    void mul(int x,int y) throws IOException{
    ^
    SwitchMethod.java:36: error: not a statement
    void mul(int x,int y) throws IOException{
    ^
    SwitchMethod.java:36: error: ';' expected
    void mul(int x,int y) throws IOException{
    ^
    SwitchMethod.java:45: error: ';' expected
    case 4: int div(int x,int y) throws IOException{
    ^
    SwitchMethod.java:45: error: expected
    case 4: int div(int x,int y) throws IOException{
    ^
    SwitchMethod.java:45: error: ';' expected
    case 4: int div(int x,int y) throws IOException{
    ^
    SwitchMethod.java:45: error: not a statement
    case 4: int div(int x,int y) throws IOException{
    ^
    SwitchMethod.java:45: error: ';' expected
    case 4: int div(int x,int y) throws IOException{
    ^
    18 errors

    ReplyDelete
  17. just copy paste your code into an IDE like Eclipse and it will tell you what is wrong with that instead of giving so many errors.

    ReplyDelete
  18. public class Dog{
    private String breed;
    private int age;
    private boolean isBarking;

    public Dog(String breed, int age){
    this.breed = breed;
    this.age = age;
    }
    void barking(){
    isBarking = true;
    }
    }
    public class DogTest{
    public static void main(String[] args){
    Dog pet1 = new Dog("Poodle", 3);
    System.out.println(pet1.breed);

    //Setter for breed
    class main {
    public void SetBreed(String breed){
    this.breed = breed;
    }

    }
    //Getter for breed
    public String getBreed(){
    return breed;
    }
    public class DogTest{
    public static void main(String[] args){
    Dog pet1 = new Dog ("pitbull", 4);
    System.out.println(pet1.getBreed);
    pet1.setBreed("poodle");
    }
    }
    //Setter for age
    public void SetAge(int age){
    this.age = age;

    }
    //Getter for age
    public int getAge(){
    return age;
    }
    public class DogTest{
    public static void main(String[] args){
    Dog pet1 = new Dog (age, 5);
    System.out.println(pet1.getAge);
    pet1.setAge(age);
    }
    }




    ReplyDelete
  19. I dont understand my edit

    public class Dog{
    private String breed;
    private int age;
    private boolean isBarking;

    public Dog(String breed, int age){
    this.breed = breed;
    this.age = age;
    }
    void barking(){
    isBarking = true;
    }
    }
    public class DogTest{
    public static void main(String[] args){
    Dog pet1 = new Dog("Poodle", 3);
    System.out.println(pet1.breed);

    //Setter for breed
    class main {
    public void SetBreed(String breed){
    this.breed = breed;
    }

    }
    //Getter for breed
    public String getBreed(){
    return breed;
    }
    public class DogTest{
    public static void main(String[] args){
    Dog pet1 = new Dog ("pitbull", 4);
    System.out.println(pet1.getBreed);
    pet1.setBreed("poodle");
    }
    }
    //Setter for age
    public void SetAge(int age){
    this.age = age;

    }
    //Getter for age
    public int getAge(){
    return age;
    }
    public class DogTest{
    public static void main(String[] args){
    Dog pet1 = new Dog (age, 5);
    System.out.println(pet1.getAge);
    pet1.setAge(age);
    }
    }




    ReplyDelete
    Replies
    1. Sorry, didn't get you? what error you are getting with your code? can you paste the error message?

      Delete
    2. What the mistake in my code



      import java.util.Scanner;

      public class TaxIncome {
      public static void main(String[] args) {

      double TaxableIncome;
      double Deductions;
      double TaxAmount;
      String Status;
      double RATE1 = 0.10;
      double RATE2 = 0.20;
      double RATE3 = 0.35;

      Scanner scan = new Scanner (System.in);
      System.out.print("INCOME TAX CALCULATOR: ");

      public double TaxIncome(double IncomeTax, double Deductions, String Status) {
      this.IncomeTax = IncomeTax;
      this.Deductions = Deductions;
      this.Status = status;

      }

      public void setDeductions( double deductions) {
      Deductions a = Dedeuctions;

      }

      public double getTaxableIncome() {
      return TaxableIncome;

      }

      public double CalculateTaxincome() {
      if (Status.equals("single")) {
      //nasted if
      if ( TaxIncome >= 21000 ) {
      Income_tax_amount = Total_income * RATE1;

      } else {
      Income_tax_amount = Total_income * RATE2;
      }
      }

      return TaxAmount;
      }











      }
      }


      Delete
    3. Deductions a = Dedeuctions; >> this one
      should be
      deductions a = Dedeuctions; but better use a different name like currentDeductions etc

      Delete
  20. I'm getting an illegal error in my code can you help
    import java.util.Scanner;
    import java.io.File;
    import java.io.IOException;

    public class FileReader {
    private static Scanner fileScanner;

    /**
    * This method, called beginScanning, is public, static and has one parameter, a String
    * representing the name of the input file.
    *
    * Write a try-catch block in order to first create a File object, and then
    * create a Scanner for the File object. Use the Scanner to read the first
    * line of the file but do nothing with that line, as the header line in
    * the file should not contribute to the statistics.
    *
    * @param fileName A String; from readFile() of the FileIO class.
    */
    public static void beginScanning(String fileName) {
    try{
    fileScanner = new Scanner(new File(fileName));
    fileScanner.nextLine();
    }catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    }

    /**
    * This is a public, static method called hasMoreLines which returns a boolean. This method
    * should return true as long as the FileReader class Scanner object is not
    * null and the Scanner object has additional lines in the input file to read.
    *
    * @return A boolean; to readFile() in class FileIO.
    */
    public static boolean hasMoreLines() {
    return fileScanner != null && fileScanner.hasNextLine();
    }

    return false;


    /**
    * This is a public, static method called getNextLine which returns a String. This String
    * represents one line from the input file.
    *
    * Use the FileReader class Scanner object to read one line and return the
    * result.
    *
    * @return A String; to readFile() in FileIO.
    */
    public static String getNextLine() {
    if(fileScanner != null ) {
    return fileScanner.nextLine();
    }

    return "";

    }
    }

    ReplyDelete
    Replies
    1. Just post this code in any IDE like Eclipse and it will you which line has the error.

      Delete
  21. public class MyClass {
    public static void main(String args[]) {
    for (int i=0;i<100; i++);) {
    System.out.println(i);};
    }
    }

    ReplyDelete
    Replies
    1. What is the problem with this code? looks good to me from naked eyes, are you getting any error?

      Delete
  22. hello may i know what is the mistake? its keep going illegal start of expression in line 3
    public class isTriangle{
    public static void main (String[] args){
    public static boolean isTriangle(int a,int b,int c){
    if (a > 0 && b > 0 && c > 0 && a + b > c && a + c > b && b + c > a){
    return true;
    }else{
    return false;}
    }

    }

    ReplyDelete
    Replies
    1. Hello @Unknown, you need to use parenthesis to write the expression, since && is a logical expression and it expect a boolean argument. Consider putting a + b into (a + b)

      Delete