Java applet – hello world

A java applet is a web object that allows you to do some funky things within a web page, you could even have a game on the screen with a java applet. But as normal you have to start from the start as such, the most used starts are the classic “hello world” example.

In a java applet, it is basically a class called Applet that you extend from and this has all of base code inside it so you only need to implement the virtual functions

  1. init
  2. start
  3. paint
  4. destory
  5. stop

And these are the basic functions that allow you to call other classes of your choice. The init – (initialize), setups up the environment of your choice, start is where the application (GUI interface) will run within, paint is what is painted to the applet screen, destory is when you destory the applet you may need to clean up some code, stop is when the application/applet is stopped.

The main basic class will extend from a applet (java.applet.Applet) so you will need to import that class library

import java.applet.Applet;
// basic class extends the applet
public class HelloWorld extends java.applet.Applet {

and then implement the functions start,init,stop,destory and paint if required. Below is more code that will resize the basic applet object and display (paint) the words Hello World using the Graphics class object drawString method.

import java.awt.Graphics;		// need this for the Graphics part of the paint function
import java.applet.Applet;		// to extend from.
public class HelloWorld extends java.applet.Applet {
    // resize the screen 
    public void init()
    public void start()
    // draw with the Graphics class object a string on the canvas, point 50, 25
    public void paint(Graphics graphicsObj)
	graphicsObj.drawString("Hello World!", 50,25);
    public void stop()
    public void destroy()

Is you save that as “” and then you need to compile it into a class file (which is a common object file that java can read to run within the virtual machine).


which will output the HelloWorld.class file, which you will need to include into the html code applet tag, below is the HTML code

<title>A hello world</title>
Test output of the program
<applet code="HelloWorld.class" width=150 height=25>

The output would be

Test output of the program

Note: If you look at the source code of this page, it will say

<applet code="HelloWorld.class" codebase="/Appletsexamples/"  archive="HelloWorld.jar" width="150" height="25"></applet>

I had to add in the codebase and archive because of the hosting, to create a jar file you just need to do

jar cf <tarname> <file(s) name>
jar cf HelloWorld.jar HelloWorld.class

The jar file is basically a zipped archive.

Leave a Reply

Your email address will not be published. Required fields are marked *