Java: Getting started

There are two environments we are interested in when working with java: applications and applets.

For both of these you need to compile your classes first. By convention, source files for classes in Java are stored in files with a .java extension. So, for a class called Helloworld there should be a file named Helloworld.java. To compile this class do:

this will create a HelloWorld.class

Note that javac allows you one public class per file and insists that the file have the same name as the class. If the filename and class do not match, javac issues a compilation error. A single file can contain multiple classes, as long as only one of the classes is public . You should avoid packing lots of classes into a single file.

  1. Applets

    Applets run on browsers (Appletviewer, Mozilla Firefox, IE, etc.)

    To run from your machine and simulate what will happen on a web page, you can use appletviewer to test your applets. To do this you need a classname.html file

    Here is an example of HelloWorld.html

      <html><head> <title>Test</title> </head> <body> <hr> <applet code=HelloWorld.class width=200 height=100> </applet> <hr> </body> </html>
    This would have been cool, if it worked...sigh

    Here is the code for the definition of the class: HelloWorld.java that does not use Swing

    To Run (after compilation):

      appletviewer HelloWorld.html
    Here is the code for the definition of the class: HelloSwingApplet.java that does use Swing

      // // Sample HelloWorld applet // /* <APPLET CODE="HelloSwingWorldApplet.class" WIDTH=300 HEIGHT=100> </APPLET> */ import javax.swing.*; import java.awt.*; public class HelloSwingWorldApplet extends JApplet { public void init() { Container contentPane = getContentPane(); JLabel label = new JLabel( "You are successfully running a Swing applet! Hello World"); label.setHorizontalAlignment(JLabel.CENTER); contentPane.add(label); } }
  2. Applications: Below is HelloWorldApp.java

      // // Sample HelloWorld application // class HelloWorldApp { public static void main(String args[]) { System.out.println("Hello World!"); } }

    To Run (after compilation):

      java HelloWorldApp

For compilation, you can use various options with javac. One useful option is -d where you specify an alternative directory for storing the class files it generates. note if HelloWorld is in a specified package then javac with the -d option will automatically create any directories needed to store the class file in the appropriate place (i.e, subdirectories mirroring the package name
See
javac - The Java Compiler page

For the java command, one has options as well.

One such option is -classpath which allows you set the CLASSPATH on the command line. java - The Java Interpreter page

In fact, here is the JDK Tools and Utilities page with Basic Tools, Security Tools, etc. links