In this post, we will see how to fix an error: Identifier expected in java.
Table of Contents [hide]
Problem : Identifier expected in Java
Let’s first reproduce this issue with the help of simple example.
When you will compile above class, you will get below error:
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.
When you will compile above class, you will get below error:
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.
When you will compile above class, you will get below error:
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.
When you will compile above class, you will get below error:
C:\Users\Arpit\Desktop>java MyClass
This is a Hello World.
That’s all about how to fix Error: Identifier expected in java