How to fix "class, interface, or enum expected" error in Java? Example

If you have ever written Java programs using Notepad or inside DOS editor, then you know that how a single missing curly brace can blow your program and throw 100s of "illegal start of expression" errors during compilation of Java Programmer. I was one of those lucky people who started their programming on DOS editor, the blue window editor which allows you to write Java programs. I didn't know about PATH, CLASSPATH, JDK, JVM, or JRE at that point. It's our lab computer where everything is supposed to work as much as our instructor wants. 

Since we don't have the internet at that point in time, we either wait for the instructor to come and rescue us and we were surprised by how he solve the error by just putting one curly brace and all errors mysteriously go away.  

Today, I am going to tell you about one such error,  "class, interface, or enum expected". This is another compile-time error in Java that arises due to curly braces. Typically this error occurs when there is an additional curly brace at the end of the program.

Since everything is coded inside a class, interface, or enum in Java, once you close the curly brace for an existing class and add another closing curly braces, the compiler will expect another class is starting hence it will complain about class, interface, or enum keyword as shown in the following program:

public class Main {

public static void main(String[] args) {
   System.out.println("Helloworld");
  }
 }
}



If you compile this program using javac, you will get the following error:

$ javac Main.java
Main.java:14: class, interface, or enum expected
}
^
1 error

Since this is a small program, you can easily spot the additional curly brace at the end of the problem but it's very difficult in a big program with several classes and methods. 

How to fix "class, interface, or enum expected" error in Java? Example


This becomes even tougher if you are not using any IDE like Eclipse or NetBeans which will give you a visible sign of where an error is. If you know how to use Eclipse or any other Java IDE, just copy-paste your code into IDE and it will tell you the exact location of the error which hint to solve.

Alternatively, if you are coding in Notepad, I assume you are a beginner, then try to correctly indent your code. n our example program above, notice that the two curly braces at the end of the program are at the same indentation level, which cannot happen in a valid program. Therefore, simply delete one of the curly braces for the code to compile, the error will go away as shown below:
$ javac Main.java
So, next time you get the "class, interface, or enum expected" error, just check if you additional curly braces a the end of your program.

Other Java error troubleshooting experiences:
  • How to fix "variable might not have been initialized" error in Java? (solution)
  • Could not create the Java virtual machine Invalid maximum heap size: -Xmx (solution)
  • Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg' (solution)
  • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory (solution)
  • Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java (solution)
  • java.lang.OutOfMemoryError: Java heap space : Cause and Solution (steps)


48 comments:

  1. Tq soo much.your explained very clearly. And I am understand very well

    ReplyDelete
  2. Tq soo much.its helped me a lot.and ur explanation is too good

    ReplyDelete
  3. for me the error was missing "class" in the class declaration ;)

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

    ReplyDelete
    Replies
    1. Yes, because you have missed "class" keyword on public Main, it should be public class Main.

      Delete
    2. in the place of public Main put class Main

      Delete
  4. //iam getting an error:class ,interface or enum expected.please solve it

    class Demo
    {
    int a;
    double b;
    char c;
    boolean d;
    void show()
    {
    System.out.println(obj.a);
    System.out.println(obj.b);
    System.out.println(obj.c);
    System.out.println(obj.d);
    }
    }
    Class Test 13
    {
    public static void main(String[] args)
    {
    Demo obj=new Demo();
    obj.show();
    }
    }

    ReplyDelete
    Replies
    1. beside other possible errors, you should change capital C to small c in your main class and no space between Test and 13: class Test13

      Delete
    2. Yes, that's correct. Also, paste the exact error as it also has line number and more information to help you better. Thanks Maryam for helping fellow learners.

      Delete

  5. public class ConditionalOrOperator {
    public static void main (String[] args) {
    }

    int age = 31;
    int money = 50;
    }
    if(age > 18 || money > 500)
    System.out.println("Welcome!");





    I am getting error of error: class, interface, or enum expected
    can you help me out ?

    ReplyDelete
    Replies
    1. the code should be inside your main method but that is empty, try this

      public class ConditionalOrOperator {
      public static void main (String[] args) {
      int age = 31;
      int money = 50;
      if(age > 18 || money > 500)
      System.out.println("Welcome!");
      }
      }

      Delete
    2. The public type ConditionalOrOperator must be defined in its own file

      Delete

  6. import java.util.Scanner;
    import java.lang.String;


    //A==1;B==2;C==3
    //if the product (mod 47) of the two vals match then return "go" else "stay"
    public class myclass
    {
    public static double Product (String line1 )
    {
    String x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int [] Array= new int [line1.length()];
    int counter=0;

    for(int i=0;i<line1.length();i++)
    {
    for(int j=0;j<26;j++)
    {
    if(x.charAt(j)==line1.charAt(i))
    {
    Array[counter]=j;
    counter++;
    }
    }
    }
    double product;
    double constant=Array[0]*Array[1];
    for (int i=2;i<line1.length();i++)
    {
    product = constant *Array[i];
    constant = product;
    }
    return constant;

    }
    public static string Output (String line1, String line2)
    {
    double x= Product(line1);
    double y= Product(line2);
    if(x%47==y%47)
    {
    return "GO";
    } else
    {
    return "STAY";
    }
    }

    }

    public static void main(String [] args )
    {
    String x;
    String y;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a word (all caps)");
    x= scan.nextLine();
    System.out.println("Enter another word (all caps)");
    y=scan.nextLine();

    System.out.println("Output : " + Output(x,y) );

    }


    }
    pls identify errors

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Just past it in an IDE, it will tell you all the errors. You can even correct them live.

      Delete
    2. A quick check to your program shows a lot of error
      1. remove "} from first line, not needed
      2. space between method name is not allowed like one Parameter, add "_" if you want names like that or just use camel case oneParameter

      Delete
    3. here is the correct one
      public class ShapeAreas {
      {
      }public double oneParameter(String shape, float p1)
      {
      float area;
      if (shape.equals("C"))
      return 5 * 5 * Math.PI;
      else if (shape.equals("S"))
      return 5 * 5;
      else
      return -1.0;
      }

      public double twoParameter(String shape, float p1, float p2)
      {
      float area;
      if (shape.equals("R"))
      return p1 * p2;
      else if (shape.equals("T"))
      return 0.5 * p1 * p2;
      else
      return -1.0;
      }
      }

      Delete
    4. This comment has been removed by the author.

      Delete
    5. you can write unit test using JUnit. Use @Test annotation on method and write code inside that.

      Delete
  8. package com.company;
    Class Product{
    //Attributes
    int pid;
    String name;
    int price;
    //Constructors
    Product(){
    System.out.println(">>Product Object Constructed");
    }
    //Methods
    void setProductDetails(int pid, String name, int price){
    this.pid = pid;
    this.String = name;
    this.price = price;

    }
    //read data from Product Object we have in method
    void showProductDetails(){
    System.out.println("------Product ID"+pid+"-----");
    System.out.println("Name"+name);
    System.out.println("Price"+price);
    System.out.println("------------------");
    }

    public class Main {

    public static void main(String[] args) {
    //create new object : Product
    Product product = new Product();
    // Product is not an object is a reference variable that holds the hashcode of yhe object in hexadecimal notation
    System.out.println("product is:"+product);
    }
    // write your code here
    }
    }

    ReplyDelete
    Replies
    1. I'm getting the same kind of error.
      Thank you!

      Delete
  9. I'm getting class ,interface,enum expected in public static void main command .please clear it

    import javax.swing.*;
    import java.awt.event.*;
    public static void main(String args[])
    {
    public class test
    {
    String[]items={"banana","potato","nithin","shyam"};
    JCombobox c= newJComboBox(items);
    JButton b1= new Jbutton("print");
    JLabel l= new JLabel("display");
    test t=new test();

    public test()
    {
    frame();
    }
    public void frame()
    {
    JFrame f= new Jframe("mywd");
    f.setVisible(true);
    f.setSize(600,400);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel p= new JPanel("panel");

    b1.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {

    }
    });

    p.add(c);
    p.add(l);
    p.add(b1);
    p.add(b1);
    f.add(p);
    }
    }



    ReplyDelete
  10. package MonopolyProject;

    import javax.naming.Name;

    public class Monopoly
    {
    // declare properties
    private String name;
    private String token;
    private int location;
    private int balance;

    public Monopoly() //default constructor
    {
    Monopoly(String name, String token, int location, int balance)
    {
    this.balance = balance;
    this.name = name;
    this.location = location;
    this.token = token;
    }
    public String getName()
    {
    return name;
    }
    public String getToken()
    {
    return token;
    }
    public int getLocation()
    {
    return location;
    }
    public int getBakance()
    {
    return balance;
    }
    public void setName(String name)
    {
    this.name = name;
    }
    public void setToken(String token)
    {
    this.token = token;
    }
    public void setLocation(int location)
    {
    this.location = location;
    }
    public void setBalance(int balance)
    {
    this.balance = balance;
    }
    //to string method
    public String toString()
    {
    String s = "";
    s = s + token + "is on ";

    if(location ==0)
    {
    s = s + "GO";
    }
    else
    {
    s = s + "" + location;
    }
    s = s + "." + name + "\'s BAlance is $" + balance;
    return s;
    }
    }

    ReplyDelete
  11. In life cycle applet program there is no additional curly brace but I'm getting class interface or Enum expected what should I do
    Please reply

    ReplyDelete
  12. public class Main {
    public static void main(String[] args) {
    Main test = new Main();
    test.xyBalanced("abcdefxy"); {
    }
    }

    public boolean xyBalanced(String str) {
    boolean y = true;
    for(int i = 0; i < str.length(); i++) {
    if(Character.toString(str.charAt(i)).equals("x") && y) {
    y = false;
    }
    else if(Character.toString(str.charAt(i)).equals("y") && !y) {
    y = true;
    }
    }
    return y;
    }


    }
    public static void main(String[] args) {
    Main test = new Main();
    test.xyBalanced("abcdefxy"); {
    }
    }


    I am getting an error like enum,class,inference expected

    ReplyDelete
  13. package com.abcd ;
    public class A
    {
    public void method1()
    {
    method2();
    }
    private void method2()
    {
    System.out.println("Hello");
    }
    }
    package com.abc ;
    import com.abcd.A ;
    public class Abc
    {
    public static void main(String args[])
    {
    A obj = new A();
    obj.method1();
    }
    }


    I am getting the error as following:-
    package\Abc.java:13: error: class, interface, or enum expected
    package com.abc ;
    ^
    package\Abc.java:14: error: class, interface, or enum expected
    import com.abcd.A ;
    ^
    2 errors

    ReplyDelete
    Replies
    1. package can only be at the top most line, you need to split your code into two file. put the package com.abc into another file with name Abc.java

      Delete
  14. package p1;
    class A {
    public static void main(String[] args){
    System.out.println("Hi");
    }
    }
    package p2;
    import p1.* ;
    class B {
    public static void main(String[] args){
    A.m1();
    }
    }
    And I get error as enum, interface and class expected how to solve

    ReplyDelete
    Replies
    1. you cannot have package twice in one file, you need to separate your code into differnet files, A.java and B.java

      Delete
  15. package p1;
    class A {
    public static void main(String[] args){
    System.out.println("Hi");
    }
    }
    package p2;
    import p1.* ;
    class B {
    public static void main(String[] args){
    A.m1();
    }
    }

    ReplyDelete
    Replies
    1. I have replied you above, I guess same problem.

      Delete
  16. Getting this error:

    LandTract.java:38: error: class, interface, or enum expected
    import java.util.Scanner;
    ^
    1 error

    Code Below:

    // LandTractDemo.java
    public class LandTractDemo {

    // an int containing the tract's length
    //width - an int containing the tract's width.
    private int length, width;

    // constructor to create a land tract
    public LandTractDemo(int length, int width) {
    this.length = length;
    this.width = width;
    }

    // returns an int representing the tract's area
    public int Area() {
    return length * width;
    }

    // takes another LandTract object as a parameter and returns a boolean saying whether or not the two tracts have the same dimensions
    public boolean equals(LandTractDemo landtct) {

    if (this.length == landtct.length && this.width == landtct.width) {
    return true;
    } else
    return false;
    }

    // Overridden to string method to return the area, length and width of a land tract.
    @Override
    public String toString() {

    return "landtract object with Length: " + length + " and Width: " + width + "\nArea: " + Double.toString(Area()) + "\n";

    }
    }


    import java.util.Scanner;

    public class LandTract
    {

    public static void main(String[] args)
    {

    int length, width;
    Scanner scan = new Scanner(System.in);

    System.out.println("What is the first land tracts length? ");
    length = scan.nextInt();
    System.out.println("What is the first land tracts width? ");
    width = scan.nextInt();
    LandTract lt1 = new LandTract(length, width);

    System.out.println("What is the second land tracts length? ");
    length = scan.nextInt();
    System.out.println("What is the second land tracts width? ");
    width = scan.nextInt();
    // Second land tract.
    LandTract lt2 = new LandTract(length, width);

    System.out.println(lt1.toString());
    System.out.println(lt2.toString());
    // Calls the equals method and return a value based on the comparison.
    if (lt1.equals(lt2) == false)
    {
    System.out.println("The two tracts do not have the same size");
    } else
    {
    System.out.println("The two tracts have the same size\n");
    }
    }
    }

    ReplyDelete
    Replies
    1. It seems you have two import statement in the code and two public class in one file. You have two option to solve this problem
      1. Remove the second import and make the second class non public, just remove the public keyword from second class.

      2. Separate the code into two files for each class.

      Delete
  17. package account;



    public class Assignment5 {

    SavingsAccount savings = new SavingsAccount();
    CheckingAccount checking = new CheckingAccount();
    Account account;

    public static void main (String[] args) {
    Account account = new Account(1122, 20000);

    }
    public static void Print (double x) {
    System.out.printf("The current balance is "+" $ "+"%4.2f"+"%n",x);
    }
    }



    class Account {
    private int id;
    double balance;
    private static double annualInterestRate;
    private java.util.Date dateCreated;

    public Account() {
    dateCreated = new java.util.Date();
    }

    public Account(int newId, double newBalance) {
    id = newId;
    balance = newBalance;
    dateCreated = new java.util.Date();
    }

    public int getId() {
    return this.id;
    }

    public double getBalance() {
    return balance;
    }

    public static double getAnnualInterestRate() {
    return annualInterestRate;
    }

    public void setId(int newId) {
    id = newId;
    }

    public void setBalance(double newBalance) {
    balance = newBalance;
    }

    public static void setAnnualInterestRate(double newAnnualInterestRate) {
    annualInterestRate = newAnnualInterestRate;
    }

    public double getMonthlyInterest() {
    return balance * (annualInterestRate / 1200);
    }

    public java.util.Date getDateCreated() {
    return dateCreated;
    }

    public void withdraw(double amount) {
    balance -= amount;
    }

    public void deposit(double amount) {
    balance += amount;
    }
    }

    package account;
    public class CheckingAccount extends Account {


    double overDraft = -1000;

    public void checking(double i) {

    //initializes double variable balance as 0.0
    double balance = 0.0;
    if (balance - i < overDraft){
    System.out.println("Failure: Can't overdraft more than $1,000. A $25 +"
    + "overdraft fee will be issued to your account. ");
    balance = balance - 25; }
    else
    balance = balance - i;
    }
    }
    package account;
    public class SavingsAccount extends Account{
    double overdraftLimit = 0;

    public void withdraw (double w) {
    if (balance - w < overdraftLimit)
    System.out.println("Insufficient Funds");
    else
    balance = balance - w;
    }
    }


    Please find error im getting clas intergace enum expected

    ReplyDelete
  18. compiler.java:26: error: class, interface, or enum expected
    import java.util.Scanner;
    ^
    1 error

    From this code:

    import java.util.Scanner;

    public class test{

    public static void main(String args[]){

    Scanner myObj = new Scanner ( System.in);
    System.out.println("Who are you?");
    String tyty = myObj.nextLine();
    System.out.println ("Hello" + tyty);
    String toto = myObj.nextLine ();
    System.out.println ("Please enter a number");
    System.out.println ("okay," + toto);


    System.out.print("Enter an integer number: ");
    num=sc.nextInt();

    System.out.println("Square of "+ num + " is: "+ Math.pow(num, 4));

    }
    }




    import java.util.Scanner;

    public class test{

    public static void main(String [] args)
    {
    Scanner sc = new Scanner(System.in);
    System.out.print("Please enter a number: 4 ");
    int num = sc.nextInt();
    System.out.println("Your squared number is: " + square(num));
    }
    public static int square(int num)
    {
    return num * num;




    }
    }

    ReplyDelete
    Replies
    1. If all these code is in same file then you don't need to import twice, delete the second import and it will work. Also import can only be at the top of file. also there can't be two public class in one file, remove public from other class and change its name

      Delete
  19. package com.example.android.miwok;

    public class Word
    {
    private String mDefaultTranslation;
    private String mMiwokTranslation;

    }
    public Word(String defaultTranslation, String miwokTranslation)
    {
    mDefaultTranslation = defaultTranslation;
    mMiwokTranslation = miwokTranslation;
    }
    public String getDefaultTranslation()
    {
    return mDefaultTranslation;
    }
    public String getMiwokTranslation()
    {
    return mMiwokTranslation;
    }


    it gives me error in public Word

    ReplyDelete
  20. TestQueue.java

    public class TestQueue {
    public static void main(String[] args) {
    CustomQueue data = new CustomQueue();
    for (int i = 1; i < 21; i++)
    data.add(i);
    System.out.println(data);
    System.out.println("is Full: "+data.isFull());
    data.remove();
    data.remove();
    System.out.println(data);
    }
    }
    //CustomQueue.java

    public class CustomQueue {
    //variable which stores the capacity of queue
    private int capacity=20;
    //variable for current index
    private static int current=0;
    //which stores data
    private int data[]=new int[capacity];
    //add element at end
    public boolean add(int a) {
    if(current1) {
    for(int i=1;i=0&&index<current)
    return data[index];
    return -1;
    }
    }

    In this code it gives this error.

    Main.java:9: error: class, interface, or enum expected
    TestQueue.java
    ^
    1 error

    Please tell me how to fix?

    ReplyDelete
    Replies
    1. you cannot have two public class in same java file, either remove the public keyword from "public class CustomQueue" or put that class into a separate file with name CustomeQueue.java This should fix your problem

      Delete
  21. I keep getting error: class, interface, or enum expected on every import package i put in between the classes. How would i possibly fix?

    ReplyDelete
    Replies
    1. may be a wrong keyword at wrong place, can you post your code?

      Delete
  22. class, interface, or enum expected
    public static Void main(String[] args)
    ^
    i find this error in

    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Scanner;
    import static javafx.application.Platform.exit;

    /**
    *
    * @author asus
    */

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args)
    {
    // TODO code application logic here
    }



    ReplyDelete
  23. class Calculate
    {
    int service;
    }
    int price(int x, int y, int z)//overloading
    {
    return (x + y + z);
    }
    int price(int x, int y)//overloading
    {
    return (x + y );
    }
    }

    C:\Users\User\Documents\Calculate.java:12: error: class, interface, or enum expected
    int price(int x, int y, int z)//overloading
    ^
    C:\Users\User\Documents\Calculate.java:15: error: class, interface, or enum expected
    }
    ^
    C:\Users\User\Documents\Calculate.java:19: error: class, interface, or enum expected
    }
    ^
    3 errors

    can i know where to fix it?

    ReplyDelete
  24. package mypack;
    public class box
    {
    public int l=10,b=20;
    public void display()
    {
    System.out.println(l);
    System.out.println(b);
    }
    }
    import mypack.box;
    class packagedemo
    {
    public static void main(String args[])
    {
    box b1=new box();
    b1.display();
    }
    }

    ReplyDelete
  25. import java.io.*;
    import java.util.Scanner;
    class Geeks {
    static void isDivisibleByPrime (int n)
    {
    int a = 2;
    int b = 3;
    int c = 11;

    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();

    if (N % 2 == 0){
    System.out.println("Two");
    }else if (N % 3 == 0){
    System.out.println("Three");
    }else if ( N % 11 == 0){
    System.out.println("Eleven");
    }else {
    System.out.println("-1");
    }

    System.out.println();
    }

    kindly look into my problem pls

    ReplyDelete
  26. public class Main {
    private Map locations = new HashMap();
    private Map vocabulary = new HashMap();

    public Main() {
    locations.put(0, new Location(0, "You are sitting in front of a computer learning Java"));
    locations.put(1, new Location(1, "You are standing at the end of a road before a small brick building"));
    locations.put(2, new Location(2, "You are at the top of a hill"));
    locations.put(3, new Location(3, "You are inside a building, a well house for a small spring"));
    locations.put(4, new Location(4, "You are in a valley beside a stream"));
    locations.put(5, new Location(5, "You are in the forest"));

    locations.get(1).addExit("W", 2);
    locations.get(1).addExit("E", 3);
    locations.get(1).addExit("S", 4);
    locations.get(1).addExit("N", 5);

    locations.get(2).addExit("N", 5);

    locations.get(3).addExit("W", 1);

    locations.get(4).addExit("N", 1);
    locations.get(4).addExit("W", 2);

    locations.get(5).addExit("S", 1);
    locations.get(5).addExit("W", 2);
    }


    public void command() {

    Scanner scanner = new Scanner(System.in);

    vocabulary.put("QUIT", "Q");
    vocabulary.put("NORTH", "N");
    vocabulary.put("SOUTH", "S");
    vocabulary.put("EAST", "E");
    vocabulary.put("WEST", "W");
    int loc = 1;
    while (true) {
    System.out.println(locations.get(loc).getDescription());
    if (loc == 0) {
    break;
    }

    Map exits = locations.get(loc).getExits();
    System.out.print("Available exits are ");
    for (String exit : exits.keySet()) {
    System.out.print(exit + ", ");
    }
    System.out.println();

    String[] words = scanner.nextLine().toUpperCase().split(" ");
    String direction = "";
    for (String word : words) {
    if (vocabulary.containsKey(word)) {
    direction = vocabulary.get(word);
    break;
    }
    }
    if (exits.containsKey(direction)) {
    loc = exits.get(direction);
    } else {
    System.out.println("You cannot go in that direction");
    }
    }
    }

    }

    help me solve this error. the error message
    error: class, interface, or enum expected

    ReplyDelete
  27. I thin know have extra braces, try deleting the brace a the end, also you can easily paste this code to any online code Editor and it will point out the line where the error comes

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.