September 12, 2016

Compiling and run java program in command line

1. If your code is not in any package, then running the following command will compile and execute your java program just fine

javac TheClassName.java
java TheClassName


 2. However, if the class is in a package such as below :

package thepackagename;

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

Then calling the same command will give you the following results (or similar) :

Error: Could not find or load main class TheClassName.

This is because, to run your code, it needs to be called with its fully-qualified name (include packagename in it's name) and also note that this command must be called from the directory in which the thepackagename directory exists, not where your class TheClassName is placed (not inside the thepackagename folder itself - must be one level above)

cd {path-to-one-level-above-thepackagename}
javac thepackagename/TheClassName.java
java thepackagename.TheClassName