Java ошибка illegal start of expression

Возникает ошибка при создании:

(9:9)illegal start of expression.

В чем моя ошибка?

Имеется код:

package com.company;
import java.util.Scanner;

 public class Main {

public static void main(String[] args) {
    // write your code here
    Scanner scc = new Scanner(System.in);
    public static void main(String[] args) {
        int firstNum = whatnumber();
        int secodNum = whatnumber();
        char znak = Goperation();
        int resault = resaultX();
        System.out.print(resault);


    }
    public static int whatnumber() {
        System.out.print("Введите число: ");
        int num;
        num = scc.nextInt();
    }
    public static void Goperation() {
        System.out.print("Введите знак: ");
        char znakL;
        znakL = scc.hasNext();
    }
    public static void resaultX(int firstNum, int secondNum, char operation){
        int resault;
        switch (operation) {
            case "+":
                resault = firstNum + secondNum;
                break;
            case "-":
                resault = firstNum - secondNum;
                break;
            case "/":
                resault = firstNum / secondNum;
                break;
            case "*":
                resault = firstNum * secondNum;
                break;
        }
    }
}

Roman C's user avatar

Roman C

8,7184 золотых знака18 серебряных знаков28 бронзовых знаков

задан 28 июн 2018 в 9:32

Шурок Петров's user avatar

5

  1. Как и сказали main внутри main — нельзя писать метод внутри метода
  2. Не понятно вообще это вам нужно(вторая строка с main) — просто удалите
  3. Даже учитывая что вы неправильно написали второй раз main — тут вы еще не закрыли скобку, всегда открывающиеся скобки нужно закрывать.
  4. В методе Goperation()scc.hasNext() — возращает boolean — правда/ не правда, т.е. вы не записываете чар, а проверяете наличие.
    «Существует и метод hasNext(), проверяющий остались ли в потоке ввода какие-то символы.»
    http://kostin.ws/java/java-input-stream.html

    1. Если вы используете char — то нужно указывать '', вместо "" — они используются для String.

ответ дан 28 июн 2018 в 10:12

sank's user avatar

sanksank

3772 серебряных знака21 бронзовый знак

   package My.Package;
import java.util.Scanner;

public class Main {

    Scanner scc = new Scanner(System.in);
    public static void main(String[] args) {
        int firstNum = whatnumber();
        int secodNum = whatnumber();
        String znak = Goperation();
        int resault = resaultX(firstNum,secodNum,znak);
        System.out.print(resault);


    }
    public static int whatnumber() {
        Scanner scc = new Scanner(System.in);
        System.out.print("Введите число: ");
        int num;
        num = scc.nextInt();
        return  num;
    }
    public static String Goperation() {
        Scanner scc = new Scanner(System.in);
        System.out.print("Введите знак: ");
        String znakL;
        znakL = scc.nextLine();
        return  znakL;
    }
    public static int resaultX(int firstNum, int secondNum, String operation){
        int resault;
        switch (operation) {
            case "+":
                resault = firstNum + secondNum;
                break;
            case "-":
                resault = firstNum - secondNum;
                break;
            case "/":
                resault = firstNum / secondNum;
                break;
            case "*":
                resault = firstNum * secondNum;
                break;
            default: resault = 0;
        }
        return resault;
    }
}

ответ дан 28 июн 2018 в 10:20

Dima Morgunov's user avatar

(9:9)illegal start of expression. — говорит что это ошибка компиляции. Структура программы на Java имеет определённый синтаксис. Этот синтаксис определяет правила использования элементов языка в вашей программе.

Java это очень сложный язык. Конечно читать сразу JLS будет сложно, поэтому новичкам рекомендуют начинить с пониманием базовых концепций. Потом уже переходить к кодированию.

Suvitruf - Andrei Apanasik's user avatar

ответ дан 28 июн 2018 в 10:44

Roman C's user avatar

Roman CRoman C

8,7184 золотых знака18 серебряных знаков28 бронзовых знаков

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

Introduction to Java Compile-time Errors

Over the past two and a half decades, Java has consistently been ranked as one of the top 3 most popular programming languages in the world [1], [2]. As a compiled language, any source code written in Java needs to be translated (i.e., compiled) into machine code before it can be executed. Unlike other compiled languages where programs are compiled directly into machine code, the Java compiler converts the source code into intermediate code, or bytecode, which is then translated into machine code for a specific platform by the Java Virtual Machine (JVM). This, in the simplest of terms, is how Java achieves its platform independence (Fig. 1).

One advantage that comes with being a compiled language is the fact that many errors stemming from incorrect language syntax and semantics (such as “illegal start of expression”) can be captured in the compilation process, before a program is run and they inadvertently find their way into production environments. Since they occur at the time of compilation, these errors are commonly referred to as compile-time errors.

The Java compiler can detect syntax and static semantic errors, although it is incapable of recognizing dynamic semantic errors. The latter are logical errors that don’t violate any formal rules and as such cannot be detected at compile-time; they only become visible at runtime and can be captured by well-designed tests.

When it encounters an error it can recognize, the Java compiler generates a message indicating the type of error and the position in the source file where this error occurred. Syntax errors are the easiest to detect and correct.

Java Compilation Process

Figure 1: The Java Compilation Process [3]

Illegal Start of Expression: What is it?

Expressions are one of the main building blocks of any Java application. These are constructs that compute values and control the execution flow of the program. As its name implies, the “illegal start of expression” error refers to an expression that violates some rule at the point where it starts, usually right after another expression ends; the assumption here is that the preceding expression is correct, i.e., free of errors.

The “illegal start of expression” error often arises from an insufficient familiarity with the language or due to basic negligence. The cause for this error can usually be found at the beginning of an expression or, in some cases, the entire expression might be incorrect or misplaced.

Illegal Start of Expression Examples

Access modifiers on local variables

A local variable in Java is any variable declared inside the body of a method or, more generally, inside a block. A local variable’s accessibility is predetermined by the block in which it is declared—the variable can be accessed strictly within the scope of its enclosing block. Therefore, access modifiers have no use here and, if introduced, will raise the “illegal start of expression” error (Fig. 2(a)). Removing the access modifier (as shown on line 5 in Fig. 2(b)) resolves the Java error.

(a)

package rollbar;

public class AccessModifierOnLocalVariable {
    public static void main(String... args) {
        private String localString = "MyString";
        System.out.println(localString);
    }
}
AccessModifierOnLocalVariables.java:5: error: illegal start of expression
        private String localString = "MyString";
        ^

(b)

package rollbar;

public class AccessModifierOnLocalVariable {
    public static void main(String... args) {
        String localString = "MyString";
        System.out.println(localString);
    }
}
Output: MyString
Figure 2: Local variable with an access modifier (a) error and (b) resolution

Nested methods

Unlike some other languages (most notably functional languages), Java does not allow direct nesting of methods, as shown in Fig. 3(a). This violates Java’s scoping rules and object-oriented approach.

There are two main ways of addressing this issue. One is to move the inner method to an appropriate place outside the outer method (Fig. 3(b)). Another one is to replace the inner method with a lambda expression assigned to a functional interface (Fig. 3(c)).

(a)

package rollbar;

public class MethodInsideAnotherMethod {
   public static void main(String... args) {
       static double root(int x) {
           return Math.sqrt(x);
       }
       System.out.println(root(9));
   }
}
MethodInsideAnotherMethod.java:5: error: illegal start of expression
        static double root(int x) {
        ^ 

(b)

package rollbar;

public class MethodInsideAnotherMethod {
   public static void main(String... args) {
       System.out.println(root(9));
   }

   static double root(int x) {
       return Math.sqrt(x);
   }
}
Output: 3.0

(c)

package rollbar;
import java.util.function.Function;

public class MethodInsideAnotherMethod {
   public static void main(String... args) {
       Function<Integer, Double> root = x -> Math.sqrt(x);
       System.out.println(root.apply(9));
   }
}
Output: 3.0
Figure 3: Nested method (a) error and (b)(c) two viable resolutions

Missing braces

According to Java syntax, every block has to start and end with an opening and a closing curly brace, respectively. If a brace is omitted, the compiler won’t be able to identify the start and/or the end of a block, which will result in an illegal start of expression error (Fig. 4(a)). Adding the missing brace fixes the error (Fig. 4(b)).

(a)

package rollbar;

public class MissingCurlyBrace {

   static int fibonacci(int n) {
       if (n <= 1) return n;
       return fibonacci(n - 1) + fibonacci(n - 2);

   public static void main(String... args) {
       System.out.println(fibonacci(10));
   }
}
MissingCurlyBrace.java:10: error: illegal start of expression
    public static void main(String... args) {
    ^

(b)

package rollbar;

public class MissingCurlyBrace {

   static int fibonacci(int n) {
       if (n <= 1) return n;
       return fibonacci(n - 1) + fibonacci(n - 2);
   }

   public static void main(String... args) {
       System.out.println(fibonacci(10));
   }
}
Output: 55
Figure 4: Missing curly brace (a) error and (b) resolution

Array creation

Traditionally, array creation in Java is done in multiple steps, where the array data-type and size are declared upfront and its values initialized afterwards, by accessing its indices. However, Java allows doing all of these operations at once with a succinct, albeit somewhat irregular-looking, syntax (Fig. 5(a)).

While very convenient, this syntactical idiosyncrasy only works as a complete inline expression and will raise the illegal start of expression error if used otherwise (Fig. 5(b)). This syntax cannot be used to initialize values of an array whose size has already been defined, because one of the things it tries to do is exactly that—assign a size to the array.

The only other scenario in which this syntax may be used is to overwrite an existing array with a new one, by prefixing it with the new directive (Fig. 5(c)).

(a)

package rollbar;

import java.util.Arrays;

public class ArrayInitialization {
   public static void main(String[] args) {
       int[] integers = {1, 2, 3, 4, 5};
       System.out.println(Arrays.toString(integers));
   }
}
Output: [1, 2, 3, 4, 5]

(b)

package rollbar;

import java.util.Arrays;

public class ArrayInitialization {
   public static void main(String... args) {
       int[] integers = new int[5];
       integers = {1, 2, 3, 4, 5};
       System.out.println(Arrays.toString(integers));
   }
}
ArrayInitialization.java:8: error: illegal start of expression
        integers = {1, 2, 3, 4, 5};
                   ^

(c)

package rollbar;

import java.util.Arrays;

public class ArrayInitialization {
   public static void main(String... args) {
       int[] integers = {1, 2, 3, 4, 5};
       System.out.println(Arrays.toString(integers));
       integers = new int[]{6, 7, 8, 9};
       System.out.println(Arrays.toString(integers));
   }
}
Output: [1, 2, 3, 4, 5]
        [6, 7, 8, 9]
Figure 5: Array creation (a)(c) valid syntax and (b) invalid syntax examples

Summary

Being a compiled language, Java has an advantage over other languages in its ability to detect and prevent certain errors from slipping through into production. One such error is the “illegal start of expression” error which belongs to the category of syntax errors detected at compile time. Common examples have been presented in this article along with explanations of their cause and ways to resolve them.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] TIOBE Software BV, “TIOBE Index for October 2021: TIOBE Programming Community index,” TIOBE Software BV. [Online]. Available: https://www.tiobe.com/tiobe-index/. [Accessed Oct. 28, 2021].

[2] Statistics & Data, “The Most Popular Programming Languages – 1965/2021,” Statistics and Data. [Online]. Available: https://statisticsanddata.org/data/the-most-popular-programming-languages-1965-2021/. [Accessed Oct. 28, 2021].

[3] C. Saternos, Client-Server Web Apps with JavaScript and Java. Sebastopol, CA: O’Reilly Media, Inc., 2014, Ch. 4, p.59

Have you ever come across the error illegal start of expression in Java and wondered how to solve it? Let’s go through the post and study how we address the Illegal start of expression Java error.

This is a dynamic error, which means that the compiler finds something that doesn’t follow the rules or syntax of Java programming. Beginners mostly face this bug in Java. Since it is dynamic, it is prompted at compile time i.e., with the javac statement.

This error can be encountered in various scenarios. The following are the most common errors. They are explained on how they can be fixed. 

1. Prefixing the Local Variables with Access Modifiers

Variables inside a method or a block are local variables. Local variables have scope within their specific block or method; that is, they cannot be accessed anywhere inside the class except the method in which they are declared. Access modifiers: public, private, and protected are illegal to use inside the method with local variables as its method scope defines their accessibility.

This can be explained with the help of an example:  

Class LocalVar {
public static void main(String args[])
{
int variable_local = 10
}
}
illegal start of expression in Java - Access Modifiers
Using the modifier with the local variable would generate an error

2. Method Inside of Another Method

A method cannot have another method inside its scope. Using a method inside another method would throw the “Illegal start of expression” error. The error would occur irrespective of using an access modifier with the function name. 

Below is the demonstration of the code: 

Class Method
{
public static void main (String args[])
{
public void calculate() { } 
}
}
illegal start of expression in Java - Definition of a method inside
Definition of a method inside and another method is illegal
Class Method
{
public static void main (String args[])
{
void calculate() { } 
}
}
illegal start of expression in Java
The error doesn’t depend on the occurrence of modifier alone

3. Class Inside a Method Must Not Have Modifier

Similarly, a method can contain a class inside its body; this is legal and hence would not give an error at compile time. However, make note classes do not begin with access modifiers, as modifiers cannot be present inside the method.

In the example below, the class Car is defined inside the main method; this method is inside the class Vehicle. Using the public modifier with the class Car would give an error at run time, as modifiers must not be present inside a method.

class Vehicle
{
public static final void main(String args[])
{
public   class Car { }
}
}
illegal start of expression in Java - Declaring a class with a modifier
Declaring a class with a modifier, inside the method is not allowed

4. Missing Curly “{}“ Braces

Skipping the curly braces of any method block can result in having an “illegal start of expression” error. The error will occur because it would be against the syntax or against the rules of Java programming, as every block or class definition must start and end with curly braces. The developer might also need to define another class or method depending on the requirement of the program. Defining another class or method would, in turn, have modifiers as well, which is illegal for the method body.

In the following code, consider the class Addition, the method main adds two numbers and stores them in the variable sum. Later, the result is printed using the method displaySum. An error would be shown on the terminal as the curly brace is missing at the end of the method main.

public class Addition
{
static int sum;
public static void main(String args[])
{
int x = 8;
int y= 2;
sum=0;
sum= x + y;
{
System.out.println("Sum = " + sum);
}
}
illegal start of expression in Java - Missing curly braces
Missing curly braces from the block definition causes errors.

5. String Character Without Double Quotes “” 

Initializing string variables without the double quotes is a common mistake made by many who are new to Java, as they tend to forget the double quotes and later get puzzled when the error pops up at the run time. Variables having String data type must be enclosed within the double quotes to avoid the “illegal start of expression” error in their code.

The String variable is a sequence of characters. The characters might not just be alphabets, they can be numbers as well or special characters like @,$,&,*,_,-,+,?, / etc. Therefore, enclose the string variables within the double quotes to avoid getting an error.

Consider the sample code below; the missing quotes around the values of the variable operator generates an error at the run time.

import java.util.*;
public class Operator
{
public static void main(String args[])
{
int a = 10;
int b = 8;
int result =0; 
Scanner scan = new Scanner(System.in);
System.out.println("Enter the operation to be performed");
String operator= scan.nextLine();
if(operator == +)
{
   result = a+b;
}
  else 
   if(operator == -)
{
    result = a-b;
   }
  else
{
System.out.prinln("Invalid Operator");
}
  System.out.prinln("Result = " + result); 
}
String values must be enclosed in double-quotes to avoid above mentioned error

6. Summary

To sum up, the “Illegal start of expression” error occurs when the Java compiler finds something inappropriate with the source code at the time of execution. To debug this error, try looking at the lines preceding the error message for missing brackets, curly braces, or semicolons and check the syntax.

Useful tip: Remember, in some cases, a single syntax error sometimes can cause multiple “Illegal start of expression” errors. Therefore, evaluating the root cause of the error and always recompiling when you fix the bug that means avoiding making multiple changes without compilation at each step.

7. Download the Source Code

Last updated on Jan. 10th, 2022

Автор оригинала: 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 могут значительно защитить нас от этой ошибки.

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

Like this post? Please share to your friends:
  • Java ошибка 403
  • Java ошибка 2203
  • Java ошибка 1723 при удалении
  • Java ошибка 170
  • Java ошибка 1625