Applet Life Cycle in Java

Applet Life Cycle:

Applets are small Java programs that are primarily used in Internet computing. It can be transported over the internet from one computer to another and run using the Applet Viewer or any web browser that supports Java. An applet is like an application program, it can do many things for us. It can perform arithmetic operations, display graphics, create animation & games, play sounds and accept user input, etc. Every Java applet inherits a set of default behaviours from the Applet class.

As a result, when an applet is loaded, it undergoes a series of changes in its state. The Applet Life Cycle is defined as how the applet is created, started, stopped and destroyed during the entire application execution. The methods to execute in the applet life cycle are init(), start(), stop(), destroy(). The applet life cycle diagram is given below:

applet life-cycle

  • Born or Initialization State
  • Running State
  • Idle State
  • Dead State

1. Born or Initialization State:
Applets enter the initialization state when it is first loaded. It is achieved by the init() method of the Applet class. Then applet is born.

public void init()
{
.............
.............
(Action)
}

 

2. Running State: The Applet enters the running state when the system calls the start() method of the Applet class. This occurs automatically after the applet is initialized.

public void start()
{
.............
.............
(Action)
}

 

3. Idle State: An applet becomes idle when it stops running. Stopping occurs automatically when we leave the page containing the currently running applet. This is achieved by calling the stop() method explicitly.

public void stop()
{
.............
.............
(Action)
}

 

4. Dead State: An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when we want to quit the browser.

 

public void destroy()
{
.............
.............
(Action)
}

Example of Applet Life Cycle in Java

import java.applet.Applet;
import java.awt.applet.*;
import java.awt.*;
import java.awt.Graphics;

public class MyApplet extends Applet {
 	
 	
 	public void init() {
   		setBackground(Color.BLUE); 
   		System.out.println("init() is invoked"); 
 	}
 	
 	
 	public void start() {
 		System.out.println("Start() is invoked"); 
 	}
 	
 	
 	public void paint(Graphics g) {
 		System.out.println("Paint() is invoked"); 
 	}
 	
 	
 	public void stop() {
 		System.out.println("Stop() is invoked"); 
 	}
 	
 	
 	public void destroy() {
 		System.out.println("Destroy() is invoked"); 
 	}
}