Java - could not find main class

The code below does not compile:

package app1;

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

The following message appears in the terminal:

Error: Could not find or load main class main

The file main.java is saved in the folder app1. I am compiling by terminal in Manjaro.

I do not understand, when I compile in the IDE (be it NetBeans or Eclipse) the code runs, but by the terminal goes wrong. I appreciate your attention.

Author: Henrique Marques, 2017-11-11

2 answers

The error is in this call: java main

You must use the full name of the class which in this case is: app1.main. However, it still won't work. Java will try to enter an app1 package to find the class. However, you are already inside the package. In order for the call to work, you need to add the parent package of app1 in the java classpath. The classpath is a kind of directory list where java will look for the necessary classes to run the code.

So your call should be: java -cp .. app1.main

To make the command easier you can exit the app1 folder and go to its parent folder. This way you can run this command: java app1.main

Just clarifying a few things. Your code gives no compile error. What happens is an execution error. Java can't find the class with main because you're not passing the correct name and aren't even telling you where to find the class.

Say: Name classes in java should start with a capital letter.

 2
Author: Fagner Fonseca, 2017-11-14 02:43:25

You must ensure that the location of your .class file add to your classpath. So if it's in the current folder, add it .to your classpath. Note that the Windows classpath tab is a dot-dot, i.e.;

 0
Author: Ogarov, 2017-11-11 05:05:19