How to resolve the "class interface or enum expected" error

The class interface or enum expected error is a compile-time error in Java which arises due to curly braces. Typically, this error occurs when there is an additional curly brace at the end of the program.

Let’s try to understand this with an example:

Code

Case 1 (extra bracket)

class Main {
public static void main(String[] args) {
System.out.println("Helloworld");
}
}
} //extra bracket.

Here, the error can be corrected by simply removing the extra bracket,​ or by keeping an eye on the indentation.

class Main {
public static void main(String[] args)
{
System.out.println("Hello world");
}
}

Case 2 (function outside class)

class MyClass {
public static void main(String args[]) {
//Implementation
}
}
public static void printHello() {
System.out.println("Hello");
}

In the above example, we get an error because the method printHello() is outside of the MyClass class. We can fix this by moving the closing curly braces } to the end of the file. In other words, move the printHello() method inside of​ MyClass.

class MyClass {
public static void main(String args[]) {
//Implementation
}
public static void printHello() {
System.out.println("Hello");
}
}
Copyright ©2024 Educative, Inc. All rights reserved