Home » Core Java » What is Applet in Java??

What is Applet in Java??

An applet is a java program which can be embedded in a web program.
It can be run on any browser which supports Java.
It can be also be tested using appletviewer tool which is included in JDK.
For running an applet , it must be included in a web page using HTML tags.
e.g.

<html>  
      <body>  
          <applet code="DemoApplet.class" width="400" height="400">  
           </applet>  
     </body>  
</html>  

Restrictions of an Applet:

Due to security reasons, there are certain restrictions imposed on applet in java. They are as follows:
• An applet can not read or write files on the user’s system.
• An applet cannot load libraries or define native methods.
• An applet cannot read certain system properties.
• An applet cannot make network connections except to the host that it came from.
• An applet can not load or run any programs stored on the user’s system.

Applet Class:

• Applet class is present in java.applet package. It is the only class present in that package.
• It has many methods (over 20 methods) which are used to display images, play audio files etc.
• The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard interface between applets and their environment.

Applet class contains these life cycle methods:

I. public void init(): It is used to initialize the Applet. It is invoked only once.
II. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
III. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
IV. public void destroy(): is used to destroy the Applet. It is invoked only once.
• Applet class extends java.awt.Panel class.

A simple demo applet AppletDemoClass.java is as below:

import java.applet.Applet;
import java.awt.Graphics;
public class AppletDemoClass extends Applet {
	private static final long serialVersionUID = 1L;
	@Override
	public void init() {
		super.init();
		System.out.println("Inside init method");
	}

	@Override
	public void start() {
		super.start();
		System.out.println("Inside start method");
	}

	@Override
	public void stop() {
		super.stop();
		System.out.println("Inside stop method");
	}

	@Override
	public void destroy() {
		super.destroy();
		System.out.println("Inside destroy method");
	}

	public void paint(Graphics g) {
		g.drawString("welcome", 150, 150);
	}

}