In this post, we will see how to fix an error: Identifier expected in java.
Table of Contents
Problem : Identifier expected in Java
Let’s first reproduce this issue with the help of simple example.
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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>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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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>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>java MyClass
This is a Hello World.
That’s all about how to fix Error: Identifier expected in java