Java Error: illegal start of expression
Expressions are essential building blocks of any Java program . One of the most common Java error illegal start of expression , is a compile time error when the compiler encounters an inappropriate statement in the source code. This error can be encountered in various scenarios . In this course, we’ll see examples that elaborate the main causes of this error and how to fix it.
- Missing curly braces
- Method Inside of Another Method
- Access Modifier Inside Method
- Char or String Without Quotes
Missing curly braces
In a Java program, curly braces enclose meaningful units of code. When you open a curly brace it means that you open a new scope (usually it’s a nested scope). One important thing to understand is that a variable that you’ll define inside this scope (which end where you put the closing curly brace) will not be recognized outside of the scope. So, it is important to note that missing curly braces may lead to the illegal start of expression error.
example
output
Missing the closing curly brace of main() method is the root cause of the problem.
In order to fix this problem, adding the closing curly brace to the main() method.
Method Inside of Another Method (Nested Methods)
Java does not support «directly» nested methods . (Most functional languages do though, including some JVM languages such as Scala and Clojure ). Nested methods would not be meaningful in Java, because methods do not have scope: they have a containing class . From the perspective of the Java runtime, this means it doesn’t have to apply scoping rules to resolve method names: it simply looks them up in the inheritance hierarchy of the instance (or class, in the case of static methods) which contains them. So, using a method inside another method would in Java throw the Illegal start of expression error.
example
In the above example, we can see that the method innerMethod() is placed inside another method outerMethod().
output
In java 8 and newer version you can achieve nested methods by lambda expression .
Access Modifier Inside Method

Access modifiers in Java helps to restrict the scope of a class , constructor , variable , method or data member. Since the scope of the local variables belong to the method/block/constructor/ these are not accessed from outside, therefore, having access specifiers like public, private, protected (which allows access outside of the current context) makes no sense. If we break the rule and have access modifiers inside a method, the illegal start of expression error will be raised.
example
output
You can fix this error by removing the private access modifier from «private int sum».
Char or String Without Quotes
In Java, char is a primitive data type whereas String is a class. We define char in java program using single quote (‘) whereas we can define String in Java using double quotes («). If we forget to enclose these in the proper quotes, the Java compiler will treat them as variable names . So, if we forget to add quotes to char or string is not a valid Java variable name, then the Java compiler will report the illegal start of expression error.
Java Error: illegal start of expression
I’m basically refining, completing and trying to compile a test code from a reference book for java beginners. The objective is to create a guessing game wherein the target is located in 3 continuous cells (I’m holding the locations in an array) and the user guesses the cell no. to destroy the target cell by cell.
I checked out half a dozen posts here on the same error, but I couldn’t figure out what was going wrong.
This is my error:
4 Answers 4
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself , you use the Integer array locations .
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
How to Fix “Illegal Start of Expression” in Java

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.
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.
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)).
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)).
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)).
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

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
How to fix illegal start of expression error in java
In this post, we will see how to fix "illegal start of expression" in java.
You will get this error while using javac command in command prompt. In eclipse or any other ide, it will give you more helpful compile time error.
There can be multiple reasons for getting this error.
Using private, public or protected modifiers inside a method
You might know that you can not use private, public or protected modifier inside a method. If you use it, you will get illegal start of expression.
When you run javac Command, you will get below error.
When you use the same code in eclipse ide, you will get below error.
As you can see eclipse ide provides better information regarding this error.
Using method inside a method
You might know that you cannot have method inside another method. If you put it, you will get illegal start of expression.
Actually, it is again due to public static modifiers only
When you run javac Command, you will get below error.
Forgot to add curly braces
If you forgot to add curly braces, you will get again get this error.
but eclipse ide, you will get below error.
That’s all about illegal start of expression. I hope you will be able to solve the issue with the help of this post.
Was this post helpful?
Share this
How to fix class interface or enum expected error in java
Related Posts
Author

Related Posts

[Fixed] Unsupported class file major version 61 in Java
Table of ContentsReason for Unsupported class file major version 61 in JavaSolution for Unsupported class file major version 61 in JavaAndorid studio/Intellij Idea with gradleAny other scenario In this post, we will see how to fix Unsupported class file major version 61 in Java. Reason for Unsupported class file major version 61 in Java You […]

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]

[Fixed] Unable to obtain LocalDateTime from TemporalAccessor
Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]

[Solved] Variable might not have been initialized in Java
Learn about how to solve Variable might not have been initialized in Java.

[Solved] Class names are only accepted if annotation processing is explicitly requested
Learn about how to fix class names are only accepted if annotation processing is explicitly requested in java.