Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to compile and run Java applet code

📅 2015-Jan-22 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

The Java programming language can be used to write applets that run in a browser. Applet source code is similar to a typical Java program source code, except that it does not have a main method. Applet source code can be created in .java files.

Compiling them is the same as usual:

$ javac

This generates a foo.class compiled bytecode file.

However, running the generated .class file using the Java VM gives this error:

$ java foo
Error: Main method not found in class foo, please define the main method as:
   public static void main(String[] args)

Applet can only be executed in a browser by opening a HTML file that refers to this applet .class file. A minimal HTML file that does is:

<applet code=foo width=400 height=200>

Save this as foo.html file in the same directory as the foo.class file. Open it in a browser that can run Java applets and you can see the result. :)

Tried with: Java 1.7, Firefox 34 and Ubuntu 14.04