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
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
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
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.