Skip to content

Tools

Java learners often compile and run Java programs using javac and java. However, JDK comes with many other powerful tools like jar, jhat, jdb, javap, javadoc, jcmd, javah, keytool, jconsole, jps, jstatd, jstat, jinfo, jmap, jstack and many more to help Java developers program better.

JAVAC

The javac compiler translates source code into bytecode. A separate .class file is created for each class that has been defined within a .java file. The compiler automatically monitors the dependencies between the source files. For example, if a class Y is used in a class X in the X.java file, which is located in Y.java, Y.java is automatically translated as well, if necessary. Instead of the list of file names, a text file can also be specified after an @ in which the files to be translated are specified separated by whitespaces.

javac [ options ] [@filelist | { filename.java }]
Option meaning
-classpath path Specifies the list of paths to search for class files. This switch overrides the value of any CLASSPATH environment variable that has been set.
-g Enable generation of debug information. This switch should be activated before a program is debugged.
-nowarn Disables the output of warnings.
-O Turns on the code optimizer.
-verbose Activates the output of messages about loaded source and class files during translation.
-depend Normally a source file is recompiled if the last modified date is after the modified date of the class file or if the class file is missing entirely. With the help of this switch, this decision is made in a more reliable way based on header information in the class file. However, the translation process may be slower.
-deprecation Ensures that every time a method marked as deprecated (@deprecated mark in the documentation comment) is called, additional information about possible workarounds is output. All methods from older JDKs that are no longer to be used in the current JDK are marked with this flag.
-target version Bytecode is generated that is compatible with the specified version of the runtime system.
-source version Source code that is compatible with the specified version is accepted.

JAVA

java [ options ] classname [{ args }]
javaw [ options ] classname [{ args }]

The java interpreter is used to execute compiled Java programs that are available as bytecode in .class files. javaw serves the same purpose, but does not create a terminal window when the program is started and does not allow the use of the standard streams System.in, System.out and System.err. When calling both programs, the name of a class file is expected (without the .class extension). In order for it to be executed, it must contain a class method main with the following signature:

public static void main(String[] args)
Option meaning
-classpath path Specifies the list of paths to search for class files. Alternatively, the abbreviation -cp can be used.
-prof Activates the profiler in the interpreter in pre-1.2 versions of the JDK, which writes information about the runtime behavior of the application to the java.prof file. As of JDK 1.2, the profiler is activated with the -Xprof or -Xrunhpof option.
-version Output of the version number.
-help Output of a short help text.
-verbose Outputs a message to the console each time a class is loaded. As of JDK 1.3, the switches: class,: gc or: jni can be added.
-verbosegc Causes the garbage collector to output a message each time it is called.
-DpropName = value Assigns the value value to the property propName.
-Xms n Specifies the size of the memory allocated at startup.
-Xmx n Specifies the size of the maximum allocable memory.

JDB

jdb is the JDK's debugger. It offers the possibility of running programs in a controlled manner and setting breakpoints, executing the next command in single-step mode or inspecting the content of variables or objects. However, you shouldn't expect too much from jdb, because the program is a command line debugger in the most beautiful UNIX tradition. It has little in common with the graphical debuggers of the integrated Java development environments. Unfortunately, it is not only more difficult to use, but also lacks some important features of modern debuggers.

serialver

The serialVersionUID of a class can be accessed with serialver. If the program is called with a class name, it outputs the serialVersionUID on the console. If it is called with the -show option (and without a class name), it is called with a simple graphical user interface.

serialver -show | classname

JAVADOC

Documentation is a key part of program code. Not only does it help others understand the program, it also helps the author recall how his / her own older programs also work. Java encourages us to write documentation directly into the source code since external documentation can easily become outdated as the program changes. Updating the documentation as and when program code changes requires less effort. Java standardizes documentation writing syntax and semance. It also provides a Javadoc tool to generate HTML files for convenient viewing of the documentation from a web browser.

Note that Java also uses this tool to generate source code specifications for Java APIs. Indeed, if we have the source code we can generate this ourselves. We can also use javadoc to generate HTML documentation similar to the reference pages of Java APIs.

Since documentation comments (or just doc comments) go straight into the source code, we have to hide it from the Java compiler. So documentation is written as special comments between the sequence of characters /** and */ starting and ending the comment, respectively.

Here is an example of a single-line comment:

 /** This is a single line java doc comment. */ 

Comments may spread across multiple lines:

/** 
  This is an example of comments 
  that spans multiple lines. 
  */

A doc comment may be attached with only a class, interface, constructor, method, or field statement by writing a comment immediately before it. The following is a comment with a Class X attached.

/** Represents the class of two-dimensional geometrical points. */ 
public class Point {} 

Similarly, the following attaches a comment with a method.

public class Point { 
    private int x, y; 
    /** Returns x coordinate of the point */ 
    public int getX() { 
        return x; 
    }
} 

We can pass either a series of Java package names or source files to javadoc as argument(s). Here is an example:

javadoc Point.java
Creating destination directory: "point\" 
Loading source file Point.java... 
Constructing Javadoc information... 
Standard Doclet version 1.7.0_07 
Building tree for all the packages and classes... 
Generating point\Point.html... 
Generating point\package-frame.html...
Generating point\package-summary.html... 
...

We can place HTML tags inside the description section as usual. For example, the following example uses the <b> tag to make it more important: <b>javac</b> is an import tool.

In addition to the main description, the comment document may have an optional tag section. The main description starts after the start delimiter /** and must end before the tag section. The tag section contains special tags that are used to generate a well-formatted API for the documented code.

The tags will take the form @tagname. For example, we can use @param in comments on methods and @return tags (if applicable) to describe the parameters of the method and return value, respectively. The @param tag should be followed by the name of the parameter, and then a description of the parameter. Similarly, the @return tag is followed simply by a description of the return value. Here is an example of this:

/** 
  @param x     the X coordinate of the point  
*/ 
public void setX(int x) {
  this.x = x; 
}
/** 
  @return     the X coordinate of the point 
*/ 
public int getX() {
  return x;
}
The summary of frequently used tags is shown in the following table.

Tag Description
@author name-text Adds an “Author” entry with the specified name-text
{@code text} Displays text in code font
{@docRoot} Represents the relative path to the generated document’s (destination) root directory from any generated page.
@deprecated deprecated-text Adds an “Deprecated” entry with the specified deprecated-text
@exception class-name description Adds a “Throws” subheading to the generated documentation, with the classname and description text
{@inheritDoc} Inherits a comment from the nearest inheritable class or implementable interface
{@link package.class#member label} Inserts an in-line link with visible text label that points to the documentation for the specified package, class or member name of a referenced class
{@linkplain package.class#member label} Similar to {@link}, except the link’s label is displayed in plain text than code font
{@literal text} Displays text without interpreting the text as HTML markup or nested javadoc tags
@param parameter-name description Adds a parameter with the specified parameter-name followed by the specified description to the “Parameters” section
@return description Adds a “Returns” section with the description text
@see reference Adds a “See Also” heading with a link or text entry that points to reference
@serial field-description, include, exclude Used in the doc comment for a default serializable field
@serialData data-description Documents the data written by the writeObject( ) or writeExternal( ) methods
@serialField field-name field-type field-description Documents an ObjectStreamField component
@since since-text Adds a “Since” heading with the specified since-text to the generated documentation (Contd)
@throws class-name description Similar to @exception tag
{@value package.class#field} When {@value} is used in the doc comment of a static field, it displays the value of that constant
@version version-text Adds a “Version” subheading with the specified version-text to the generated docs when the -version option is used

JAVAP

The javap disassembler reads the translated code of a class and outputs information about it on the standard output. Either only information about variables and methods or the complete bytecode of the class can be output. javap is unable to restore the Java source code of a class file.

javap [ options ] classname

When calling, the name of the class must be specified without the .class extension, for example:

javap -c java.lang.String

Option meaning
-classpath path Specifies the list of paths to search for class files.
-public Only the class elements of the type public are displayed.
-protected Only the class members of type public and protected are displayed.
-package The class elements of type public, protected and the elements with package visibility are displayed. This is the default.
-private All class elements are displayed.
-c Disassemble the code.
-s Output of the method signatures.
-l Output line numbers.

JCMD

Diagnostic commands can be sent to a running JVM with the command line program jcmd. The shell jcmd is available into the $JAVA_HOME/bin folder. If you execute it without any parameter it will dump the list of Java Processes which are running:

$ jcmd
6328 sun.tools.jcmd.JCmd

The Java programs are identified again via a PID, which jcmd can also display. In order to use jcmd you need to execute some commands against the Java Process (you can reference it either by PID or by its name). The list of available commands depend on the actual JDK you are using.

The "help" command however will display which commands are built-in:

$ jcmd 28430 help
28430:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
VM.native_memory
VM.check_commercial_features
VM.unlock_commercial_features
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.run_finalization
GC.run
VM.uptime
VM.flags
VM.system_properties
VM.command_line
VM.version
help

JHAT

jhat is a Java heap analysis tool or heap dump file browser. It parses a Java heap dump file and launches a Web server to browse heap dump files using your favorite webbrowser. jhat supports pre-designed queries (such as show all instances of a known class Foo**) as well as OQL (Object Query Language) - a SQL-like query language to query heap dumps. Help on OQL is available from the OQL help page shown by "jhat". With the default port, OQL help is available at http://localhost:7000/oqlhelp/

But the jmap tool included in the Windows version of JDK only supports functions to print histogram of Java object heap and generate a heap dump of a given JVM process.

C:\...\java\jdk1.8.0\bin\jhat -help

Usage: jhat [-stack <bool>] [-refs <bool>] [-port <port>] 
   [-baseline <file>] [-debug <int>] [-version] [-h|-help] <file>

   -stack false     Turn off tracking object allocation call stack.
   -refs false      Turn off tracking of references to objects
   -port <port>     Set the port for the HTTP server. Default is 7000.
   -exclude <file>  Specify a file that lists data members that should
                    be excluded from the reachableFrom query.
   -baseline <file> Specify a baseline object dump.  Objects in
                    both heap dumps with the same ID and same class 
                    will be marked as not being "new".
   -debug <int>     Set debug level.
                    0:  No debug output
                    1:  Debug hprof file parsing
                    2:  Debug hprof file parsing, no server
   -version         Report version number
   -h|-help         Print this help and exit
   <file>           The file to read

For a dump file that contains multiple heap dumps,
you may specify which dump in the file
by appending "#<number>" to the file name, i.e. "foo.hprof#3".

All boolean options default to "true"

JAR

A Java ARchive (JAR) is a file bundling multiple files into one single file. Typically a JAR-file Contains auxiliary and class media. JAR files clearly carry the following advantages: * Java programs (including the Java core API) are usually distributed as JAR files. * JAR files are formatted using ZIP file. So, we are able to compress/decompress files. * Since JAR file contains a bundle of files, it is possible to transfer a set of files over the network using a single request * Optionally, we can seal packages stored in JAR files to ensure continuity of the versions. Sealing a box inside a JAR file ensures all classes specified in that package are available. * A JAR file which contains software requiring special privilege can be digitally signed. This enables end-users to Test the signature and the author's digital certificate to allow/disallow the privilege. * Use JAR files with its packaging for extension functions, we can extend the functionality to Java core framework. * JAR files can contain a special file for holding actual file metadata. This helps us to customize your program

Remember that JAR files are identical to the tar (tape archive) files in Unix/Linux:

jar
Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
  -c create new archive
  -t list table of contents for archive
  -x extract named (or all) files from archive
  -u update existing archive
  -v generate verbose output on standard output
  -f specify archive file name
  -m include manifest information from specified manifest file
  -e specify application entry point for stand-alone application
      bundled into an executable jar file
  -0 store only; use no ZIP compression
  -M do not create a manifest file for the entries
  -i generate index information for the specified jar files
  -C change to the specified directory and include the following file
      If any file is a directory then it is processed recursively.
      The manifest file name, the archive file name and the entry point name are
      specified in the same order as the 'm', 'f' and 'e' flags.

Example 1: to archive two class files into an archive called classes.jar:
    jar cvf classes.jar Foo.class Bar.class
Example 2: use an existing manifest file 'mymanifest' and archive all the files in the foo/ directory into 'classes.jar':
    jar cvfm classes.jar mymanifest -C foo/ .
  • Exercise 1:

    • write an small application with 2 classess
    • generate document using Javadoc in src directory:
      • javadoc -d doc *
  • Exercise 2:

    • for the application of Execise 1, create the following comments:
      • @param provides any useful description about a method's parameter or input it should expect
      • @return provides a description of what a method will or can return
      • @see will generate a link similar to the {@link} tag, but more in the context of a reference and not inline
      • @since specifies which version the class, field, or method was added to the project
      • @version specifies the version of the software, commonly used with %I% and %G% macros
      • @throws is used to further explain the cases the software would expect an exception
      • @deprecated gives an explanation of why code was deprecated, when it may have been deprecated, and what the alternatives are