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

    java TheClassName</pre>

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

    <pre>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) :

    <pre>Error: Could not find or load main class TheClassName.</pre>
    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)

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