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
47k76 gold badges252 silver badges433 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.6k12 gold badges102 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
59.4k11 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
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);
}
}
Rollbar
Misplaced 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.3
Summary
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].
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
80.2k17 gold badges159 silver badges190 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
679k91 gold badges1225 silver badges1256 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
115k71 gold badges315 silver badges417 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,0413 gold badges22 silver badges28 bronze badges
Also, it’s (String[] args)
Not (String args[])
answered Jan 14, 2017 at 18:33
1
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:\Users\Arpit\Desktop>javac MyClass.java
MyClass.java:9: error: <identifier> expected
hello.printHelloWorld();
^
1 error
C:\Users\Arpit\Desktop>
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:\Users\Arpit\Desktop>javac MyClass.java
C:\Users\Arpit\Desktop>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:\Users\Arpit\Desktop>javac MyClass.java
C:\Users\Arpit\Desktop>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:\Users\Arpit\Desktop>javac MyClass.java
C:\Users\Arpit\Desktop>java MyClass
This is a Hello World.
That’s all about how to fix Error: Identifier expected in java
In this article, we’ll give you some pointers on how to fix the Identifier Expected Warning in Java.
1. Why does it appear?
Identifier Expected is one of many different syntax error messages a Java compiler may produce. It occurs when the compiler reaches a point in your program where, based on the grammar of the Java language, an identifier must appear, but something else is there instead.
2. What does the Identifier Expected Warning in Java mean?
Technically, an “Identifier Expected” error means exactly what it says: at some point in your program, the Java compiler expected to find an identifier, but instead found something else. However, Java compilers and Java developers each view code (especially buggy code) through very different sets of eyes. What a Java compiler might diagnose as “Error A at location x” can look more like “Error B at location y” to a human observer. So, in practice, it’s best not to take “<identifier> expected” errors too literally: treat them as if they mean “an error”, rather than “the error”.
The key to addressing “<identifier> expected” errors successfully is not to read too much into them. Don’t assume the problem is literally a missing identifier at the indicated location, and don’t assume the solution is to insert an identifier at the indicated location. Always look at the bigger picture, and come to your own conclusion about what the “real” problem and its proper solution are. Here are a couple of examples to inspire you.
3.1 Example #1
These two nearly identical pieces of code each have an error at line #5:Demo1WithErrors.java
package com.jcg.identexpected; public class Demo1WithErrors { public static double squareOf(double) { return x * x; } }
code\demos\src\main\java\com\jcg\identexpected\Demo1WithErrors.java:5: error: expected public static double squareOf(double) ^ 1 error
Demo2WithErros.java
package com.jcg.identexpected; public class Demo2WithErrors { public static double squareOf(x){ return x * x; } }
code\demos\src\main\java\com\jcg\identexpected\Demo2WithErrors.java:5: error: expected public static double squareOf(x){ ^ 1 error
The Java compiler diagnosed identical errors in both cases: an <identifier> was expected at the location of the right-paren. You, however, probably see two somewhat different problems:
- In
Demo1WithErrors
, the parameter was supposed to bedouble x
; the typedouble
was specified, but the namex
was omitted; - In
Demo2WithErrors
, the parameter was supposed to bedouble x
; the namex
is present, but the typedouble
was omitted.
But had you been thinking like a Java compiler, you would have seen things this way:
- In
Demo1WithErrors
, the parameter should consist of a <type>, followed by an <identifier>; the <type> isdouble
, but no <identifier> follows, only a right-paren. Thus “<identifier> expected” error at the position of the right-paren! - In
Demo2WithErrors
, the parameter should consist of a <type> followed by an <identifier>; the type isx
, but no <identifier> follows, only a right-paren. Thus, “<identifier> expected” error at the position of the right-paren.
Both sets of assessments are technically correct, just from different points of view.
The fix, in both cases, is to make the parameter declaration read double x
. In the case of Demo1WithErrors
, it’s a simple matter of taking the error message more or less at its word and inserting the missing identifier x
after the existing type double
(in other words, at the position right-paren):Demo1.java
package com.jcg.identexpected; public class Demo1 { public static double squareOf(double x) { return x * x; } }
As for Demo2WithErrors
, the “intuitive” fix is simply to insert the missing type double
before the existing parameter name x
, more or less ignoring the specifics of the “<identifier> expected” error. But another way to think about it is that you are first inserting the missing identifier, x
, at the location of the right-paren, and then correcting the already-present, but incorrect, type x
to double
. Either way, the end result is:Demo2.java
package com.jcg.identexpected; public class Demo2 { public static double squareOf(double x){ return x * x; } }
3.2 Example #2
An “<identifier> expected” error can sometimes be just a minor symptom of a much larger problem. Consider this common newbie mistake:Demo3WithErrors.java
package com.jcg.identexpected; import java.util.Arrays; public class Demo3WithErrors { int[] nums = {9,1,3,10,7,4,6,2,8,5}; int max; max = nums[0]; for (int i = 1; i < nums.length; ++i){ if (nums[i] > max){ max = nums[i]; } } System.out.println("List: " + Arrays.toString(nums)); System.out.println("Largest = " + max); }
This code produces a rather impressive slew of error messages (29 in all!) that starts off with these:
code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:9: error: expected max = nums[0]; ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: illegal start of type for (int i = 1; i < nums.length; ++i){ ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: ')' expected for (int i = 1; i < nums.length; ++i){ ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: illegal start of type for (int i = 1; i < nums.length; ++i){ ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: expected for (int i = 1; i < nums.length; ++i){ ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: ';' expected for (int i = 1; i < nums.length; ++i){ ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: > expected for (int i = 1; i < nums.length; ++i){ ^ code\demos\src\main\java\com\jcg\identexpected\Demo3WithErrors.java:10: error: '(' expected for (int i = 1; i < nums.length; ++i){
Clearly there’s something more going on here than a simple missing identifier. The Java compiler seems unable to recognize perfectly normal Java statements!
The problem here is that these statements have been dropped right into the top level of the Demo3WithErrors
class body, where only class member declarations belong. The compiler doesn’t recognize statements at this point in the code, simply because it isn’t expecting any statements. Instead, it tries to parse the statements as class member declarations, with varying degrees of success.
The solution, of course, is to put those statements where they belong, in an appropriate context. Here it makes sense to move them into a new main
method:Demo3.java
package com.jcg.identexpected; import java.util.Arrays; public class Demo3 { public static void main(String[] args) { int[] nums = {9, 1, 3, 10, 7, 4, 6, 2, 8, 5}; int max; max = nums[0]; for (int i = 1; i < nums.length; ++i) { if (nums[i] > max) { max = nums[i]; } } System.out.println("List: " + Arrays.toString(nums)); System.out.println("Largest = " + max); } }
4. Summary
That was an article on how to fix the Identifier Expected warning in Java.
- The «Identifier Expected» message is caused by a syntax error in your code;
- The «real» error might, or might not, actually be the result of a missing identifier, and inserting the supposed missing identifier might, or might not, fix it;
- Look at the bigger picture and use your own best judgment.
5. Download the Source Code
Use the link below to download a Maven project containing all the example code from this article.