0

my code:

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

when i save it as a .java file, then cd Desktop, then javac it, it makes the class file and puts it on my desktop, and then when I attempted to java it, i get:

Error: Could not find or load main class Main

I've tried to add .class to it, but i still get the same error.

Would it be because of the path? Would it be because of something with my environment variables?

  • 1
    This may help you: https://stackoverflow.com/questions/2864622/how-do-i-run-class-files-on-windows-from-command-line – ControlAltDel Mar 11 '20 at 17:13
  • 1
    If running `java Main` gives you this error, then it means that `Main.class` is not in the same directory location. – Tim Biegeleisen Mar 11 '20 at 17:13
  • @TimBiegeleisen how would I fix it? Would I need to change the path? – javacoder2 Mar 11 '20 at 17:15
  • I think the disconnect might be in the `and puts it on my desktop` step. Are you sure that `Main.class` exists in the location where you are running `javac`? Type `ls` or `dir` to check on this. – Tim Biegeleisen Mar 11 '20 at 17:17
  • If you ran `javac Main.java` followed by `java Main` and got that error, the problem is probably the classpath as detailed in #2 in the duplicate. `java -cp . Main` would confirm that (note spaces around `.`) – that other guy Mar 11 '20 at 17:28

1 Answers1

0

The class containing main method should always be declared as public, otherwise java runtime would not have access to the run the main method which is the starting point for any java application.

Incase of javac, you are just compiling the application to convert your java source code into byte code which doesn't need to know where the main method is.