Applet in Java Program: Step-by-Step Guide with Code and Explanation

Java has been one of the most widely used programming languages for building robust, secure, and platform-independent applications. Among the many features that helped Java rise in popularity during its early years, applets were one of the most innovative. They allowed developers to create small, dynamic programs that could run inside a web browser, adding interactivity and multimedia support to websites. While applets are largely obsolete today due to security and compatibility issues, they remain an essential topic for understanding the history of Java and its client-side execution capabilities.

We will explore what an applet is, how it works, its structure, and how to create and run simple examples. By examining these basics, you will gain a solid understanding of the foundation on which applets were built.

What is an Applet in Java

An applet in Java is a small application that runs within the context of a web browser or an applet viewer. Unlike standalone applications, which are executed directly on the operating system, applets are executed on the client side inside a controlled environment. They are embedded into HTML pages and downloaded from a web server to the user’s browser.

The concept of applets was designed to provide an easy way to create interactive features on websites at a time when web pages were mostly static. Using Java applets, developers could add animations, graphics, calculations, forms, or even games directly into a webpage.

Some key characteristics of Java applets are:

  • They are written in Java and executed by the Java Virtual Machine (JVM) within the browser.

  • They have access to the Java API, which makes them as powerful as standalone applications.

  • They run in a sandbox environment that restricts access to system resources, enhancing security.

  • They provide client-side execution, reducing the server’s workload and improving user interaction.

Even though applets are not supported by modern browsers like Chrome, Firefox, and Edge, the concepts are still useful to understand because they shaped the way Java approached graphical programming and client-side execution.

Basic Structure of an Applet Program

An applet in Java is created by extending the Applet class, which is part of the java.applet package. Additionally, graphical output and interaction are usually handled using the classes of the java.awt package.

The general structure of an applet includes:

  • Importing the necessary packages.

  • Extending the Applet class.

  • Overriding the paint method to display content on the applet window.

  • Optionally overriding lifecycle methods like init, start, stop, and destroy.

In this program:

  • The class MyApplet extends the Applet class.

  • The paint method is overridden to draw text on the applet window.

  • The Graphics object g is used to display text, images, and shapes.

Steps to Compile and Run an Applet

Since applets are not standalone applications, running them requires a slightly different approach compared to normal Java programs. The following steps outline the process:

Step 1: Write and Save the Java File

Save the code in a file with the same name as the class. For the example above, the file should be saved as HelloWorldApplet.java.

Step 2: Compile the Code

Use the javac compiler to compile the Java file:

javac HelloWorldApplet.java

 

This generates a bytecode file HelloWorldApplet.class.

Step 3: Create an HTML File to Embed the Applet

To run the applet in a browser or applet viewer, you must embed it inside an HTML file:

<!DOCTYPE html>

<html>

<head>

    <title>HelloWorld Applet</title>

</head>

<body>

    <applet code=”HelloWorldApplet.class” width=”300″ height=”200″></applet>

</body>

</html>

The applet tag specifies the compiled class file along with the width and height of the applet display area.

Step 4: Run the Applet

You can run the applet in two ways:

  • By opening the HTML file in a Java-enabled browser.

  • By using the appletviewer tool provided with the JDK:

appletviewer HelloWorldApplet.html

When executed, the applet displays the text message on the window.

Limitations of Running Applets Today

In the early years of Java, applets were a breakthrough technology. However, over time they became less popular due to several reasons:

  • Modern browsers such as Chrome, Firefox, and Edge no longer support Java plug-ins.

  • Security concerns made it risky to allow arbitrary code to run on client machines.

  • Alternative technologies like JavaScript, HTML5, and CSS offered more secure and flexible solutions for interactivity.

For this reason, applets are now primarily studied for educational purposes rather than practical development. However, the knowledge of how they work is still useful for students of Java.

How Applets Differ from Standalone Applications

Standalone Java applications are executed directly by the Java Virtual Machine from the command line or within an integrated development environment. They usually include a main method, which serves as the entry point for the program.

Applets, in contrast, do not have a main method. Instead, their lifecycle is managed by the browser or applet viewer. The browser invokes specific methods such as init, start, stop, and destroy at appropriate times.

Another difference is that standalone applications can freely access system resources such as files or local storage, whereas applets are confined to a restricted environment known as the sandbox. This limitation is designed to protect the client machine from malicious code.

Drawing and Graphics in Applets

One of the strengths of Java applets was their ability to use the Graphics class for drawing shapes, text, and images on the screen. This made it possible to create interactive games, animations, and visualizations.

This applet demonstrates:

  • Drawing rectangles, ovals, and lines.

  • Changing colors using the setColor method.

Such features were widely used to build graphical interfaces and educational tools during the time when applets were popular.

Using Parameters with Applets

Applets can accept parameters from the embedding HTML page using the param tag. These values can then be retrieved in the Java code using the getParameter method.

Common Applications of Applets in Early Web Development

Before modern frameworks and technologies became dominant, applets were frequently used for:

  • Creating interactive data visualizations.

  • Building educational tools with animations and graphics.

  • Developing small browser-based games.

  • Providing form validation and client-side calculations.

  • Embedding multimedia content like sound or images within web pages.

Although these tasks are now handled by technologies such as JavaScript and HTML5, the ideas behind applets still reflect the demand for interactive and dynamic content on the web.

Understanding the Applet Life Cycle

An applet does not start execution from a main method. Instead, it is controlled by the browser or the applet viewer, which manages its lifecycle. The lifecycle of an applet refers to the different stages it passes through from the moment it is loaded until it is destroyed.

Each stage is represented by a specific method in the Applet class. Developers can override these methods to customize the applet’s behavior at different points. The main stages of the applet lifecycle are initialization, starting, running, stopping, and destruction.

Initialization Stage

The initialization stage is the first step in the lifecycle. It occurs when the browser or applet viewer loads the applet for the first time.

  • The applet’s class is loaded by the Java Virtual Machine.

  • The init method is called once during the lifecycle of the applet.

  • Developers use this stage to set up resources, initialize variables, or load data required for later stages.

Starting Stage

After initialization, the applet enters the starting stage. The start method is invoked to indicate that the applet should begin or resume execution.

  • The start method is called each time the user visits the page containing the applet.

  • If the user navigates away from the page and later returns, the start method is called again.

  • This stage is typically used to start animations, threads, or continuous activities.

Running Stage

The running stage is the period during which the applet is actively displayed on the screen and can interact with users. In this stage, the applet continues to process events, handle user input, and update its display when necessary.

While there is no specific method called running, the applet remains in this state until the stop method is called. Developers often use paint or repaint methods to refresh the applet’s appearance during this phase.

Stopping Stage

The stopping stage occurs when the applet is no longer visible to the user, such as when they navigate away from the page.

  • The stop method is called automatically by the browser.

  • It is used to pause background tasks, stop animations, or release temporary resources.

  • If the user revisits the page, the start method is called again to resume execution.

Destroying Stage

The final stage of the applet lifecycle is destruction. This occurs when the applet is about to be unloaded from memory.

  • The destroy method is called only once during the lifecycle of the applet.

  • Developers use this method to perform final cleanup, such as closing files or releasing system resources.

Key Methods in Applet Programming

The Applet class provides several methods that developers can override. The most commonly used ones include:

  • init: Called once when the applet is loaded.

  • start: Called every time the applet becomes active.

  • stop: Called when the applet is not visible.

  • destroy: Called once before the applet is removed from memory.

  • paint: Called to draw content on the screen.

  • getParameter: Retrieves parameter values from the HTML file.

Each method serves a unique purpose, and together they define the structure and behavior of an applet.

Types of Applets in Java

Applets can be categorized based on how and where they are stored and executed. There are two main types of applets: local applets and remote applets.

Local Applets

A local applet is stored on the user’s computer and not downloaded from a web server.

  • It is loaded directly from the local machine into the browser or applet viewer.

  • Since it is stored locally, it is generally considered more secure and runs faster.

  • Local applets are often used for testing or demonstration purposes.

Remote Applets

A remote applet is stored on a server and downloaded by the browser when the webpage is loaded.

  • It is accessed through a URL specified in the HTML page.

  • Remote applets are more flexible because they can be updated on the server and automatically delivered to users.

  • However, they are subject to stricter security restrictions to prevent malicious code execution.

Comparing Local and Remote Applets

While both types of applets share the same structure, they differ in execution context and security handling.

  • Local applets are more trusted because they originate from the user’s own machine.

  • Remote applets are downloaded from the internet and therefore face limitations on what they can access.

  • Performance is often better for local applets since they do not require network transfers.

  • Remote applets are more portable and can be accessed from anywhere with an internet connection.

Practical Uses of Applet Types

In practice, local applets were mostly used during development or for offline applications, while remote applets were used in web applications to provide interactive content. Examples included online calculators, data visualization tools, and small browser-based games.

Although these functions are now handled by other technologies, the distinction between local and remote applets highlights the flexibility of the Java applet model.

Architecture of Java Applets

An applet is not just a small program but a component that integrates into a larger environment such as a browser or the applet viewer. The architecture of applets is designed to provide a controlled execution environment, enforce security, and enable interaction with users through graphical interfaces.

The major components of applet architecture are the applet class, the Java Virtual Machine, the browser or applet viewer, the Abstract Window Toolkit, and the security manager.

Applet Class

At the heart of the architecture lies the Applet class, which is part of the java.applet package. All applets must extend this class to function properly. The Applet class provides default implementations of lifecycle methods such as init, start, stop, and destroy. Developers override these methods to customize behavior.

Without extending this base class, a program cannot function as an applet because the browser or viewer relies on these predefined hooks to control execution.

Java Virtual Machine

The execution of an applet depends on the Java Virtual Machine. The JVM is responsible for interpreting the compiled bytecode and providing a runtime environment. It ensures portability, which means an applet written once can run on any system with a JVM, regardless of operating system or hardware.

This architectural design was one of the reasons applets gained popularity in the 1990s. By embedding the JVM into a browser, applets could run interactively across multiple platforms without requiring developers to rewrite code for each system.

Browser or Applet Viewer

Applets do not run independently like regular Java applications. Instead, they are embedded in web pages and displayed by browsers or special tools such as appletviewer. The browser or viewer loads the applet’s class file, initializes it, and then manages the lifecycle events.

The interaction between the browser and the applet is governed by the HTML page that contains the applet tag or object tag. Through this embedding, parameters can be passed to the applet, making it flexible and adaptable to different contexts.

Abstract Window Toolkit

The Abstract Window Toolkit (AWT) plays a key role in applet architecture by providing a set of classes for building graphical user interfaces. Applets often rely on AWT to create windows, draw graphics, and handle user input.

The Graphics class in AWT is especially important, as it allows developers to draw shapes, text, and images directly on the applet’s surface. Event handling mechanisms in AWT also enable applets to respond to user actions such as mouse clicks and key presses.

Security Manager

Security was a central consideration in the architecture of applets. Since remote applets were downloaded from servers, they could not be trusted to access local resources without restrictions. The security manager enforced strict rules that prevented applets from:

  • Reading or writing files on the local system.

  • Accessing system properties beyond a limited set.

  • Establishing arbitrary network connections.

This sandbox model ensured that applets could provide interactivity while minimizing risks to the user’s system.

Event Handling in Applets

One of the most powerful features of applets was their ability to handle events, making them interactive and responsive to user actions. Event handling in Java applets is based on the delegation event model introduced with the Abstract Window Toolkit.

This model separates event generation from event handling, creating a clean and modular way to manage user interactions.

Delegation Event Model

The delegation event model is based on three main components:

  • Event source – The object that generates an event, such as a button or text field.

  • Event object – An instance of a class that encapsulates details about the event, such as the type of event and its source.

  • Event listener – An object that receives the event and defines how it should be handled.

This separation allows multiple listeners to respond to the same event and keeps the code modular.

Handling Mouse Events

Mouse interactions are among the most common events in applets. By implementing interfaces such as MouseListener or MouseMotionListener, applets can respond to actions like clicking, pressing, releasing, entering, and exiting a component.

Handling Keyboard Events

Keyboard input is another common form of interaction in applets. By implementing the KeyListener interface, applets can respond to key presses, releases, and typing actions.

Action Events with Buttons

Applets can also include graphical components such as buttons. When a button is pressed, an ActionEvent is generated and passed to the corresponding listener.

Combining Events in Applets

A single applet can handle multiple types of events, making it highly interactive. Developers often combined mouse, keyboard, and action events to create rich user interfaces.

For instance, an educational applet might allow a user to press a button to start a quiz, use the keyboard to answer questions, and interact with graphics using the mouse. This level of interactivity was one of the reasons applets gained popularity in early online learning and visualization platforms.

Limitations of Event Handling in Applets

While event handling in applets was powerful, it also came with limitations.

  • Complex event-driven programs could become difficult to manage if not structured properly.

  • The reliance on AWT restricted the visual appearance of applets compared to modern UI frameworks.

  • Security restrictions sometimes limited the ability of applets to fully interact with local hardware or system events.

Despite these limitations, the delegation event model introduced in applets was a significant step forward and influenced later frameworks such as Swing and JavaFX.

Modern Relevance of Applet Architecture

Although applets themselves are now obsolete, the principles behind their architecture remain important for modern programming. Understanding applet architecture helps developers appreciate the evolution of Java and how certain ideas persist in newer frameworks.

Influence on Swing and JavaFX

The event handling model introduced in applets became the foundation for Swing and JavaFX, which continue to use similar patterns for responding to user input. The separation of event sources, objects, and listeners has become a standard practice in Java GUI development.

Lessons from Applet Security

The sandbox model used in applets laid the groundwork for modern security practices in Java. Today, Java applications still use security managers, permissions, and restricted execution environments to protect users from untrusted code.

Relevance in Modular Design

Applet architecture emphasized modularity, where small components could be embedded in larger systems. This idea has carried forward into modern software design, particularly in the use of reusable components in web frameworks and modular Java applications.

Continued Educational Value

Although developers no longer build new applets, learning about their architecture and event handling continues to provide educational value. It helps students and professionals understand how Java evolved, how GUI programming works, and why modular, secure design is essential in software development.

The Decline of Applets

Despite their early success, applets gradually fell out of favor. Several factors contributed to their decline.

Browser Compatibility Issues

Initially, many browsers integrated JVM support directly, making applets easy to run. Over time, however, maintaining this integration became difficult. Users often encountered compatibility issues, mismatched JVM versions, or missing plugins. The reliance on the Java plugin became a major barrier to seamless execution.

Security Concerns

Applets operated in a restricted environment, but vulnerabilities were frequently discovered in the Java plugin. Exploits allowed malicious applets to bypass sandbox restrictions, which damaged trust among users and organizations. Browser vendors responded by phasing out plugin support, ultimately eliminating the environment where applets thrived.

Performance Limitations

Running applets required downloading class files and initializing the JVM, which slowed startup times compared to lightweight alternatives like JavaScript. Users demanded faster, smoother experiences, and applets could not keep up with evolving expectations.

Emergence of Alternatives

As technologies like JavaScript, Flash, and later HTML5 emerged, they provided faster and more flexible ways to create interactive web applications without relying on external plugins. This shift significantly reduced the role of applets in web development.

Rise of Swing as a Replacement

As applets lost relevance, Java introduced Swing, a lightweight GUI toolkit built on top of the Abstract Window Toolkit. Swing became the primary framework for building desktop applications in Java.

Features of Swing

Swing offered several advantages over applets and AWT.

  • Lightweight components: Unlike AWT, which relied on native operating system components, Swing components were written entirely in Java, ensuring consistency across platforms.

  • Rich UI elements: Swing provided a wide range of components such as tables, trees, text panes, and tabbed panels, allowing developers to build complex interfaces.

  • Pluggable look and feel: Developers could customize the appearance of applications without changing underlying code.

  • Event-driven programming: Building on the delegation event model, Swing refined event handling to support more sophisticated user interactions.

JavaFX: A Modern Approach to GUI Programming

While Swing remained popular for many years, JavaFX emerged as a modern alternative. JavaFX addressed many limitations of Swing and offered a richer set of tools for developing interactive applications.

Features of JavaFX

  • Declarative UI design: JavaFX supports FXML, an XML-based language that allows developers to design interfaces separately from application logic.

  • Rich multimedia support: JavaFX includes built-in capabilities for audio, video, and animations, making it ideal for multimedia applications.

  • CSS styling: Developers can apply CSS to style JavaFX applications, similar to how web applications are styled.

  • Hardware acceleration: JavaFX leverages modern graphics hardware for smoother rendering.

  • Scene graph model: Instead of using traditional containers, JavaFX organizes UI elements into a hierarchical scene graph, improving flexibility and performance.

Lessons Carried Forward from Applets

Even though applets disappeared, many of the concepts introduced by their architecture influenced future frameworks and technologies.

Lifecycle Management

Applets introduced a structured lifecycle with methods such as init, start, stop, and destroy. Similar lifecycle concepts appear in Swing, JavaFX, and even modern web frameworks like React and Angular. These structures help manage resources, initialize components, and ensure proper cleanup.

Event Handling

The delegation event model pioneered in applets became a standard for handling user interactions across GUI frameworks. Today, JavaFX and Swing still use event listeners and event objects, and the same principles are applied in JavaScript frameworks.

Component-Based Architecture

Applets emphasized modular design, where small, reusable components could be embedded into larger systems. This idea foreshadowed modern component-based architectures seen in React, Vue, and Angular.

Security Awareness

The sandbox model of applets highlighted the importance of restricting untrusted code. Modern programming environments, from Java applications to web browsers, continue to rely on strict permissions and security policies inspired by these early lessons.

Transition to Web Technologies

While Swing and JavaFX became the successors to applets for desktop applications, web development followed a different path.

Rise of JavaScript

JavaScript became the dominant language for client-side interactivity in browsers. Its lightweight nature, ease of integration with HTML and CSS, and absence of plugins made it the natural choice for interactive web applications.

Over time, JavaScript evolved from simple scripting to a robust language with support for object-oriented and functional programming. Libraries such as jQuery simplified DOM manipulation, while frameworks like Angular, React, and Vue introduced structured approaches to building large-scale applications.

HTML5 and CSS3

HTML5 and CSS3 provided native support for multimedia, graphics, and animations, eliminating the need for plugins like Java applets or Flash. Features such as the canvas element and WebGL brought rich graphical capabilities directly into browsers.

WebAssembly

WebAssembly has recently extended the possibilities of client-side development by allowing code written in languages like C, C++, and Rust to run in browsers. This new technology further ensures performance and portability, echoing the original vision of Java applets but without their limitations.

Comparing Applets with Modern Frameworks

The shift from applets to modern frameworks highlights how technology evolves while retaining core principles.

Execution Environment

  • Applets required a JVM plugin in browsers.

  • Modern frameworks run natively in browsers without plugins, relying on HTML, CSS, and JavaScript.

Security

  • Applets enforced a sandbox model, but vulnerabilities made them risky.

  • Modern browsers implement same-origin policies, content security policies, and sandboxing to protect users.

Performance

  • Applets suffered from slow startup due to JVM initialization.

  • Modern frameworks load quickly, with advanced optimizations like lazy loading and tree shaking.

Developer Experience

  • Applets required Java knowledge and HTML integration.

  • Modern frameworks offer powerful developer tools, modular structures, and large ecosystems.

Educational Value of Learning Applets Today

Although obsolete, applets retain educational significance. For students and professionals, understanding applets helps in the following ways:

  • Grasping the fundamentals of event-driven programming.

  • Appreciating the evolution of Java’s GUI frameworks.

  • Understanding how security concerns influence design.

  • Learning about modular design and lifecycle management.

These lessons remain valuable in modern contexts such as building JavaFX applications or developing web applications with JavaScript frameworks.

Conclusion

The journey of applets in Java reflects both the promise and limitations of early client-side technologies. When they were first introduced, applets brought interactivity, modularity, and graphics into web pages at a time when most online experiences were limited to static text and images. Their ability to run code inside browsers gave developers the freedom to create animations, visualizations, and interactive tools that shaped the early web.

Over time, however, challenges such as browser incompatibility, security vulnerabilities, and performance bottlenecks gradually diminished the role of applets. Modern browsers eventually removed support, replacing the plugin-based approach with safer, more efficient, and open standards such as JavaScript, HTML5, and CSS3. While applets themselves are no longer relevant in practical development, they left a legacy that continues to shape how programmers think about lifecycle management, event handling, and component-based design.

The transition from applets to frameworks like Swing and JavaFX shows the natural evolution of Java’s approach to building user interfaces. Concepts first introduced in applets, such as structured lifecycle methods and reusable components, matured into more robust models for desktop and multimedia applications. At the same time, web technologies moved toward lightweight, native solutions that no longer depend on external plugins.

Studying applets today is not about bringing them back into modern software development but about appreciating their role as a stepping stone in the history of programming. They provide valuable lessons in understanding how interactive systems are built, how security and performance considerations shape technology adoption, and how ideas can evolve across generations of tools. Whether one is learning JavaFX, Swing, or modern web frameworks, the principles that originated in applets remain relevant for designing responsive, secure, and user-friendly applications.