How to Fix “class, interface, or enum expected” Error in Java with Examples?
Last Updated :
28 Jan, 2021
In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java:
Case 1: Extra curly Bracket
Java
class Hello {
public static void main(String[] args)
{
System.out.println( "Helloworld" );
}
}
}
|
In this case, the error can be removed by simply removing the extra bracket.
Java
class Hello {
public static void main(String[] args)
{
System.out.println( "Helloworld" );
}
}
|
Case 2: Function outside the class
Java
class Hello {
public static void main(String args[])
{
System.out.println( "HI" );
}
}
public static void func() { System.out.println( "Hello" ); }
|
In the earlier example, we get an error because the method func() is outside the Hello class. It can be removed by moving the closing curly braces “}” to the end of the file. In other words, move the func() method inside of Hello.
Java
class Hello {
public static void main(String args[])
{
System.out.println( "HI" );
}
public static void func()
{
System.out.println( "Hello" );
}
}
|
Case 3: Forgot to declare class at all
There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not.
Case 4: Declaring more than one package in the same file
Java
package A;
class A {
void fun1() { System.out.println( "Hello" ); }
}
package B;
public class B {
public static void main(String[] args)
{
System.out.println( "HI" );
}
}
|
We can not put different packages into the same source file. In the source file, the package statement should be the first line.
Java
package A;
class A {
void fun1() { System.out.println( "Hello" ); }
}
public class B {
public static void main(String[] args)
{
System.out.println( "HI" );
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...