Sourav Bhattacharya
Sourav Bhattacharya

Reputation: 1

Could not find or load java main class

I have a very basic program in java,the filename is MainClass1.java

import java.util.Scanner;
class Student{
    String name;
    int roll_number;
    double marks;
    Student(String s,int r,double m)
    {
        this.name=s;
        this.roll_number=r;
        this.marks=m;
    }
}
class MainClass1{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        String name="Sourav";
        int roll_number=25;
        double marks=70.50;
        Student student1=new Student(name,roll_number,marks);
        System.out.println("The student is "+student1.name+" and his roll number is "+student1.roll_number+" and his marks is "+student1.marks);
    }
}

It compiles fine,however when I am trying to run it by

java Mainclass1

it shows an error


Error: Could not find or load main class Mainclass1
Caused by: java.lang.NoClassDefFoundError: MainClass1 (wrong name: Mainclass1)

I know its a very basic issue,but unable to figure out the issue.

Please help anyone

Upvotes: 0

Views: 62

Answers (1)

Kaan
Kaan

Reputation: 5754

When you run a program (that is, when you call java ...) the JVM needs to know where to start running the code. It looks for a public static method named main, which takes an array of String as input, and is defined on whatever class is named in the .java file.

So:

  1. verify that your file is named "MainClass1.java" – the filename and the class name need to match
  2. verify that the class includes the public modifier, so change this:
    class MainClass1 {
    ...
    }
    
    to this:
    public class MainClass1 {
    ...
    }
    

Upvotes: 1

Related Questions