What’s the issue here?
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
UserInput input = new UserInput();
input.name();
}
This complains:
<identifier> expected
input.name();
asked May 11, 2012 at 22:52
randombitsrandombits
46.8k75 gold badges251 silver badges432 bronze badges
3
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then «run» the class from your IDE
answered May 11, 2012 at 22:55
You can’t call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
answered May 11, 2012 at 22:54
TudorTudor
61.4k12 gold badges99 silver badges142 bronze badges
input.name() needs to be inside a function; classes contain declarations, not random code.
answered May 11, 2012 at 22:54
geekosaurgeekosaur
58.8k11 gold badges123 silver badges114 bronze badges
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
answered May 11, 2012 at 22:56
I saw this error with code that WAS in a method; However, it was in a try-with-resources block.
The following code is illegal:
try (testResource r = getTestResource();
System.out.println("Hello!");
resource2 = getResource2(r)) { ...
The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about «try-with-resources» here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
answered Sep 22, 2021 at 22:12
class if{
public static void main (String args[]){
int x = 9;
if (x <= 9){
System.out.println("Yay");
}else{
System.out.println("Yay");
}
}
}
I’m running this from the compiler, using Notepad++ as the text editor. And I am getting an error in the compiler saying <identifier> expected class if. And another error saying illegal start of expression.
As well as saying error ";" expected. I have a total of 9 errors.
I made sure to match all the {} and (). Even scraped the program and tried again with the same results.
asked Aug 17, 2011 at 21:36
2
if is a reserved keyword in Java (as seen in your if statement), and is thus not an eligible class name. Choose another name for your class, like IfTesting.
By convention, all class names start with an upper-case letter. The full details for what is and isn’t a valid Java identifier are found in the Java Language Specification. In short, it can’t be a keyword, true, false, or null.
answered Aug 17, 2011 at 21:37
Mark PetersMark Peters
79.9k17 gold badges158 silver badges189 bronze badges
2
You shouldn’t call a class «if». It’s a reserved Java keyword (that you’re using in your program, BTW).
Furthermore, by convention, all classes start with an uppercase letter in Java.
answered Aug 17, 2011 at 21:39
JB NizetJB Nizet
675k91 gold badges1217 silver badges1251 bronze badges
2
You cannot name your class or even a variable with a keyword.
answered Aug 17, 2011 at 21:39
Eng.FouadEng.Fouad
115k70 gold badges312 silver badges416 bronze badges
You can’t name your class if, as it’s a keyword. Check this for more examples.
answered Aug 17, 2011 at 21:39
dckrooneydckrooney
3,0112 gold badges22 silver badges28 bronze badges
Also, it’s (String[] args)
Not (String args[])
answered Jan 14, 2017 at 18:33
1
Introduction to Identifiers
By definition, an identifier in Java is a sequence of one or more characters, where the first character must be a valid first character (letter, $, _) and each subsequent character in the sequence must be a valid non-first character (letter, digit, $, _). An identifier can be used to name a package, a class, an interface, a method, a variable, etc. An identifier may contain letters and digits from the entire Unicode character set, which supports most writing scripts in use in the world today, including the large sets for Chinese, Japanese, and Korean. This allows programmers to use identifiers in programs written in their native languages [1].
Identifier Expected Error: What It Is & What Triggers It
The initial phase of the Java compilation process involves lexical analysis of the source code. The compiler reads the input code as a stream of characters and categorizes them into lexemes of tokens, before proceeding to parse the tokens into a syntax tree. Here is where all tokens, including identifiers, are being checked against a predefined set of grammar rules. When the compiler reaches a point where, according to these rules, an identifier is expected to appear but something else is found instead, it raises the <identifier> expected error, where the angle brackets denote a reference to a token object [2].
The <identifier> expected error is a very common Java compile-time error faced by novice programmers and people starting to learn the language. This error typically occurs when an expression statement (as defined in [3]) is written outside of a constructor, method, or an instance initialization block. Another common scenario for this error is when a method parameter does not have its data type, or similarly, its name declared.
Identifier Expected Error Examples
Misplaced expression statements
When isolated expression statements such as assignments or method invocations appear outside the scope of a constructor, a method, or an instance initialization block, the <identifier> expected error is raised (Fig. 1(a)). Moving the statements in question to an appropriate place resolves this error (Fig. 1(b)).
(a)
package rollbar;
public class IdentifierExpectedExpression {
private String str;
str = "Rollbar";
System.out.println(str);
}
IdentifierExpectedExpression.java:5: error: <identifier> expected
str = "Rollbar";
^
IdentifierExpectedExpression.java:6: error: <identifier> expected
System.out.println(str);
^
IdentifierExpectedExpression.java:6: error: <identifier> expected
System.out.println(str);
^
3 errors
(b)
package rollbar;
public class IdentifierExpectedExpression {
private String str;
public IdentifierExpectedExpression(String str) {
this.str = str;
}
public static void main(String... args) {
var rollbar = new IdentifierExpectedExpression("Rollbar");
System.out.println(rollbar.str);
}
}
RollbarMisplaced declaration statements
One interesting but not so obvious example of where the <identifier> expected error might appear is the try-with-resources statement [4]. This statement requires any closeable resource (such as a BufferedReader instance) to be declared within parentheses immediately after the try keyword, so it can be closed and finalized automatically. Declaring a resource variable outside the try-with-resources statement will raise the <identifier> expected error, as shown in Fig 2.
(a)
package rollbar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IdentifierExpectedDeclaration {
public static void main(String... args) {
StringBuilder result = new StringBuilder();
BufferedReader br = null;
try (br = new BufferedReader(new InputStreamReader(System.in))){
String line = "";
while (!(line = br.readLine()).isBlank()) {
result.append(line);
}
} catch(IOException e){
e.printStackTrace();
}
System.out.println(result);
}
}
IdentifierExpectedDeclaration.java:12: error: <identifier> expected
try (br = new BufferedReader(new InputStreamReader(System.in))) {
^
1 error
(b)
package rollbar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IdentifierExpectedDeclaration {
public static void main(String... args) {
StringBuilder result = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
String line = "";
while (!(line = br.readLine()).isBlank()) {
result.append(line);
}
} catch(IOException e){
e.printStackTrace();
}
System.out.println(result);
}
}Missing method parameter data type or name
A method parameter should consist of a data type, followed by it’s name, which is an identifier. Being a statically typed language with strict grammar rules, Java treats these as crucial pieces of information—omitting either one will inevitably raise the <identifier> expected error.
In the toAbsoluteValue method in Fig. 3(a), the type of the parameter is double, but no identifier follows, only a right parenthesis. Therefore, the <identifier> expected error is raised at the position of the right parenthesis. In Fig. 3(b) the compiler assumes the parameter type to be x, but it sees no identifier next to it, hence halting with the same error.
(a)
package rollbar;
public class IdentifierExpectedMethodParams {
public static double toAbsoluteValue(x) {
return x < 0 ? x * -1 : x;
}
public static void main(String... args) {
System.out.println(toAbsoluteValue(-4.3));
}
}
IdentifierExpectedMethodParams.java:5: error: <identifier> expected
public static double toAbsoluteValue(x) {
^
1 error
(b)
package rollbar;
public class IdentifierExpectedMethodParams {
public static double toAbsoluteValue(double) {
return x < 0 ? x * (-1) : x;
}
public static void main(String... args) {
System.out.println(toAbsoluteValue(-4.3));
}
}
IdentifierExpectedMethodParams.java:5: error: <identifier> expected
public static double toAbsoluteValue(double) {
^
1 error
(c)
package rollbar;
public class IdentifierExpectedMethodParams {
public static double toAbsoluteValue(double x) {
return x < 0 ? x * -1 : x;
}
public static void main(String... args) {
System.out.println(toAbsoluteValue(-4.3));
}
}
4.3Summary
Identifiers are used to name structural units of code in Java. A compile-time error associated with identifiers and common amongst Java newcomers is the <identifier> expected error. When the Java compiler expects to find an identifier but discovers something else in its place, the compilation process fails by triggering the <identifier> expected error. With the aim to learn how to comprehend, resolve, and prevent this error, relevant examples have been presented in this article.
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] Oracle, 2021. The Java® Language Specification. Chapter 3. Lexical Structure. Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.8 . [Accessed Nov. 15, 2021].
[2] A. Reis, Compiler Construction Using Java, JavaCC, and Yacc. Hoboken, New Jersey: John Wiley & Sons, 2012, pp. 355-358.
[3] Oracle, 2021. Expressions, Statements, and Blocks (The Java™ Tutorials > Learning the Java Language > Language Basics). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html. [Accessed Nov. 15, 2021].
[4] Oracle, 2021. The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html . [Accessed Nov. 15, 2021].
Posted by Marta on November 21, 2021
Viewed 97850 times
In this article you will learn how to fix the java error: identifier expected to get a better understanding of this error and being able to avoid in the future.
This error is a very common compilation error that beginners frequently face when learning Java. I will explain what is the meaning of this error and how to fix it.
What’s the meaning of Identifier Expected error?
The identifier expected error is a compilation error, which means the code doesn’t comply with the syntax rules of the Java language. For instance, one of the rules is that there should be a semicolon at the end of every statement. Missing the semicolon will cause a compilation error.
The identifier expected error is also a compilation error that indicates that you wrote a block of code somewhere where java doesn’t expect it.
Here is an example of piece of code that presents this error:
public class Example {
System.out.println("Hello");
}
If you try to compile this class, using the javac command in the terminal, you will see the following error:
Output:
Example.java:5: error: <identifier> expected
System.out.println("Hello");
^
Example.java:5: error: illegal start of type
System.out.println("Hello");
^
This error is slightly confusing because it seems to suggest there is something wrong with line 2. However what it really means is that this code is not in the correct place.
How to Fix it
We have seen what the error actually means, however how could I fix it? The error appears because I added some code in the wrong place, so what’s the correct place to right code? Java expects the code always inside a method. Therefore, all necessary to fix this problem is adding a class method and place the code inside. See this in action below:
public class Example {
public void print() {
System.out.println("Hello");
}
}
The code above will compile without any issue.
Another example
Here is another example that will return the identifier expected error:
public class Example {
public void print() {
System.out.println("Hello");
}
Example e = new Example();
e.print(); // Here is the error
}
Output:
Example.java:10: error: <identifier> expected
e.print();
^
As before, this compilation error means that there is a piece of code: e.print() that is not inside a class method. You might be wondering, why line 7 ( Example e = new Example(); ) is not considered a compilation error? Variable declarations are allowed outside a method, because they will be considered class fields and their scope will be the whole class.
Here is a possible way to fix the code above:
public class Example {
public void print() {
System.out.println("Hello");
}
Example e = new Example();
public void method2(){
e.print();
}
}
The fix is simply placing the code inside a method.
Conclusion
To summarise, this article covers how to fix the identifier expected java error. This compilation error will occur when you write code outside a class method. In java, this is not allow, all code should be placed inside a class method.
In case you want to explore java further, I will recommend the official documentation
Hope you enjoy the tutorial and you learn what to do when you find the identifier expected error. Thanks for reading and supporting this blog.
Happy coding!
More Interesting Articles
How to shuffle a string in java
How to open a web browser in python
Runnable vs Callable – Find out the differences
What is a mutator method in Java?
In this post, we will see how to fix an error: Identifier expected in java.
Table of Contents
- Problem : Identifier expected in Java
- Solution
- Wrap calling code inside main method
- Create instance variable and wrap calling code inside main method
- Create instance variable, initialize in constructor and wrap calling code inside main method
If you are new to Java, you might get the error identifier expected in java. You will generally get this error, when you put code randomly inside a class rather than method.
Let’s first reproduce this issue with the help of simple example.
|
class HelloWorld { public void printHelloWorld() { System.out.println(«This is a Hello World.»); } } public class MyClass { HelloWorld hello = new HelloWorld(); hello.printHelloWorld(); } |
When you will compile above class, you will get below error:
C:UsersArpitDesktop>javac MyClass.java
MyClass.java:9: error: <identifier> expected
hello.printHelloWorld();
^
1 error
C:UsersArpitDesktop>
Solution
We are getting this error because we can’t call method outside a method.
Here hello.printHelloWorld() needs to be inside a method. Let’s fix this issue with the help of multiple solutions.
Wrap calling code inside main method
Put hello.printHelloWorld() inside a main method and run the code.
|
class HelloWorld { public void printHelloWorld() { System.out.println(«This is a Hello World.»); } } public class MyClass { public static void main(String args[]) { HelloWorld hello = new HelloWorld(); hello.printHelloWorld(); } } |
When you will compile above class, you will get below error:
C:UsersArpitDesktop>javac MyClass.java
C:UsersArpitDesktop>java MyClass
This is a Hello World.
As you can see error is resolved now.
Create instance variable and wrap calling code inside main method
This is similar to previous solution, we will just create ‘hello’ as static instance variable.
|
class HelloWorld { public void printHelloWorld() { System.out.println(«This is a Hello World.»); } } public class MyClass { static HelloWorld hello = new HelloWorld(); public static void main(String args[]) { hello.printHelloWorld(); } } |
When you will compile above class, you will get below error:
C:UsersArpitDesktop>javac MyClass.java
C:UsersArpitDesktop>java MyClass
This is a Hello World.
Create instance variable, initialize in constructor and wrap calling code inside main method
In this solution, We will create instance variable, initialize it in constructor and then use instance variable inside main method.
Please note that we have to create MyClass object before using ‘hello’ instance variable.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class HelloWorld { public void printHelloWorld() { System.out.println(«This is a Hello World.»); } } public class MyClass { static HelloWorld hello; MyClass() { hello = new HelloWorld(); } public static void main(String args[]) { MyClass mc = new MyClass(); hello.printHelloWorld(); } } |
When you will compile above class, you will get below error:
C:UsersArpitDesktop>javac MyClass.java
C:UsersArpitDesktop>java MyClass
This is a Hello World.
That’s all about how to fix Error: Identifier expected in java


