For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
The applet life cycle in Java Programming represents the sequence of events that occur from the creation of an applet to its termination. Understanding this cycle is crucial for developing effective Java applets. Although Java applets have been deprecated in modern Java versions and are no longer supported in most browsers, learning about the applet life cycle provides valuable insights into how component-based applications function. This guide explains what is applet in Java, explores the applet life cycle phases, compares applets with applications, and demonstrates how to create and run applet programs with practical examples.
Want to master Java like a pro? upGrad’s software engineering course gives you real-world training and expert mentorship.
An applet in Java is a small program designed to be embedded within a web page and run inside a browser. Unlike standalone Java applications, applets operate in a restricted environment called the applet container or viewer, which ensures security and controls their execution.
Applets are mainly used to add interactive features to web applications without needing server-side processing. They are created by extending the java.applet.Applet class or, in later versions, the javax.swing.JApplet class, which offers improved GUI capabilities.
Step into the future of tech with these top-rated AI and data science courses:
• M.Sc. in AI & Data Science – Jindal Global University
• Master’s in Data Science – LJMU
• PG Diploma in ML & AI – IIIT Bangalore
In technical terms, an applet is a Java class that extends either the java.applet.Applet class or the javax.swing.JApplet class. Here's a basic definition of an applet in Java:
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet World!", 50, 50);
}
}
The HTML code required to embed this applet in a web page would look like:
<applet code="SimpleApplet.class" width="300" height="200">
Your browser does not support Java applets.
</applet>
Also read: Exception Handling in Java
The applet life cycle in Java refers to the sequence of method calls that occur during an applet's existence. This cycle consists of five main phases that govern how an applet initializes, starts, runs, stops, and terminates.
Must explore: Serialization in Java
Let's examine each of these phases in detail:
The init() method is called when an applet is first loaded. This is where you should perform one-time initialization tasks such as:
This method is called only once during the applet's life cycle.
@Override
public void init() {
// One-time initialization code
System.out.println("Applet initialized.");
// Set background color
setBackground(Color.WHITE);
// Create and add components
Button button = new Button("Click Me");
add(button);
// Initialize variables
counter = 0;
}
Must read: Annotations in Java
The start() method is called after the init() method completes, and also whenever the applet becomes visible again after being hidden (for example, when a user returns to a webpage containing the applet). This is where you should:
The start() method may be called multiple times during an applet's life cycle.
@Override
public void start() {
System.out.println("Applet started.");
// Create and start animation thread
if (animationThread == null) {
animationThread = new Thread(this);
animationThread.start();
}
// Resume any paused activities
isPaused = false;
}
Also check: Key Differences Between Inheritance and Polymorphism
The paint(Graphics g) method is called when the applet needs to render its visual content. This could be triggered by:
The paint() method may be called multiple times during an applet's life cycle.
@Override
public void paint(Graphics g) {
System.out.println("Applet painting.");
// Draw text
g.setFont(new Font("Arial", Font.BOLD, 16));
g.drawString("Current Count: " + counter, 50, 50);
// Draw shapes
g.setColor(Color.BLUE);
g.fillRect(50, 70, 100, 30);
g.setColor(Color.RED);
g.drawOval(180, 70, 50, 50);
}
Must explore: Polymorphism in Java: Concepts, Types, Characterisitics & Examples
The stop() method is called when the applet becomes invisible to the user, for example, when the user navigates away from the page containing the applet. This is where you should:
Like start(), the stop() method may be called multiple times during an applet's life cycle.
@Override
public void stop() {
System.out.println("Applet stopped.");
// Suspend animation but don't kill the thread
isPaused = true;
// Save current state if needed
saveState();
}
Check out: Inheritance in Java
The destroy() method is called when the applet is about to be unloaded, such as when the browser is closed or the user navigates away permanently. This is where you should:
This method is called only once during the applet's life cycle.
@Override
public void destroy() {
System.out.println("Applet being destroyed.");
// Terminate the animation thread
if (animationThread != null) {
animationThread.interrupt();
animationThread = null;
}
// Release other resources
releaseResources();
}
Also read: Types of Polymorphism in Java
Here's a visual representation of the applet life cycle in Java:
Let's create a comprehensive example demonstrating the applet life cycle:
import java.applet.Applet;
import java.awt.*;
import java.util.Date;
/*
<applet code="LifeCycleApplet.class" width="400" height="300">
</applet>
*/
public class LifeCycleApplet extends Applet implements Runnable {
// Member variables
private Thread animationThread;
private int counter = 0;
private boolean isPaused = false;
private Font messageFont, counterFont;
private String status = "Initialized";
private String initTime, startTime, stopTime, destroyTime;
@Override
public void init() {
// One-time initialization
initTime = new Date().toString();
status = "Initialized";
// Set up fonts
messageFont = new Font("SansSerif", Font.BOLD, 14);
counterFont = new Font("Monospaced", Font.PLAIN, 18);
// Set background color
setBackground(Color.WHITE);
// Add a button that increments the counter
Button incrementButton = new Button("Increment Counter");
incrementButton.addActionListener(e -> {
counter++;
repaint();
});
add(incrementButton);
// Add a button that resets the counter
Button resetButton = new Button("Reset Counter");
resetButton.addActionListener(e -> {
counter = 0;
repaint();
});
add(resetButton);
System.out.println("init() method called at " + initTime);
}
@Override
public void start() {
startTime = new Date().toString();
status = "Running";
isPaused = false;
// Start the animation thread
if (animationThread == null) {
animationThread = new Thread(this);
animationThread.start();
}
System.out.println("start() method called at " + startTime);
}
@Override
public void run() {
// Animation thread logic
while (animationThread != null) {
try {
Thread.sleep(1000); // Update once per second
if (!isPaused) {
// Auto-increment counter in the background
counter++;
repaint();
}
} catch (InterruptedException e) {
break;
}
}
}
@Override
public void paint(Graphics g) {
// Set font for messages
g.setFont(messageFont);
// Draw status and lifecycle information
g.setColor(Color.BLACK);
g.drawString("Applet Status: " + status, 20, 50);
g.drawString("Init Time: " + initTime, 20, 70);
g.drawString("Start Time: " + startTime, 20, 90);
if (stopTime != null) {
g.drawString("Last Stop Time: " + stopTime, 20, 110);
}
if (destroyTime != null) {
g.drawString("Destroy Time: " + destroyTime, 20, 130);
}
// Draw counter
g.setFont(counterFont);
g.setColor(Color.BLUE);
g.drawString("Counter: " + counter, 20, 170);
// Draw a moving element to visualize animation
g.setColor(Color.RED);
int xPos = (counter % 300) + 50;
g.fillOval(xPos, 200, 20, 20);
}
@Override
public void stop() {
stopTime = new Date().toString();
status = "Stopped";
isPaused = true;
System.out.println("stop() method called at " + stopTime);
}
@Override
public void destroy() {
destroyTime = new Date().toString();
status = "Destroyed";
// Terminate the animation thread
if (animationThread != null) {
animationThread.interrupt();
animationThread = null;
}
System.out.println("destroy() method called at " + destroyTime);
}
}
Expected Output: When running this applet, you'll see:
The console will also show messages indicating when each lifecycle method is called.
To run an applet program in Java, you have several options:
The appletviewer tool was included with older JDK versions and allows you to run and test applets:
# Compile the applet
javac MyApplet.java
# Run using appletviewer
appletviewer MyApplet.html
Where MyApplet.html contains the applet tag:
<applet code="MyApplet.class" width="400" height="300">
Your browser does not support Java applets.
</applet>
Historically, applets were run in browsers with the Java Plugin installed:
<!-- HTML file content -->
<html>
<head>
<title>My Java Applet</title>
</head>
<body>
<h1>My First Applet</h1>
<applet code="MyApplet.class" width="400" height="300">
Your browser does not support Java applets.
</applet>
</body>
</html>
Since applets are deprecated, a modern approach is to convert the applet to a JFrame application:
import javax.swing.JFrame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AppletToApplication {
public static void main(String[] args) {
// Create a JFrame to host the applet
JFrame frame = new JFrame("Applet in JFrame");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the applet
LifeCycleApplet applet = new LifeCycleApplet();
// Add the applet to the frame
frame.add(applet);
// Call the applet's lifecycle methods manually
applet.init();
// When frame becomes visible, start the applet
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
applet.start();
}
@Override
public void windowClosing(WindowEvent e) {
applet.stop();
applet.destroy();
}
});
// Display the frame
frame.setVisible(true);
}
}
Creating a Java applet involves the following steps:
Create a Java class that extends Applet or JApplet:
import java.applet.Applet;
import java.awt.Graphics;
public class MyFirstApplet extends Applet {
// Applet lifecycle methods
@Override
public void init() {
System.out.println("Applet initialized");
}
@Override
public void start() {
System.out.println("Applet started");
}
@Override
public void paint(Graphics g) {
g.drawString("My First Applet", 50, 50);
}
@Override
public void stop() {
System.out.println("Applet stopped");
}
@Override
public void destroy() {
System.out.println("Applet destroyed");
}
}
Compile the Java source code using the Java compiler:
javac MyFirstApplet.java
Create an HTML file to embed the applet:
<!DOCTYPE html>
<html>
<head>
<title>My First Applet</title>
</head>
<body>
<h1>My First Java Applet</h1>
<applet code="MyFirstApplet.class" width="400" height="200">
Your browser does not support Java applets.
</applet>
</body>
</html>
Run the applet using one of the methods described in the previous section.
Let's create a more interactive applet that demonstrates common GUI elements and user interaction:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="InteractiveApplet.class" width="500" height="400">
</applet>
*/
public class InteractiveApplet extends Applet implements ActionListener {
private TextField inputField;
private Button submitButton, clearButton;
private Choice colorChoice;
private Checkbox boldCheckbox;
private String message = "";
private Color textColor = Color.BLACK;
private boolean isBold = false;
@Override
public void init() {
// Set layout
setLayout(new BorderLayout());
// Create panels for organization
Panel inputPanel = new Panel(new FlowLayout());
Panel controlPanel = new Panel(new GridLayout(3, 1));
// Create input field
inputField = new TextField(20);
inputPanel.add(new Label("Enter text: "));
inputPanel.add(inputField);
// Create buttons
submitButton = new Button("Submit");
submitButton.addActionListener(this);
clearButton = new Button("Clear");
clearButton.addActionListener(this);
Panel buttonPanel = new Panel(new FlowLayout());
buttonPanel.add(submitButton);
buttonPanel.add(clearButton);
// Create color choice menu
colorChoice = new Choice();
colorChoice.add("Black");
colorChoice.add("Red");
colorChoice.add("Blue");
colorChoice.add("Green");
colorChoice.addItemListener(e -> {
String selected = colorChoice.getSelectedItem();
switch (selected) {
case "Red": textColor = Color.RED; break;
case "Blue": textColor = Color.BLUE; break;
case "Green": textColor = Color.GREEN; break;
default: textColor = Color.BLACK;
}
repaint();
});
Panel colorPanel = new Panel(new FlowLayout());
colorPanel.add(new Label("Text Color: "));
colorPanel.add(colorChoice);
// Create checkbox for bold text
boldCheckbox = new Checkbox("Bold Text");
boldCheckbox.addItemListener(e -> {
isBold = boldCheckbox.getState();
repaint();
});
// Add components to control panel
controlPanel.add(inputPanel);
controlPanel.add(buttonPanel);
controlPanel.add(colorPanel);
// Add to main applet
add(controlPanel, BorderLayout.NORTH);
add(boldCheckbox, BorderLayout.SOUTH);
// Set background color
setBackground(Color.LIGHT_GRAY);
}
@Override
public void paint(Graphics g) {
// Clear the drawing area
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
// Set font based on checkbox state
if (isBold) {
g.setFont(new Font("SansSerif", Font.BOLD, 18));
} else {
g.setFont(new Font("SansSerif", Font.PLAIN, 18));
}
// Set color and draw message
g.setColor(textColor);
if (!message.isEmpty()) {
FontMetrics fm = g.getFontMetrics();
int messageWidth = fm.stringWidth(message);
int x = (getWidth() - messageWidth) / 2;
g.drawString(message, x, 200);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitButton) {
message = inputField.getText();
} else if (e.getSource() == clearButton) {
message = "";
inputField.setText("");
}
repaint();
}
}
Expected Output: When running this interactive applet, you'll see:
Understanding the difference between applet and application in Java is important for choosing the right approach for your project:
Feature | Java Applet | Java Application |
Entry Point | No main() method | main() method is required |
Execution Environment | Runs in browser or applet viewer | Runs as standalone program |
Security | Restricted by sandbox security model | Has full access to system resources |
Lifecycle Control | Controlled by browser/container | Controlled by the program itself |
GUI Components | AWT/Swing components built-in | Requires explicit setup of GUI framework |
Deployment | Embedded in web pages | Distributed as JAR files or native executables |
User Interaction | Limited to the applet container | Can interact with entire system |
Network Access | Limited to the origin server | Unrestricted network access |
Loading | Automatically loaded with web page | Must be explicitly started by user |
Current Status | Deprecated and not supported in modern browsers | Still widely used and supported |
Here's an example showing the same functionality implemented as both an applet and an application:
// As an Applet
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
@Override
public void paint(Graphics g) {
g.drawString("Hello, World!", 50, 50);
}
}
// As an Application
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Dimension;
public class HelloWorldApplication {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello, World!", 50, 50);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
};
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
While applets are deprecated, understanding their advanced features provides valuable knowledge about Java GUI applications:
Applets can receive parameters from HTML tags:
<applet code="ParameterApplet.class" width="400" height="300">
<param name="message" value="Hello from HTML!">
<param name="color" value="blue">
</applet>
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class ParameterApplet extends Applet {
private String message;
private Color color;
@Override
public void init() {
// Get parameters from HTML
message = getParameter("message");
if (message == null) message = "No message provided";
String colorParam = getParameter("color");
if (colorParam != null) {
switch (colorParam.toLowerCase()) {
case "red": color = Color.RED; break;
case "blue": color = Color.BLUE; break;
case "green": color = Color.GREEN; break;
default: color = Color.BLACK;
}
} else {
color = Color.BLACK;
}
}
@Override
public void paint(Graphics g) {
g.setColor(color);
g.drawString(message, 50, 50);
}
}
Applets can load and play media:
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MediaApplet extends Applet {
private AudioClip sound;
private Image image;
@Override
public void init() {
// Load sound
sound = getAudioClip(getCodeBase(), "beep.au");
// Load image
image = getImage(getCodeBase(), "logo.gif");
// Add mouse listener to play sound on click
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
sound.play();
}
});
}
@Override
public void paint(Graphics g) {
if (image != null) {
g.drawImage(image, 50, 50, this);
}
g.drawString("Click anywhere to play sound", 50, 150);
}
}
Applets on the same page can communicate:
// Sender Applet
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SenderApplet extends Applet implements ActionListener {
private TextField messageField;
private Button sendButton;
@Override
public void init() {
messageField = new TextField(20);
sendButton = new Button("Send to Other Applet");
sendButton.addActionListener(this);
add(new Label("Message: "));
add(messageField);
add(sendButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sendButton) {
String message = messageField.getText();
// Get the receiver applet from the same page
ReceiverApplet receiver = (ReceiverApplet)getAppletContext()
.getApplet("receiverApplet");
if (receiver != null) {
receiver.receiveMessage(message);
}
}
}
}
// Receiver Applet
import java.applet.Applet;
import java.awt.*;
public class ReceiverApplet extends Applet {
private String receivedMessage = "No message received yet";
@Override
public void init() {
setName("receiverApplet"); // Important for identification
}
public void receiveMessage(String message) {
receivedMessage = message;
repaint();
}
@Override
public void paint(Graphics g) {
g.drawString("Received: " + receivedMessage, 20, 50);
}
}
Understanding the applet life cycle in Java offers foundational insights into modern application design, especially in lifecycle management, resource handling, and platform-independent development.
Although applets are obsolete today, learning how they work helps developers appreciate Java’s evolution and better grasp UI frameworks like JavaFX and Swing. The principles behind initialization, rendering, pausing, and destruction continue to influence contemporary application architectures.
The main methods in the applet life cycle are init(), start(), paint(), stop(), and destroy(). These methods are called by the applet container at specific points during the applet's existence to initialize, start, display, pause, and clean up the applet, respectively.
The init() method is called only once when the applet is first loaded, making it suitable for one-time initialization tasks like setting up the UI and initializing variables. The start() method is called after init() and also whenever the applet becomes visible again after being hidden, making it appropriate for starting animations, threads, or other ongoing processes.
Yes, you can override any of the applet life cycle methods to implement custom behavior. However, it's important to call the superclass method (e.g., super.init()) if you want to preserve the default behavior before adding your own functionality.
If you don't override the paint() method, your applet won't display any custom graphics. The default implementation in the Applet class does nothing visible. For visual applets, overriding paint() is essential to draw text, shapes, or images.
The update() method is called before paint() and by default clears the screen before calling paint(). If you want to implement double-buffering or prevent flickering during animations, you might override update() to draw to an off-screen buffer first.
Parameters can be passed to an applet using the <param> tag within the <applet> tag in HTML. Inside the applet, you can retrieve these parameters using the getParameter(String name) method.
The stop() method is crucial for resource management. When a user navigates away from a page containing an applet, stop() allows you to pause animations, suspend threads, and conserve system resources. Without properly implementing stop(), an applet might continue consuming resources even when not visible.
Traditionally, applets were designed to run within a web browser or the appletviewer tool. However, you can convert an applet to run as a standalone application by embedding it in a JFrame, as shown in the "AppletToApplication" example earlier in this article.
You can debug applets by:
While both run on the client side, applets are embedded directly in web pages and run within a browser's JVM. Java Web Start applications launch outside the browser as standalone applications but are still deployed over the web. Java Web Start provides a fuller application experience while maintaining the web deployment model.
Java applets are largely obsolete for modern web development. Major browsers have discontinued support for the Java plugin, and Oracle has deprecated applets in Java 9 and removed them in Java 11. Modern alternatives include JavaScript, WebAssembly, or server-side Java with frameworks like Spring Boot or Jakarta EE.
For web-based applications, Java applets have been replaced by JavaScript frameworks, WebAssembly, and HTML5 technologies. For rich client applications, JavaFX is Oracle's recommended technology. For networked applications, technologies like Java Web Start (though also deprecated) and normal Java applications distributed through modern channels are used.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.