Identifier Expected Error in Java
An identifier expected error is a very common error faced by beginners. In this section, we will discuss what is identifier expected error, the reasons to occur errors, and how to fix the identifier expected error in Java. Before moving to the error first we will understand what are identifiers in Java.
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name, method name, package name, constant name, etc. However, In Java, there are some reserved words that cannot be used as an identifier such as int, const, new, double, enum, etc.
What is an identifier expected error?
It is a very common compilation error that occurs at compile time.
Let's consider the following Java program.
When we try to compile the above program, we get the following error.
The code looks fine but not so. Because the print statement is not a proper place. It should be inside a method/ block. Let's wrap the code inside a method and then compile and run.
Reasons to Occur Error
There may be the following reasons to occur the error:
How to fix/ resolve errors?
Let's compile the above code. We get the <identifier> expected error.
Observe the above code, we get there is an extra curly brace that is the reason to generate an error. The error can be fixed by removing an extra brace at line 6.
The error also occurs when we put semicolon instead of comma while defining values in enum. For example, consider the following code.
Let's run the above code. we get the identifier expected error.
To fix the error, remove semicolons from the enum values.
Sometimes the error may be much larger. Consider the following code.
Let's compile the above code.
We get too many errors because some statements directly write inside the class body. To resolve the error, write entire the block of code inside a method and then compile and run.