Issue
I have just started learning about classes in Java so I am not sure what I am missing here or what I should be doing differently. This is what I am doing:
class Student {
private int roll;
private String name;
public void hW(){
System.out.println("Hello world");
}
}
public class classes {
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
System.out.println("hello");
Student s = new Student();
s.hW();
// TODO code application logic here
}
}
It's giving this error when I run this file:
error: can't find main(String[]) method in class: Student
What changes should I make??
I am using Netbeans IDE 11.3 on macOSX
Solution
Though you haven't mentioned in your question how you were trying to run the file, I was able to reproduce the issue with some hit and trial. Here is what you trying to do and why you faced the issue:
- You have created
classes.java
in your IDE and in this file, you have typed the code which you have posted. - Now, you are going to Mac OS Terminal window and trying to run
java classes.java
probably thinking of Java 11 feature which allows you to run a single-file program without compiling.
Why you faced the problem?
You faced the problem because class Student
is at the top but it does not have public static void main(String[] args)
while this feature of Java requires the top-level class to be executable (i.e. having this main
method)
Check the following paragraph from https://openjdk.java.net/jeps/330
In source-file mode, execution proceeds as follows:
The class to be executed is the first top-level class found in the source file. It must contain a declaration of the standard public static void main(String[]) method.
What is the solution?
Any of the following will work:
- Move the class,
classes
up so that it becomes the first class in your file. Since the class,classes
already haspublic static void main(String[] args)
, your command,java classes.java
will execute it without any problem. - Put the following piece of code inside
class Student
and executejava classes.java
from the Terminal window.
public static void main(String args[]) {
System.out.println("hello");
Student1 s = new Student1();
s.hW();
}
- Execute the following command from the Mac OS Terminal window to run your class in the pre-Java11 way:
javac classes.java
java classes
- Execute the file from your IDE.
On a side note, you should follow Java naming conventions e.g. the class, classes
should be Classes
as per the naming conventions.
Answered By - Arvind Kumar Avinash
Answer Checked By - Cary Denson (JavaFixing Admin)