Java class runs fine in IntelliJ but not from command line
I've compiled and run a simple Java file in IntelliJ. It contains a main method and one other small static method. It works perfectly every time.
However, whenever I try to run the java command on the .class file from the terminal I get this:
Error: Could not find or load main class [file name here]
What am I doing wrong?
1 Answer
You have to run java YourClassName, not java YourClassName.class.
The problem is that you are including the .class suffix in the command.
There are a few other possible explanations, since you have not given the specific command you ran. It's possible that you are running the command from somewhere other than the location of your .class file and not giving a full path to it, or that you are misspelling its name, and so forth. However, including a spurious .class suffix, which the java command does not expect, is the most common cause of this problem.
Suppose the class that contains your program's entry point (main() method) is called Foo, and that its source code was in a file in the current directory called Foo.java, so that you compiled your program by running javac Foo.java. Because Foo is the name of the class, this produces a file called Foo.class containing the compiled Java bytecode for that class.
To run the program, you must run:
java FooYour description makes it sound like you are instead running java Foo.class. This is a common stumbling block for users who using the java command to run .class files for the first time (whether they are programming in Java or just running .class files provided by someone else).
java Foo.class won't work; the java command interprets its argument as the name of the class that contains the entry point, not the name of the file. When you run java Foo it knows to look for a file called Foo.class.