DEV Community

Abhinav Pandey
Abhinav Pandey

Posted on • Updated on

Running java programs from the terminal

Here's a few basic commands for executing standalone java programs.
I have been a Java developer for almost 5 years but I rarely execute Java programs from command line and am not very fluent at it. I just thought I'll note it down here for myself and others.

Compiling a java class

javac -cp /project/classes -d /project/classes /path/to/File.java
Enter fullscreen mode Exit fullscreen mode

-cp -> classpath - path where other compiled dependencies are present.
-d -> destination of the generated .class(bytecode) file from the operation.

Executing the program

java -cp /project/classes ClassFileName(or package.ClassFileName) 
     arg1 arg2 ...
Enter fullscreen mode Exit fullscreen mode

package.ClassFileName is required if the classpath contains sub-folder structure.
From Java 11, you can also specify a single source file and compilation and execution can be done in a single command.
This will not generate a .class file.
This works only if the source file contains all the source and does not require other compiled classes to run. E.g. a typical Hello world scenario

java /path/to/package/ClassFileName arg1 arg2 ...
Enter fullscreen mode Exit fullscreen mode

Creating javadoc

javadoc -d /documentation/path 
        -sourcepath /path/to/java/files
        -subpackages /path/to/root/package
Enter fullscreen mode Exit fullscreen mode

Top comments (0)