[Fixed] Error: Identifier expected in java

In this post, we will see how to fix an error: Identifier expected in java.

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.

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:

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.

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.

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.

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

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.