Your browser has JavaScript turned off. This page is best viewed with Javascript enabled. Certain functions on this site will not work, and some style sheets will not load. Check your browser preferences to enable JavaScript.

Teach Yourself Java

How to Compile and Run a Java Program

Everytime you make a Java program, you will follow the same 3 steps:

  1. Create a source file. This is the file where you write the java code. This file can be written in any text editor (such as Notepad on Windows or Xemacs on UNIX). This file must be saved with a .java extension.
    Note: the Java compiler is case-sensitive so you must capitalize consistently. HelloWorld is not the same as helloworld.

  2. Compile the source file. The compiler, javac, takes your source file and translates it into bytecode.
    1. Bring up the Command Prompt
      • Windows XP- Start Menu->Accessories->"Command Prompt"
      • Windows 95/98/2000/NT/ME - Start menu->"MS-DOS Prompt"
      • UNIX - Open eterm or xterm
    2. Move into the directory that contains your source file(s)
      • Type cd dirname to change directories (where dirname is in the name of the directory you want to go into and is located in the current directory).
      • Type ls in UNIX or dir in DOS (Windows) to list the contents of the current directory.
      • Type ../ to move up (back) a directory.
    3. Type javac filename
      • filename should be the name of your .java source file(s)
      • If you have errors trying to compile, see our FAQ Page.

  3. Run the program. Since we are dealing only with Applets in this guide, there are 2 options for running your program. We can either view the applet with the AppletViewer or embed our applet on a website and view it in a java-enabled web browser.

    • Web -
      1. Create a web page
        • For help see Basic HTML or use this basic template.
        • Make sure that you set the source of the Applet to the name of your compiled class files. I.E. In the <applet> tag, make sure you set code="filename.class" where filename is the class file you just compiled.
      2. Open your web page using any java-enabled web browser (such as Internet Explorer or Netscape Navigator).

    • AppetViewer -
      1. Create a web page
        • See instructions above.
      2. Bring up the Command Prompt
        • See above if you have trouble.
      3. Move into the directory that contains your web page and the .class files you just compiled (probably in the same directory you were in when you compiled).
        • See above if you have trouble.
      4. Type appletviewer filename
        • filename should be the name of your website (.html file)