Java Applet Life Cycle: A Step-By-Step Guide


By NIIT Editorial

Published on 06/07/2023

Applets built in the Java programming language are tiny applications that may be placed in a web page to offer interactivity. Nevertheless, owing to security concerns and the broad use of alternative web technologies like HTML5 and JavaScript, the use of applets to add interactive content to web sites has dropped in recent years.

The life cycle of a Java applet includes the steps of being loaded, initialised, shown, and finally destroyed. There are four stages in an applet's life cycle that the browser or applet viewer will trigger: init(), start(), stop() and destroy()

The browser or applet viewer is responsible for calling these methods at the proper moments during the life cycle of a Java applet. To ensure that their code is correctly initialised and cleaned away, applet developers must be familiar with the life cycle.


 

Table of Contents

  • Initialization Phase 
  • Loading Phase 
  • Execution Phase 
  • Termination Phase 
  • Applet Life Cycle Methods 
  • Best Practices for Managing Applet Life Cycle 
  • Conclusion


 

Initialization Phase

The life cycle of a Java applet begins with its startup step. This phase lasts from the time the applet is loaded into memory until the init() function is invoked. Many smaller stages occur inside this larger one:

 

1. Loading the Applet Class

Any programme that can display applets will do so, loading the class file into memory. The class file for the applet is retrieved from the server or a local cache to do this.

 

2. Instantiating the Applet Object

The class file for the applet is used to instantiate the applet. The applet's function Object() { [native code] } is contacted to do this.

 

3. Setting Parameters

Any parameters supplied to the applet are determined by the browser or applet viewer. The param> elements in the HTML code that contains the applet are where these arguments will be provided.

 

4. Calling the init() Method

When the browser or applet viewer is ready, it will invoke the applet's init() function. At this phase, the applet initialises objects, creates data structures, and conducts any other preliminary activities that may be required.

Some possible samples of code to use during setup are shown below.

 

5. Loading the Applet Class

java

// Assuming the applet class is named "MyApplet"

URL appletURL = new URL(getDocumentBase(), "MyApplet.class");

InputStream classStream = appletURL.openStream();

byte[] classBytes = readBytes(classStream);

Class appletClass = defineClass("MyApplet", classBytes, 0, classBytes.length);

 

6. Instantiating the Applet Object

java

MyApplet applet = new MyApplet();

Setting Parameters:

html

<applet code="MyApplet.class" width="400" height="300">

  <param name="param1" value="value1">

  <param name="param2" value="value2">

</applet>

 

7. Calling the init() Method

java

public void init() {

  // Set up data structures and initialize objects

  String param1 = getParameter("param1");

  String param2 = getParameter("param2");

  // ...

}

The exact code used during the startup step may vary depending on the requirements of the applet, but they serve as samples.



 

Loading Phase

In the life cycle of a Java applet, the loading step comes second. After the init() function is invoked, the loading process starts and continues until the applet is ready to be shown. Many smaller stages occur inside this larger one:

 

1. Loading Resources

Images, audio, and configuration files might all be needed by the applet. Typically, the server or a local cache is used to provide these resources.

 

2. Verifying Security

The applet's source code is inspected for any security holes. This includes validating that the applet is not attempting to access resources or execute activities that it is not authorised to do, and confirming the digital signature of the applet if it has one.

 

3. Allocating Memory

Memory for the applet's programme and data structures is provided by the browser or applet viewer.

 

4. Starting Execution

The applet's code is finally run, starting with the start() function.

Several possible instances of loading-phase code are shown below:

 

  • Loading Resources:

java

// Load an image resource

URL imageURL = new URL(getDocumentBase(), "image.gif");

Image image = getImage(imageURL);

// Load a sound resource

URL soundURL = new URL(getDocumentBase(), "sound.wav");

AudioClip sound = getAudioClip(soundURL);

  • Verifying Security:

java

// Check if the applet is allowed to access the local file system

try {

  AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "read"));

} catch (SecurityException e) {

  System.err.println("Security Exception: " + e.getMessage());

  // handle the security violation

}

 

  • Allocating Memory: In most cases, the browser or applet viewer will take care of this automatically for you.

 

  • Starting Execution

java

public void start() {

  // Begin the applet's execution

  // ...

}

All of these are simply samples; the real code used by the applet during loading will be tailored to the demands of the application.

 


Execution Phase

The third stage of a Java applet's life cycle is the execution phase. It starts when the start() function is invoked and lasts until the user or the applet itself ends it. Many smaller stages occur inside this larger one:

 

1. Running Code

In reaction to certain conditions or actions, the applet's code is run.

2. Handling User Input

Input events like clicks, typed text, and touches may need to be processed by the applet.

 

3. Displaying Output

It's possible that the applet will need to show some kind of output to the user.

 

4. Managing State 

In other cases, like a game, the applet will need to maintain its own state, such as saving and loading user settings.

 

5. Cleaning Up

The applet may have unfinished business, such as releasing resources or storing data, that must be completed when it is terminated.

Some possible samples of executable code are shown below:

 

  • Running Code

java

// Example of running code in response to a button click

public void actionPerformed(ActionEvent e) {

  if (e.getSource() == myButton) {

    // Perform some action when the button is clicked

    // ...

  }

}

 

  • Handling User Input

java

// Example of handling mouse clicks

public void mouseClicked(MouseEvent e) {

  int x = e.getX();

  int y = e.getY();

  // Do something with the mouse coordinates

  // ...

}


 

  • Displaying Output:

java

// Example of drawing graphics

public void paint(Graphics g) {

  g.setColor(Color.RED);

  g.fillRect(10, 10, 50, 50);

  // ...

}

 

  • Managing State

java

// Example of managing state in a game

public void keyPressed(KeyEvent e) {

  int keyCode = e.getKeyCode();

  if (keyCode == KeyEvent.VK_LEFT) {

    // Move the player character to the left

    // ...

  }

}

 

  • Cleaning Up:

java

// Example of releasing resources when the applet is stopped

public void stop() {

  // Release any resources held by the applet, such as images or sounds

  // ...

}

 

These are only samples; the actual code used by the applet during operation will be tailored to its own requirements.

 


Termination Phase

The life cycle of a Java applet concludes with the termination step. The process starts when the applet is terminated, either manually by the user or automatically by the applet's code, and continues until all of the applet's resources have been freed and the applet has been deleted from memory. Many smaller stages occur inside this larger one:

 

1. Stopping Execution

java

// Example of stopping execution when a button is clicked

public void actionPerformed(ActionEvent e) {

  if (e.getSource() == myStopButton) {

    stop();

  }

}

 

2. Releasing Resources

java

// Example of releasing resources when the applet is stopped

public void stop() {

  // Release any resources held by the applet, such as images or sounds

  if (myImage != null) {

    myImage.flush();

    myImage = null;

  }

  if (mySound != null) {

    mySound.stop();

    mySound = null;

  }

  // ...

}

 

3. Finalization

java

// Example of finalization code

public void destroy() {

  // Perform any final cleanup tasks, such as closing open files

  if (myFileInputStream != null) {

    try {

      myFileInputStream.close();

    } catch (IOException e) {

      // handle the exception

    }

    myFileInputStream = null;

  }

  // ...

}

The actual code used during the termination phase will be tailored to the requirements of the applet, thus the samples given here should be taken with a grain of salt.

 

Applet Life Cycle Methods

The Java applet application programming interface provides four life cycle methods for controlling the lifetime of an applet. Some techniques include:

 

1. init()

This function is invoked when the applet is initially loaded into a browser, during the initialization process. Initialization procedures, such as loading resources and establishing data structures, are carried out via the init() method.

 

2. start()

This method is invoked after the init() function has been completed and the applet is prepared to execute. To initiate the execution of the applet's code, such as animation or game logic, the start() function is used.

 

3. stop()

When the user or the applet's code decides to terminate the applet, this function is invoked. To terminate an active programme and finish any unfinished business, the stop() function is used.

 

4. destroy()

This function is used just before an applet is deleted from memory. Final cleaning, such as freeing up system resources or shutting open files, is handled by using the destroy() function.

 

These procedures are called in the following order:

 

1. init()

This function is invoked first, just after the applet has been loaded.

2. start()

This function is invoked after init() has been completed and the applet is prepared to begin execution.

 

3. stop()

When the user or the applet's code decides to terminate the applet, this function is invoked.

4. destroy()

This function is used just before an applet is deleted from memory.

 

Several possible samples of code for each life cycle technique are shown below:

 

1. init()

java

public void init() {

  // Load any necessary resources, such as images or sounds

  myImage = getImage(getCodeBase(), "image.png");

  // ...

}

 

2. start()

java

public void start() {

  // Begin running any necessary code, such as game logic or animation

  myTimer = new Timer(1000 / 60, new ActionListener() {

    public void actionPerformed(ActionEvent e) {

      // Update the game state and render the graphics

      // ...

    }

  });

  myTimer.start();

}


 

3. stop()

java

public void stop() {

  // Stop any running code and perform any necessary cleanup tasks

  if (myTimer != null) {

    myTimer.stop();

    myTimer = null;

  }

  // ...

}

 

4. destroy()

java

public void destroy() {

  // Perform any final cleanup tasks, such as releasing system resources

  if (myFileInputStream != null) {

    try {

      myFileInputStream.close();

    } catch (IOException e) {

      // handle the exception

    }

    myFileInputStream = null;

  }

  // ...

}

These are only samples; the real code included in each life cycle technique will vary according to the requirements of the applet.
 

 

Best Practices for Managing Applet Life Cycle

Here are some best practices for managing applet life cycle:

 

1. Keep the init() Method Lightweight 

Only the most crucial initialization operations, such as loading resources or building up data structures, should be performed in the init() function. To prevent stalling the applet's startup, any time-consuming or resource-intensive processing should be done in the start() function.

 

2. Use the start() and stop() Methods to Manage Applet Resources 

The start() function should initiate the applet's required resources, such as timers and threads, and the stop() method should terminate them. When the applet is terminated or deleted, this ensures that all associated resources are correctly cleaned away.

 

3. Use the destroy() Method to Release Resources 

The destruct() function should be used to free up any file handles or network connections that the applet has opened. This guarantees that the applet releases resources when they are no longer in use and helps avoid resource leaks.

 

4. Avoid Using the show() and hide() Methods 

These techniques were formerly used to control the visibility of Java applets, but they have been phased out in favour of more modern approaches. Control visibility instead using the setVisible() function.

 

5. Debug with the Java Console

Applets may be debugged and error messages and stack traces can be seen in the Java Console. In the Advanced tab of the Java Control Panel, this feature may be activated.

Memory leaks, resource leaks, and unexpected behaviour as a result of incorrect setup or cleaning are all potential problems in the context of applet life cycle management. Some potential answers to these problems are as follows:

 

6. Use Try-Catch Blocks to Handle Exceptions

Applets are less likely to crash and exhibit unexpected behaviour if exceptions are handled correctly. If an error occurs when running the applet, be sure you catch and process it.

 

7. Use the finalize() Method to Release Resources

Resources may be freed in the finalise() function if they weren't correctly freed in the destroy() method. This method may or may not be called; nonetheless, it should not be depended upon as the only means of resource cleaning unless you know for sure that it will be invoked.

 

8. Use the Java VisualVM Tool to Monitor Applet Performance 

To track how well an applet is using its allotted resources and pinpoint any memory leaks, you may utilise Java VisualVM. Use it to keep tabs on how much time each thread spends running and how much memory it's using.

The Java Console may be used to examine error messages, logs can be used to monitor applet operation, and an IDE like Eclipse can be used for breakpoints and step-through debugging. To further assure compatibility, testing applets across several browsers and OSes is recommended.

 


Conclusion

The stages of an applet's life cycle in Java are, in order, startup, loading, execution, and shutdown. Within each stage, there are distinct actions to do, and they must be carried out in a specified sequence. To create effective and high-performing applets, knowing the phases of an applet's life cycle is crucial.

For effective resource use and the prevention of problems like memory leaks and unexpected behaviour, applet life cycle management is crucial. Applet developers may create high-quality applets that work reliably across browsers and operating systems by adhering to best practises and using debugging tools.

There is a need for qualified Java developers since Java is still extensively utilised in many sectors. Taking a Java developer course may help you become a Java developer or improve your current knowledge of Java applets and other Java technologies. To review, there are many stages in the Java applet life cycle: startup, loading, execution, and shutdown. There are distinct steps and procedures that must be carried out inside each phase. In order to create effective and high-performing applets, it is crucial to have a firm grasp of the applet life cycle.

For effective resource use and the prevention of problems like memory leaks and unexpected behaviour, applet life cycle management is crucial. Applet developers may create high-quality applets that work reliably across browsers and operating systems by adhering to best practises and using debugging tools.

The need for proficient Java developers persists as long as Java is a popular programming language. Attending a Java developer course may help you become a Java developer or improve your current knowledge of Java applets and other Java technologies.

 



Top