Compiling a Java Program from the Command Line

1. Download the latest version of the JDK (Java Development Kit) installer.  As of this writing, this is available at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

2. Navigate to the directory where the JDK installer was downloaded and double-click the installer’s icon to begin the installation process.

3. Follow the prompts to install the JDK.  Make a note of the directory to which the JDK is installed.  This directory contains a subdirectory called “bin”, which is where the file “javac.exe” (the Java compiler) is stored.

4. In any convenient location, create a new directory named “HelloWorld”.

5. In the HelloWorld directory, create a new text file named “HelloWorld.java”, containing the following text.

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

6. Still in the HelloWorld directory, create a new text file named “JavaPathAndProgramNameSet.bat”, and enter the following text.  Substitute the path of the directory where javac.exe is located for the bracketed text.  This directory was created in step 2.

set javaPath="[the directory where javac.exe is located]"
for %%* in (.) do (set programName=%%~n*)

7. Still in the HelloWorld directory, create a new text file named “ProgramBuild.bat”, containing the following text.

call JavaPathAndProgramNameSet.bat

%javaPath%\javac.exe %programName%.java

pause

8. Double-click the icon for ProgramBuild.bat.  A console window will appear and javac.exe will compile HelloWorld.java.

9. After the compilation is complete, a prompt saying “press any key to continue” will appear.  Press a key to close the console window.

10. In the HelloWorld directory, a new file called “HelloWorld.class” should now be present.  This file contains the “compiled” program.  Note, however, that since Java compiles to “bytecode” rather than native machine language, this program cannot be run directly from the host operating system. Instead, the Java Runtime Environment must be used to run it.

11. In the HelloWorld folder, create a new text file named “ProgramRun.bat”, containing the following text.

call JavaPathAndProgramNameSet.bat

%javaPath%\java.exe %programName%

pause

12. In the HelloWorld directory, double-click the icon for ProgramRun.bat to run it.  A console window should appear, and the text “Hello, world!” should appear somewhere in it.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s