Java Compiler Error: illegal start of expression
Last modified: December 28, 2019
I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:
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:
If we compile the above class:
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:
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:
If we try compiling the above code, we’ll see the compilation error:
Removing the private access modifier easily solves the problem:
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:
Let’s compile the above source file and see what the Java compiler reports:
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:
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:
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:
The solution to the problem is simple — wrapping String literals in double-quotes:
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.
Синтаксические ошибки в коде
почему когда я пишу данный текст,мне выдаёт ошибки :
Building «Hello»
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:6 : ‘ <' expected
public class HelloClass Canv.addCommand(exit); extends MIDlet implements CommandListener
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:6 : illegal start of type
public class HelloClass Canv.addCommand(exit); extends MIDlet implements CommandListener
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:6 : ‘;’ expected
public class HelloClass Canv.addCommand(exit); extends MIDlet implements CommandListener
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:6 : illegal start of type
public class HelloClass Canv.addCommand(exit); extends MIDlet implements CommandListener
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:6 : ‘;’ expected
public class HelloClass Canv.addCommand(exit); extends MIDlet implements CommandListener
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:1 2: illegal start of expression
public void startApp()
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:1 2: illegal start of expression
public void startApp()
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:1 2: ‘;’ expected
public void startApp()
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 4: illegal start of expression
public void pauseApp()
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 4: illegal start of expression
public void pauseApp()
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 4: ‘;’ expected
public void pauseApp()
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 8: illegal start of expression
public void destroyApp(boolean u)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 8: illegal start of expression
public void destroyApp(boolean u)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 8: ‘;’ expected
public void destroyApp(boolean u)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:2 8: ‘;’ expected
public void destroyApp(boolean u)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 3: illegal start of expression
public void commandAction(Command command, Displayable displayable)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 3: illegal start of expression
public void commandAction(Command command, Displayable displayable)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 3: ‘;’ expected
public void commandAction(Command command, Displayable displayable)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 3: ‘;’ expected
public void commandAction(Command command, Displayable displayable)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 3: not a statement
public void commandAction(Command command, Displayable displayable)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 3: ‘;’ expected
public void commandAction(Command command, Displayable displayable)
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:4 1: reached end of file while parsing
>
Помогите разобратся пожалуйста. Ещё я что то исправлял исправлял,(пытался) , уменя вылезало 2 ошибки :
Building «Hello»
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:1 7: cannot find symbol
symbol : variable exit
location: class HelloClass
Canv.addCommand(exit);
^
C:\Documents and Settings\user\j2mewtk\2.5.2\apps\Hello\src\HelloClass.java:3 6: cannot find symbol
symbol : variable exit
location: class HelloClass
if(command == exit)
^
Добавлено через 1 минуту
P.S. эти два кода я пишу в двух разных файлах если что)
Синтаксические ошибки в коде
как избавиться от этих ероров?
Синтаксические ошибки в коде
с 2059, с2143, с2447. Решил создать игру «змейка» по образцу. Создавал само поле и давай я.
Исправить синтаксические ошибки в коде
Я вот тут код такой набрала: // circ.cpp: главный файл проекта. #include «stdafx.h».
Синтаксические ошибки в коде Java
Я делаю лабораторную, в ней необходимо ввести код функции на языке Java. В тексте лабораторной.
с первой ошибкой, попробуйте добавить в файл HelloClass.java строчку:
private HelloCanvas Canv;
со второй ошибкой, у вас command с маленькой буквы(в if операторе), а в начале вы описывали эту же переменную с большой буквы
private Command exit = new.
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.
Исправить синтаксические ошибки в коде
Всем привет! я не программист. но пытаюсь сам написать макрос к Excel. При запуске выдает ошибку.
Исправить синтаксические ошибки в коде
нужно исправить ошибки(они подчеркнуты красным) см фото #include #include .
Исправить синтаксические ошибки в коде
Подскажите пожалуйста в чем ошибка. Dev C++ Пишет, что в 5 строчке. #include .
Исправить ошибки в коде, возможно, только синтаксические
Помогите исправить двумерный массив string ss; Random b = new random(); Ss = «»; int ar = new.
Перевод illegal start of expression
Townsmen |
| ||
Шустрый Профиль Репутация: нет
public class MD5HashingExample public static void main(String[] args)throws Exception |
кто знает как устранить. заранее благодарен
Это сообщение отредактировал(а) Townsmen — 5.8.2011, 12:00
Krivoy |
| ||
Профиль Репутация: нет | |||
|
Stolzen |
| ||
Эксперт Профиль Репутация: 23 О ужас. А вы массивы не пробовали использовать? И циклы. Это сообщение отредактировал(а) Stolzen — 5.8.2011, 13:15 | |||
|
Townsmen |
| ||
Шустрый Профиль Репутация: нет точно, скобку пропустил в циклы for )) Stolzen, я просто с java начал работать с вчерашнего дня, раньше с as3 работал, там проще мне. не могу создать массив потому что не знаю как, у меня нет учебника или мануала по джаве. посоветуйте какую нибудь хорошую книгу, такую что бы скачать архивом.. | |||
|
Stolzen |
| ||
Эксперт Профиль Репутация: 23 А в action script нет массивов? Это сообщение отредактировал(а) Stolzen — 5.8.2011, 18:02 | |||
|
Townsmen |
| ||||||||||
Шустрый Профиль Репутация: нет в as3 есть массивы но там не так регистрируются переменные
|