Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

[Solved] Error: Identifier expected in Java

In this post, I will be sharing how to fix the Error "identifier expected in Java". This compilation error is mostly faced by Java beginners. This error generally occurs when you place the code inside the class instead of the method. Before moving on to the solution, we will produce the error first.

Read Also: Error: Could not find Java SE Runtime Environment

[Fixed] Error : Identifier expected


Example 1: Producing the error by using an extra curly brace


Consider the following code:

public class HelloWorld {
public static void main(String args[]) {
System.out.println("Alive is Awesome");}

System.out.println("Love Yourself");
}
}


If you compile the above code using the javac command:

javac HelloWorld.java

then you will find the following compilation error:

Output:
/HelloWorld.java:4: error: expected
System.out.println("Love Yourself");
                              ^
/HelloWorld.java:4: error: illegal start of type
System.out.println("Love Yourself");
                               ^
/HelloWorld.java:6: error: class, interface, or enum expected
}
^
3 errors

Explanation


If you observe the code, then you will find there is an extra curly brace, since the code is not properly indented, it is difficult to view. The above error can be fixed by removing the extra curly brace.

Solution



public class HelloWorld {
public static void main(String args[]) {
System.out.println("Alive is Awesome");

System.out.println("Love Yourself");
}
}


Output:
Alive is Awesome
Love Yourself


Example 2: Producing the error by placing code inside the class



public class HelloWorld {
System.out.println("Alive is Awesome");

}


If you compile the above code using the javac command:

javac HelloWorld.java

You will get the following error:

/HelloWorld.java:2: error: expected
System.out.println("Alive is Awesome");
                              ^

/HelloWorld.java:2: error: illegal start of type
System.out.println("Alive is Awesome");
                               ^
2 errors


Explanation


We are getting expected error because we have placed the code inside the class not inside the method. Let's solve this issue by placing the code inside the main method.

Solution


public class HelloWorld {
public static void main(String args[]) {
System.out.println("Alive is Awesome");

}
}

Output:
Alive is Awesome


That's all for today, please mention in the comments in case you are still facing the error: identifier expected in java.


This post first appeared on Java Hungry, please read the originial post: here

Share the post

[Solved] Error: Identifier expected in Java

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×