Tuesday, September 6, 2011

javac and java at the command line

After you have created a Java source code file, you will want to compile and run your code. Using a simple HelloWorld class, here is how it is done at the command line.

The code will look like this:

/** Filename: HelloWorld.java
  * Assignment #, page #, exercise #
  * Student Name
  * Due Date: 13 September 2011
  */


public class HelloWorld
{
    public static void main(String[] args)
    {

        // Display message
        System.out.println("Hello World!");
    }
}


Let us assume that you saved your work on your flash drive in a directory called comp171

    e:\comp171>

You must name the file the same as the class. This is a requirement of the Java programming language and Java is case-sensitive. 'J' is not equivalent to 'j'.

So, you would save this file as

    e:\comp171\HelloWorld.java

To compile the code, you use the javac compiler:

    e:\comp171> javac HelloWorld.java

This will create a class file:

    e:\comp171\HelloWorld.class

To execute the code, you use the java interpreter:

    e:\comp171> java HelloWorld
    Don't add the .class extension!

The output will be:

    e:\comp171> Hello World!