Java long questions
Java long questions
An applet is a small application written in Java, designed to be run in a web browser or an applet
viewer. It is embedded in an HTML page and executed by the Java Virtual Machine (JVM) in
the context of a browser.
Applet Lifecycle
The lifecycle of an applet includes the following methods, which are called in a specific
sequence:
1. init(): This method is called once when the applet is first loaded. It is used for
initialization.
2. start(): This method is called after init(), and every time the applet is revisited in the
browser. It is used to start or resume the applet’s execution.
3. stop(): This method is called when the applet is no longer visible or the user navigates
away. It is used to stop any processing started by start().
4. destroy(): This method is called when the applet is being destroyed, such as when the
browser is closed. It is used to clean up resources before the applet is removed from
memory.
5. paint(Graphics g): This method is called whenever the applet needs to redraw its output.
It is often used to render the applet’s graphics.
import java.applet.Applet;
import java.awt.Graphics;
<html>
<body>
<applet code="SimpleApplet.class" width="300" height="300">
</applet>
</body>
</html>
Exception in Java
An exception in Java is an event that disrupts the normal flow of the program’s instructions
during execution. It is an object that is thrown at runtime when an error or other unusual
condition occurs.
Java provides a powerful mechanism for handling exceptions using a combination of try, catch,
finally, throw, and throws keywords.
1. try block: Code that might throw an exception is placed inside a try block.
2. catch block: Code to handle the exception is placed inside a catch block. It catches
exceptions of a specific type.
3. finally block: Code that is always executed, regardless of whether an exception is thrown
or not. It is typically used for cleanup activities.
4. throw statement: Used to explicitly throw an exception.
5. throws keyword: Used in a method signature to declare the types of exceptions that the
method might throw.
Example of Exception Handling
java
Copy code
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
In this example: