Illegal start of type java ошибка

here is the relevent code snippet:

public static Rand searchCount (int[] x) 
{
    int a ; 
    int b ; 
    int c ; 
    int d ; 
    int f ; 
    int g ;
    int h ; 
    int i ; 
    int j ;
    Rand countA = new Rand () ;
        for (int l= 0; l<x.length; l++) 
        {
            if (x[l] = 0) 
            a++ ;
            else if (x[l] = 1) 
            b++ ;
        }
    }
    return countA ;

}

(Rand is the name of the class that this method is in)

when compiling it get this error message:

Rand.java:77: illegal start of type
        return countA ;
        ^

what’s going wrong here? what does this error message mean?

My program:

public class m
{
    public static void main (String[] args)
    {
        boolean bool = true;

        while(bool)
        {
            rand_number player_1 = new rand_number();
            System.out.println("Player_1 guessed " + player_1.rand_n);

            rand_number player_2 = new rand_number();
            System.out.println("Player_2 guessed " + player_2.rand_n);

            rand_number player_3 = new rand_number();    
            System.out.println("Player_3 guessed " + player_3.rand_n);

            if(player_1.guessed || player_2.guessed || player_3.guessed)
            {
                System.out.println("We have a winner");   
                bool = false;
            }
        }
    }
}

class rand_number
{
    int rand_n = (int)(Math.random() * 10);

    if(rand_n == 2) 
    {
        boolean guessed = true;
    }
}

I’m getting this error: m.java:31: illegal start of type. The syntax is absolutely right, I have checked it million times. What’s wrong?

asked Sep 6, 2010 at 18:36

good_evening's user avatar

good_eveninggood_evening

21.2k65 gold badges192 silver badges298 bronze badges

0

class rand_number
{
    //...    
    if(rand_n == 2) 
    {
        boolean guessed = true;
    }
}

You can only have field declarations at the class level. An if statement like this needs to be in a method, constructor, or initializer block.

You could eliminate the if statement like this:

boolean guessed = rand_n == 2;

But I question why you have any desire to set this value at creation time at all, as opposed to in response to some user action.

answered Sep 6, 2010 at 18:37

Mark Peters's user avatar

Mark PetersMark Peters

79.9k17 gold badges158 silver badges189 bronze badges

Your syntax is absolutely wrong. rand_number doesn’t contains methods and yet tries to do conditions.


If you want to do random numbers you should try the Random class like this :

Random random = new Random();
int numberToFind = random.nextInt(2);

You should take a look at the Java naming conventions, it helps to have a clean code that any java developer can understand in a second. For example, start your classes names with an uppercase.

answered Sep 6, 2010 at 18:39

Colin Hebert's user avatar

Colin HebertColin Hebert

91.2k15 gold badges158 silver badges151 bronze badges

0

Автор оригинала: Kai Yuan.

1. Обзор

“Незаконное начало выражения”-это распространенная ошибка, с которой мы можем столкнуться во время компиляции.

В этом уроке мы рассмотрим примеры, иллюстрирующие основные причины этой ошибки и способы ее устранения.

2. Отсутствующие Фигурные Скобки

Отсутствие фигурных скобок может привести к ошибке “незаконное начало выражения”. Давайте сначала рассмотрим пример:

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Если мы скомпилируем вышеуказанный класс:

$ javac MissingCurlyBraces.java
MissingCurlyBraces.java:7: error: illegal start of expression
        public int calcSum(int x, int y) {
        ^
MissingCurlyBraces.java:7: error: ';' expected
        public int calcSum(int x, int y) {
   .....

Отсутствие закрывающей фигурной скобки print Sum() является основной причиной проблемы.

Решение проблемы простое — добавление закрывающей фигурной скобки в метод printSum() :

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Прежде чем перейти к следующему разделу, давайте рассмотрим ошибку компилятора.

Компилятор сообщает, что 7-я строка вызывает ошибку “незаконное начало выражения”. На самом деле, мы знаем, что первопричина проблемы находится в 6-й строке. Из этого примера мы узнаем, что иногда ошибки компилятора не указывают на строку с основной причиной , и нам нужно будет исправить синтаксис в предыдущей строке.

3. Модификатор Доступа Внутри Метода

В Java мы можем объявлять локальные переменные только внутри метода или конструктора . Мы не можем использовать модификатор доступа для локальных переменных внутри метода, поскольку их доступность определяется областью действия метода.

Если мы нарушим правило и у нас будут модификаторы доступа внутри метода, возникнет ошибка “незаконное начало выражения”.

Давайте посмотрим на это в действии:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        private int sum = x + y; 
        System.out.println("Calculation Result:" + sum);
    }
}

Если мы попытаемся скомпилировать приведенный выше код, мы увидим ошибку компиляции:

$ javac AccessModifierInMethod.java 
AccessModifierInMethod.java:5: error: illegal start of expression
        private int sum = x + y;
        ^
1 error

Удаление модификатора private access легко решает проблему:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        int sum = x + y;
        System.out.println("Calculation Result:" + sum);
    }
}

4. Вложенные методы

Некоторые языки программирования, такие как Python, поддерживают вложенные методы. Но, Java не поддерживает метод внутри другого метода.

Мы столкнемся с ошибкой компилятора “незаконное начало выражения”, если создадим вложенные методы:

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        public int calcSum ( int x, int y) {
            return x + y;
        }
    }
}

Давайте скомпилируем приведенный выше исходный файл и посмотрим, что сообщает компилятор Java:

$ javac NestedMethod.java
NestedMethod.java:6: error: illegal start of expression
        public int calcSum ( int x, int y) {
        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                          ^
NestedMethod.java:6: error:  expected
        public int calcSum ( int x, int y) {
                                   ^
NestedMethod.java:6: error: not a statement
        public int calcSum ( int x, int y) {
                                        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                                         ^
5 errors

Компилятор Java сообщает о пяти ошибках компиляции. В некоторых случаях одна ошибка может привести к нескольким дальнейшим ошибкам во время компиляции.

Выявление первопричины имеет важное значение для того, чтобы мы могли решить эту проблему. В этом примере первопричиной является первая ошибка “незаконное начало выражения”.

Мы можем быстро решить эту проблему, переместив метод calcSum() из метода print Sum() :

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum ( int x, int y) {
        return x + y;
    }
}

5. символ или строка Без кавычек

Мы знаем, что String литералы должны быть заключены в двойные кавычки, в то время как char значения должны быть заключены в одинарные кавычки.

Если мы забудем заключить их в соответствующие кавычки, компилятор Java будет рассматривать их как имена переменных .

Мы можем увидеть ошибку “не удается найти символ”, если “переменная” не объявлена.

Однако если мы забудем дважды заключить в кавычки Строку , которая не является допустимым именем переменной Java , компилятор Java сообщит об ошибке “незаконное начало выражения” .

Давайте посмотрим на это на примере:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals(+)) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

Мы забыли процитировать строку |//+ внутри вызова метода equals , и + , очевидно, не является допустимым именем переменной Java.

Теперь давайте попробуем его скомпилировать:

$ javac ForgetQuoting.java 
ForgetQuoting.java:5: error: illegal start of expression
        if (operation.equals(+)) {
                              ^
1 error

Решение проблемы простое — обертывание String литералов в двойные кавычки:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals("+")) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

6. Заключение

В этой короткой статье мы рассказали о пяти различных сценариях, которые приведут к ошибке “незаконное начало выражения”.

В большинстве случаев при разработке приложений Java мы будем использовать среду IDE, которая предупреждает нас об обнаружении ошибок. Эти замечательные функции IDE могут значительно защитить нас от этой ошибки.

Тем не менее, мы все еще можем время от времени сталкиваться с этой ошибкой. Поэтому хорошее понимание ошибки поможет нам быстро найти и исправить ошибку.

Being a java developer, you must encounter numberless bugs and errors on daily basis. Whether you are a beginner or experienced software engineers, errors are inevitable but over time you can get experienced enough to be able to correct them efficiently. One such very commonly occurring error is “Illegal start of expression Java error”.

The illegal start of expression java error is a dynamic error which means you would encounter it at compile time with “javac” statement (Java compiler). This error is thrown when the compiler detects any statement that does not abide by the rules or syntax of the Java language. There are numerous scenarios where you can get an illegal start of expression error. Missing a semicolon at the end of The line or an omitting an opening or closing brackets are some of the most common reasons but it can be easily fixed with slight corrections and can save you a lot of time in debugging.

Following are some most common scenarios where you would face an illegal start of expression Java error along with the method to fix them,

new java job roles

1. Use of Access Modifiers with local variables

Variables that are declared inside a method are called local variables. Their functionality is exactly like any other variable but they have very limited scope just within the specific block that is why they cannot be accessed from anywhere else in the code except the method in which they were declared.

Access modifier (public, private, or protected) can be used with a simple variable but it is not allowed to be used with local variables inside the method as its accessibility is defined by its method scope.

See the code snippet below,

1.	public class classA {
2.	    public static void main(String args[])
3.	    {        
4.	       public int localVar = 5;
5.	    }
6.	}

 Here the public access modifier is used with a local variable (localVar).

This is the output you will see on the terminal screen:

$javac classA.java
 
classA.java:4: error: illegal start of expression
       public int localVar = 5;
       ^
1 error

It reports 1 error that simply points at the wrong placement of access modifier. The solution is to either move the declaration of the local variable outside the method (it will not be a local variable after that) or simply donot use an access modifier with local variables.

2. Method Inside of Another Method

Unlike some other programming languages, Java does not allows defining a method inside another method. Attempting to do that would throw the Illegal start of expression error.

Below is the demonstration of the code:

1.	public class classA {
2.	    public static void main(String args[]) {        
3.	       int localVar = 5;
4.	       public void anotherMethod(){ 
5.	          System.out.println("it is a method inside a method.");
6.	       }
7.	    }
8.	}

This would be the output of the code,

 $javac classA.java
 
classA.java:5: error: illegal start of expression
       public void anotherMethod()
       ^
classA.java:5: error: illegal start of expression
       public void anotherMethod()
              ^
classA.java:5: error: ';' expected
       public void anotherMethod()
                                ^
3 errors

It is a restriction in Java so you just have to avoid using a method inside a method to write a successfully running code. The best practice would be to declare another method outside the main method and call it in the main as per your requirements.

3. Class Inside a Method Must Not Have Modifier

Java allows its developers to write a class within a method, this is legal and hence would not raise any error at compilation time. That class will be a local type, similar to local variables and the scope of that inner class will also be restricted just within the method. However, an inner class must not begin with access modifiers, as modifiers are not to be used inside the method.

In the code snippet below, the class “mammals” is defined inside the main method which is inside the class called animals. Using the public access modifier with the “mammals” class will generate an illegal start of expression java error.

1.	public class Animals {
2.	    public static final void main(String args[]){        
3.	      public class mammals { }
4.	    }
5.	}

 The output will be as follows,

$javac Animals.java
 
Animals.java:4: error: illegal start of expression
       public class mammals { }
       ^
1 error

This error can be fixed just by not using the access modifier with the inner class or you can define a class inside a class but outside of a method and instantiating that inner class inside the method.

Below is the corrected version of code as well,

1.	class Animals {
2.	   
3.	   // inside class
4.	   private class Mammals {
5.	      public void print() {
6.	         System.out.println("This is an inner class");
7.	      }
8.	   }
9.	   
10.	   // Accessing the inside class from the method within
11.	   void display_Inner() {
12.	      Mammals inside = new Mammals();
13.	      inside.print();
14.	   }
15.	}
16.	public class My_class {
17.	 
18.	   public static void main(String args[]) {
19.	      // Instantiating the outer class 
20.	      Animals classA = new Animals();
21.	      // Accessing the display_Inner() method.
22.	      classA.display_Inner();
23.	   }
24.	}

 Now you will get the correct output,

$javac Animals.java
 
$java -Xmx128M -Xms16M Animals
 
This is an inner class

4.Nested Methods

Some recent programming languages, like Python, supports nested methods but Java does not allow to make a method inside another method.  You will encounter the illegal start of expression java error if you try to create nested methods.

Below mentioned is a small code that attempts to declare a method called calSum inside the method called outputSum,

1.	public class classA {
2.	    public void outputSum(int num1, int num2) {
3.	        System.out.println("Calculate Result:" + calSum(x, y));
4.	        public int calSum ( int num1, int num2) {
5.	            return num1 + num2;
6.	        }
7.	    }
8.	}

 And here is the output,

$ javac classA.java
NestedMethod.java:6: error: illegal start of expression
        public int calSum ( int num1, int num2) {
        ^
classA.java:6: error: ';' expected
        public int calSum ( int num1, int num2) {
                          ^
classA.java:6: error:  expected
        public int calSum ( int num1, int num2) {
                                   ^
NestedMethod.java:6: error: not a statement
        public int calSum ( int num1, int num2) {
                                           ^
NestedMethod.java:6: error: ';' expected
        public calSum ( int num1, int num2) {
                                         ^
5 errors

The Java compiler has reported five compilation errors. Other 4 unexpected errors are due to the root cause. In this code, the first “illegal start of expression” error is the root cause. It is very much possible that a single error can cause multiple further errors during compile time. Same is the case here. We can easily solve all the errors by just avoiding the nesting of methods. The best practice, in this case, would be to move the calSum() method out of the outputSum() method and just call it in the method to get the results.

See the corrected code below,

1.	public class classA {
2.	    public void outputSum(int num1, int num2) {
3.	        System.out.println("Calculation Result:" + calSum(x, y));
4.	    }
5.	    public int calSum ( int num1, int num2) {
6.	        return x + y;
7.	    }
8.	}

5. Missing out the Curly “{ }“ Braces

Skipping a curly brace in any method can result in an illegal start of expression java error. According to the syntax of Java programming, every block or class definition must start and end with curly braces. If you skip any curly braces, the compiler will not be able to identify the starting or ending point of a block which will result in an error. Developers often make this mistake because there are multiple blocks and methods nested together which results in forgetting closing an opened curly bracket. IDEs usually prove to be helpful in this case by differentiating the brackets by assigning each pair a different colour and even identify if you have forgotten to close a bracket but sometimes it still gets missed and result in an illegal start of expression java error.

In the following code snippet, consider this class called Calculator, a method called calSum perform addition of two numbers and stores the result in the variable total which is then printed on the screen. The code is fine but it is just missing a closing curly bracket for calSum method which will result in multiple errors.

1.	public class Calculator{
2.	  public static void calSum(int x, int y) {
3.	    int total = 0;
4.	    total = x + y;
5.	    System.out.println("Sum = " + total);
6.	 
7.	  public static void main(String args[]){
8.	    int num1 = 3;
9.	    int num2 = 2;
10.	   calcSum(num1,num2);
11.	 }
12.	}

Following errors will be thrown on screen,

$javac Calculator.java
Calculator.java:12: error: illegal start of expression public int calcSum(int x, int y) { ^ 
Calculator.java:12: error: ';' expected 
 
Calculator.java:13: error: reached end of file while parsing
}
 ^
3 error

The root cause all these illegal starts of expression java error is just the missing closing bracket at calSum method.

While writing your code missing a single curly bracket can take up a lot of time in debugging especially if you are a beginner so always lookout for it.

6. String or Character Without Double Quotes “-”

Just like missing a curly bracket, initializing string variables without using double quotes is a common mistake made by many beginner Java developers. They tend to forget the double quotes and later get bombarded with multiple errors at the run time including the illegal start of expression errors.

If you forget to enclose strings in the proper quotes, the Java compiler will consider them as variable names. It may result in a “cannot find symbol” error if the “variable” is not declared but if you miss the double-quotations around a string that is not a valid Java variable name, it will be reported as the illegal start of expression Java error.

The compiler read the String variable as a sequence of characters. The characters can be alphabets, numbers or special characters every symbol key on your keyboard can be a part of a string. The double quotes are used to keep them intact and when you miss a double quote, the compiler can not identify where this series of characters is ending, it considers another quotation anywhere later in the code as closing quotes and all that code in between as a string causing the error.

Consider this code snippet below; the missing quotation marks around the values of the operator within if conditions will generate errors at the run time.

1.	public class Operator{
2.	  public static void main(String args[]){
3.	    int num1 = 10;
4.	    int num2 = 8;
5.	    int output = 0; 
6.	    Scanner scan = new Scanner(System.in);
7.	    System.out.println("Enter the operation to perform(+OR)");
8.	    String operator= scan.nextLine();
9.	    if(operator == +)
10.	  {
11.	     output = num1 + num2;
12.	  }
13.	  else if(operator == -)
14.	  {
15.	     output = num1 - num2;
16.	  }
17.	  else
18.	  {
19.	     System.out.prinln("Invalid Operator");
20.	  }
21.	  System.out.prinln("Result = " + output); 
22.	}

String values must be always enclosed in double quotation marks to avoid the error similar to what this code would return, 

$javac Operator.java
 
Operator.java:14: error: illegal start of expression
if(operator == +)
                ^
Operator.java:19: error: illegal start of expression
   if(operator == -)
                   ^
3 error

Conclusion

In a nutshell, to fix an illegal start of expression error, look for mistakes before the line mentioned in the error message for missing brackets, curly braces or semicolons. Recheck the syntax as well. Always look for the root cause of the error and always recompile every time you fix a bug to check as it could be the root cause of all errors.

See Also: Java Feature Spotlight – Sealed Classes

Such run-time errors are designed to assist developers, if you have the required knowledge of the syntax, the rules and restrictions in java programming and the good programming skills than you can easily minimize the frequency of this error in your code and in case if it occurs you would be able to quickly remove it.

Do you have a knack for fixing codes? Then we might have the perfect job role for you. Our careers portal features openings for senior full-stack Java developers and more.

new Java jobs

1. Overview

The “illegal start of expression” is a common error we may face at the compile-time.

In this tutorial, we’ll see examples that illustrate the main causes of this error and how to fix it.

2. Missing Curly Braces

Missing curly braces may lead to the “illegal start of expression” error. Let’s take a look at an example first:

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        
    public int calcSum(int x, int y) {
        return x + y;
    }
}

If we compile the above class:

$ javac MissingCurlyBraces.java
MissingCurlyBraces.java:7: error: illegal start of expression
        public int calcSum(int x, int y) {
        ^
MissingCurlyBraces.java:7: error: ';' expected
        public int calcSum(int x, int y) {
   .....

Missing the closing curly brace of printSum() is the root cause of the problem.

The fix to the problem is simple — adding the closing curly brace to the printSum() method:

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Before we step forward to the next section, let’s review the compiler error.

The compiler reports that the 7th line is causing the “illegal start of expression” error. In fact, we know that the root cause of the problem is in the 6th line. From this example, we learn that sometimes the compiler errors don’t point to the line with the root cause, and we’ll need to fix the syntax in the previous line.

3. Access Modifier Inside Method

In Java, we can only declare local variables inside a method or constructor. We cannot use any access modifier for local variables inside a method because their accessibilities are defined by the method scope.

If we break the rule and have access modifiers inside a method, the “illegal start of expression” error will be raised.

Let’s see this in action:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        private int sum = x + y; 
        System.out.println("Calculation Result:" + sum);
    }
}

If we try compiling the above code, we’ll see the compilation error:

$ javac AccessModifierInMethod.java 
AccessModifierInMethod.java:5: error: illegal start of expression
        private int sum = x + y;
        ^
1 error

Removing the private access modifier easily solves the problem:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        int sum = x + y;
        System.out.println("Calculation Result:" + sum);
    }
}

4. Nested Methods

Some programming languages, such as Python, support nested methods. But, Java doesn’t support a method inside another method. 

We’ll face the “illegal start of expression” compiler error if we create nested methods:

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        public int calcSum ( int x, int y) {
            return x + y;
        }
    }
}

Let’s compile the above source file and see what the Java compiler reports:

$ javac NestedMethod.java
NestedMethod.java:6: error: illegal start of expression
        public int calcSum ( int x, int y) {
        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                          ^
NestedMethod.java:6: error: <identifier> expected
        public int calcSum ( int x, int y) {
                                   ^
NestedMethod.java:6: error: not a statement
        public int calcSum ( int x, int y) {
                                        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                                         ^
5 errors

The Java compiler reports five compilation errors. In some cases, a single error can cause multiple further errors during compile time.

Identifying the root cause is essential for us to be able to solve the problem. In this example, the first “illegal start of expression” error is the root cause.

We can quickly solve the problem by moving the calcSum() method out of the printSum() method:

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum ( int x, int y) {
        return x + y;
    }
}

5. char or String Without Quotes

We know that String literals should be wrapped in double quotes, while char values should be quoted using single quotes.

If we forget to enclose these in the proper quotes, the Java compiler will treat them as variable names.

We may see “cannot find symbol” error if the “variable” is not declared.

However, if we forget to double-quote a String that is not a valid Java variable name, the Java compiler will report the “illegal start of expression” error.

Let’s have a look at it through an example:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals(+)) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

We forgot to quote the String + inside the call to the equals method, and + is obviously not a valid Java variable name.

Now, let’s try compiling it:

$ javac ForgetQuoting.java 
ForgetQuoting.java:5: error: illegal start of expression
        if (operation.equals(+)) {
                              ^
1 error

The solution to the problem is simple — wrapping String literals in double-quotes:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals("+")) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

6. Conclusion

In this short article, we talked about five different scenarios that will raise the “illegal start of expression” error.

Most of the time, when developing Java applications, we’ll use an IDE that warns us as errors are detected. Those nice IDE features can go a long way towards protecting us from facing this error.

However, we may still encounter the error from time to time. Therefore, a good understanding of the error will help us to quickly locate and fix the error.

Понравилась статья? Поделить с друзьями:
  • Ilife v55 ошибка е06 что делать
  • Ilife v55 pro ошибка е12
  • Ilife v55 pro ошибка е10
  • Ilife v55 pro ошибка e10
  • Ilife v55 pro ошибка e06