0% found this document useful (0 votes)
31 views

JAVA Long Q&A

Java is a high-level, object-oriented, and platform-independent programming language developed by Sun Microsystems in 1995, known for its Write Once, Run Anywhere capability. It features simplicity, portability, security, and robustness, and supports various application types including standalone, web, enterprise, and mobile applications. Key components of Java include the JVM for executing bytecode, the JRE for running Java programs, and the JDK for development, with a compilation process that converts source code into bytecode for execution.

Uploaded by

manthan7114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

JAVA Long Q&A

Java is a high-level, object-oriented, and platform-independent programming language developed by Sun Microsystems in 1995, known for its Write Once, Run Anywhere capability. It features simplicity, portability, security, and robustness, and supports various application types including standalone, web, enterprise, and mobile applications. Key components of Java include the JVM for executing bytecode, the JRE for running Java programs, and the JDK for development, with a compilation process that converts source code into bytecode for execution.

Uploaded by

manthan7114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

1. Explain the history and features of Java in detail.

Answer:
Java is a high-level, object-oriented, and platform-independent programming language developed
by James Gosling at Sun Microsystems in 1995. It was initially called Oak, but due to trademark
issues, the name was changed to Java.
Java gained popularity due to its Write Once, Run Anywhere (WORA) capability, meaning that
Java programs can be executed on any platform that has a Java Virtual Machine (JVM).

Features of Java (Java Buzzwords)


1. Simple – Java is designed to be easy to learn, with syntax similar to C++ but without
complex features like pointers and operator overloading.
2. Object-Oriented – Everything in Java is based on classes and objects.
3. Portable – Java applications can be moved from one system to another without
modification.
4. Platform-Independent – Java code is compiled into bytecode, which can be executed on
any system with a JVM.
5. Secured – Java provides built-in security mechanisms like the bytecode verifier,
classloader, and security manager.
6. Robust – Java handles memory management and exceptions efficiently.
7. Multithreaded – Java allows multiple threads to run simultaneously, improving
performance.
8. High-Performance – Though Java is slower than C++, Just-In-Time (JIT) compiler
improves performance.
9. Distributed – Java supports networking and remote method invocation (RMI).
10.Dynamic – Java supports dynamic loading of classes at runtime.

2. What are the different types of Java applications? Explain each type with
examples.
Answer:
Java is used to develop different types of applications, which can be categorized into four main
types:
1. Standalone Applications (Desktop Applications)
• These are traditional software applications installed on a computer.
• Example: Media Players (VLC), Antivirus Software, Microsoft Word.
• Java technologies: AWT, Swing, JavaFX.
2. Web Applications
• These applications run on web servers and generate dynamic web pages.
• Example: Online banking systems, e-commerce websites (Amazon, Flipkart).
• Java technologies: Servlets, JSP, Spring, Hibernate, JSF.
3. Enterprise Applications
• Large-scale applications that require high security, load balancing, and transaction
management.
• Example: Banking applications, stock management systems.
• Java technologies: Enterprise JavaBeans (EJB), JPA, Spring Boot.
4. Mobile Applications
• Applications designed for mobile devices, such as Android apps.
• Example: WhatsApp, Instagram (Android applications).
• Java technologies: Java ME, Android SDK.

3. What is JVM, JRE, and JDK? Explain their roles in Java programming.
Answer:
Java programs rely on three key components:
1. JVM (Java Virtual Machine)
• The JVM is responsible for executing Java bytecode.
• It provides features like garbage collection, memory management, and security.
• Different operating systems have their own versions of JVM.
2. JRE (Java Runtime Environment)
• JRE includes the JVM, Java class libraries, and supporting files needed to run
Java programs.
• It does not include development tools like compilers.
3. JDK (Java Development Kit)
• JDK includes JRE and additional tools like the Java compiler (javac), debugger,
and documentation generator.
• It is required for developing and compiling Java applications.

4. Explain the Java compilation and execution process.


Answer:
The compilation and execution process in Java involves multiple steps:
1. Writing the Code:
• Create a Java source file (.java extension).
• Example:
class Simple {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}

2. Compilation:
• Use the javac command to compile the file:
javac Simple.java

• This converts the source code into bytecode (.class file).


3. Execution:
• Use the java command to run the program:
java Simple

• The JVM loads the bytecode and executes it.

5. What is the difference between Java and C++?


Answer:
Feature C++ Java
Platform Dependency Platform-dependent Platform-independent (WORA)
Memory
Uses pointers No pointers, automatic garbage collection
Management
Multiple Inheritance Supported Not supported (Achieved using interfaces)
Operator
Supported Not supported
Overloading
Thread Support Requires external libraries Built-in thread support
Compiled into machine Compiled into bytecode and interpreted by
Compilation
code JVM
Exception Handling Optional Built-in exception handling

6. What are the different types of variables in Java? Explain with examples.
Answer:
Java has three types of variables:
1. Local Variables
• Declared inside a method and accessible only within that method.
• Example:
public class Example {
public void display() {
int age = 25; // Local variable
System.out.println(age);
}
}

2. Instance Variables
• Declared inside a class but outside any method.
• Each object has its own copy of instance variables.
• Example:
class Student {
String name; // Instance variable
}

3. Static Variables
• Declared using the static keyword and shared among all objects of the class.
• Example:
class Employee {
static String company = "TechCorp"; // Static variable
}

7. What are the different data types in Java? Explain each with an example.
Answer:
Java has two types of data types:
1. Primitive Data Types (8 types)
• byte (1 byte): byte b = 127;
• short (2 bytes): short s = 32767;
• int (4 bytes): int i = 100000;
• long (8 bytes): long l = 100000000L;
• float (4 bytes): float f = 10.5f;
• double (8 bytes): double d = 99.99;
• char (2 bytes): char c = 'A';
• boolean (1 bit): boolean isJavaFun = true;
2. Non-Primitive Data Types
• Strings, Arrays, Classes, Interfaces
• Example:
String name = "Java";
int[] numbers = {1, 2, 3};
1. Explain the features of Java in detail.
Answer:
Java is a powerful and versatile programming language that offers several key features:
1. Object-Oriented:
• Java follows the Object-Oriented Programming (OOP) paradigm, which means
everything in Java is treated as an object.
• Key OOP principles include Encapsulation, Inheritance, Polymorphism, and
Abstraction.
2. Platform-Independent:
• Java follows the "Write Once, Run Anywhere" (WORA) principle.
• Java programs are compiled into bytecode, which can be executed on any system
that has a Java Virtual Machine (JVM).
3. Simple and Easy to Learn:
• Java has a simple syntax similar to C++ but without complexities like multiple
inheritance and pointers.
4. Robust and Secure:
• Java provides strong memory management.
• It prevents issues like memory leaks by using automatic garbage collection.
• Security features include runtime verification and bytecode verification.
5. Multithreading:
• Java supports multithreading, allowing multiple tasks to run simultaneously,
improving performance and efficiency.
6. High Performance:
• Though Java is an interpreted language, it provides high performance using Just-In-
Time (JIT) compilation.
7. Distributed Computing:
• Java supports networking and remote method invocation (RMI), making it suitable
for distributed applications.
8. Dynamic and Extensible:
• Java supports dynamic loading of classes and integrates seamlessly with external
libraries.

2. What is an object in Java? Explain with an example.


Answer:
An object in Java is an entity that has state (attributes) and behavior (methods). It is an instance of
a class.
• State: The data stored in the object (e.g., name, age).
• Behavior: The actions that the object can perform (e.g., writing, walking).
• Identity: The unique reference assigned by the JVM.

Example:
class Car {
String brand;
int speed;

void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}

public static void main(String args[]) {


Car myCar = new Car();
myCar.brand = "Toyota";
myCar.speed = 80;
myCar.drive();
}
}

Output:
Toyota is driving at 80 km/h

Here, myCar is an object of the Car class.

3. Explain classes and objects in Java with an example.


Answer:
A class is a blueprint from which objects are created. It defines the properties (variables) and
behaviors (methods) that an object can have.
• Class: Defines attributes and methods.
• Object: An instance of a class with actual values assigned.

Example:
class Student {
int id;
String name;

void display() {
System.out.println("ID: " + id + ", Name: " + name);
}

public static void main(String args[]) {


Student s1 = new Student();
s1.id = 101;
s1.name = "John Doe";
s1.display();
}
}

Output:
ID: 101, Name: John Doe
Here:
• Student is a class.
• s1 is an object of the Student class.

4. What are constructors in Java? Explain with an example.


Answer:
A constructor is a special method that is used to initialize objects. It has the same name as the class
and does not have a return type.

Types of Constructors:
1. Default Constructor: Does not take any parameters.
2. Parameterized Constructor: Takes parameters to initialize the object with values.

Example of Default Constructor:


class Bike {
Bike() {
System.out.println("Bike is created");
}

public static void main(String args[]) {


Bike b1 = new Bike(); // Constructor is automatically called
}
}

Output:
Bike is created

Example of Parameterized Constructor:


class Employee {
int id;
String name;

// Parameterized Constructor
Employee(int empId, String empName) {
id = empId;
name = empName;
}

void display() {
System.out.println("ID: " + id + ", Name: " + name);
}

public static void main(String args[]) {


Employee e1 = new Employee(101, "Alice");
e1.display();
}
}

Output:
ID: 101, Name: Alice
5. Explain the concept of method overloading with an example.
Answer:
Method Overloading is when multiple methods in a class have the same name but different
parameters (number, type, or order).

Example of Method Overloading:


class MathOperations {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}

public static void main(String args[]) {


MathOperations obj = new MathOperations();
System.out.println(obj.add(10, 20)); // Calls method with 2
parameters
System.out.println(obj.add(10, 20, 30)); // Calls method with 3
parameters
}
}

Output:
30
60

• The compiler determines which method to call based on method signatures.


• Method Overloading is an example of Compile-Time Polymorphism.

6. What is method overriding in Java? Explain with an example.


Answer:
Method Overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its parent class.
• The method in the child class must have the same name and parameters as the parent
class.
• Method Overriding is an example of Runtime Polymorphism.

Example of Method Overriding:


class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Dog barks");
}

public static void main(String args[]) {


Dog d = new Dog();
d.makeSound(); // Calls the overridden method in Dog class
}
}

Output:
Dog barks

• Here, makeSound() is overridden in the Dog class.

7. Explain the differences between method overloading and method overriding.


Feature Method Overloading Method Overriding
Multiple methods with the same name
A child class redefines a method from
Definition
but different parameters the parent class
Parameters Must be different Must be the same
Return Type Can be different Must be the same
Cannot be more restrictive than
Access Modifier Can be different
parent method
add(int a, int b), add(float makeSound() in Animal vs.
Example
a, float b) makeSound() in Dog
Type of
Compile-Time Polymorphism Runtime Polymorphism
Polymorphism
1. Explain the concept of String in Java. How is a String created in Java?
Answer:
In Java, a String is an object that represents a sequence of characters. Unlike primitive data types,
Strings in Java are immutable, meaning once created, they cannot be changed. The
java.lang.String class is used to create and manipulate strings in Java.

Ways to Create a String in Java:


1. Using String Literal
String s = "Hello";

• This method stores the string in a String Constant Pool to save memory.
• If the string already exists in the pool, Java returns a reference to the existing object
instead of creating a new one.
2. Using the new Keyword
String s = new String("Hello");

• This method creates a new string object in heap memory, even if the same string
exists in the String Constant Pool.

Example:
public class StringExample {
public static void main(String[] args) {
String s1 = "Java"; // String literal
String s2 = new String("Java"); // Using new keyword
System.out.println(s1);
System.out.println(s2);
}
}

2. Why is the String class in Java immutable? What are the advantages of
immutability?
Answer:
The String class in Java is immutable, meaning once a String object is created, its value cannot be
changed. If any modification is made, a new object is created instead of altering the original one.

Reasons why Java Strings are Immutable:


1. Memory Efficiency:
• Java maintains a String Constant Pool where it stores string literals.
• If a string is modified, a new object is created instead of modifying the existing one,
preventing unwanted changes in shared references.
2. Security:
• Strings are used for storing sensitive data like usernames, passwords, and database
connections.
• Immutability ensures that a malicious code cannot alter these values during
execution.
3. Thread Safety:
• Since Strings are immutable, they can be shared among multiple threads without
causing concurrency issues.
• This makes them safe for multi-threaded applications.
4. Performance Optimization:
• Java optimizes string handling using String interning, reducing memory
consumption.

Example:
public class ImmutableStringExample {
public static void main(String args[]) {
String s = "Hello";
s.concat(" World");
System.out.println(s); // Output: Hello (original string remains
unchanged)
}
}

3. What are the main methods of the String class in Java? Explain with
examples.
Answer:
Java provides various String methods to manipulate and retrieve information from strings.

Some commonly used String methods:


1. length() - Returns the length of the string
String s = "Java";
System.out.println(s.length()); // Output: 4

2. charAt(int index) - Returns the character at a specific index


String s = "Hello";
System.out.println(s.charAt(1)); // Output: e

3. concat(String str) - Concatenates two strings


String s1 = "Hello";
String s2 = s1.concat(" World");
System.out.println(s2); // Output: Hello World

4. equals(Object obj) - Compares two strings (case-sensitive)


String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2)); // Output: true
5. indexOf(String str) - Finds the index of the first occurrence of a substring
String s = "Java Programming";
System.out.println(s.indexOf("Programming")); // Output: 5

6. substring(int start, int end) - Extracts a part of the string


String s = "Java Programming";
System.out.println(s.substring(0, 4)); // Output: Java

7. toUpperCase() and toLowerCase() - Converts to uppercase/lowercase


String s = "Java";
System.out.println(s.toUpperCase()); // Output: JAVA
System.out.println(s.toLowerCase()); // Output: java

8. trim() - Removes leading and trailing spaces


String s = " Hello World ";
System.out.println(s.trim()); // Output: "Hello World"

4. What is Exception Handling in Java? Explain the different types of


exceptions.
Answer:
Exception Handling in Java is a mechanism to handle runtime errors and ensure smooth program
execution. It prevents the program from terminating unexpectedly when an error occurs.

Types of Exceptions in Java:


1. Checked Exceptions:
• These exceptions are checked at compile-time.
• Example: IOException, SQLException.
• Example Code:
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("test.txt"); // May throw
IOException
}
}

2. Unchecked Exceptions:
• These exceptions occur at runtime and are not checked during compilation.
• Example: NullPointerException, ArithmeticException,
ArrayIndexOutOfBoundsException.
• Example Code:
public class UncheckedExceptionExample {
public static void main(String[] args) {
int a = 10 / 0; // ArithmeticException: Divide by zero
}
}

3. Errors:
• These are serious problems beyond the control of a programmer.
• Example: StackOverflowError, OutOfMemoryError.

5. What are the different exception handling keywords in Java? Explain with
examples.
Answer:
Java provides five keywords to handle exceptions effectively.
1. try Block:

• Contains the code that may cause an exception.


try {
int a = 10 / 0; // May throw ArithmeticException
}

2. catch Block:

• Handles the exception thrown inside the try block.


try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}

3. finally Block:

• Always executes, whether an exception occurs or not.


try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught!");
} finally {
System.out.println("Finally block executed.");
}

4. throw Keyword:

• Used to explicitly throw an exception.


public class ThrowExample {
public static void validate(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
}
public static void main(String[] args) {
validate(15); // Throws an exception
}
}
5. throws Keyword:

• Declares an exception in the method signature.


public class ThrowsExample {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) throw new ArithmeticException("Underage");
}
public static void main(String[] args) throws ArithmeticException {
checkAge(16);
}
}
1. Explain the concept of Multithreading in Java. How is it different from a
process?
Answer:
Multithreading is a feature in Java that allows multiple threads to run concurrently. A thread is the
smallest unit of execution within a process. Using multithreading, a program can perform multiple
tasks at the same time, improving the efficiency and responsiveness of applications.

Key Features of Multithreading:


• Threads share a common memory space.
• Each thread has its own execution stack.
• Context switching between threads is faster than switching between processes.
• It improves performance by utilizing CPU time efficiently.

Difference Between Thread and Process:


Feature Process Thread
A process is an instance of a program A thread is a lightweight process within
Definition
in execution. a program.
Threads share memory within the same
Memory Sharing Processes do not share memory.
process.
Speed Process switching is slow. Thread switching is faster.
Processes require inter-process Threads can communicate easily since
Communication
communication (IPC). they share memory.
Overhead More resource-intensive. Uses fewer resources.
Example of Multithreading in Java:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}

public static void main(String[] args) {


MyThread t1 = new MyThread();
t1.start(); // Starts the execution of a new thread
}
}

2. Describe the life cycle of a thread in Java.


Answer:
A thread in Java goes through several states in its life cycle. The five main states are:
1. New (Created) State:
• A thread is in the new state when it is created using the Thread class but has not yet
started.
• Example: Thread t = new Thread();
2. Runnable State:
• The thread enters this state when start() is called.
• It is waiting for the CPU to allocate time for execution.
• Example:
Thread t = new Thread();
t.start(); // Moves the thread to runnable state

3. Running State:
• When the CPU assigns time to the thread, it enters the running state.
• The thread executes the run() method.
4. Blocked or Waiting State:
• The thread enters the blocked state when it is waiting for a resource to become
available.
• Methods like wait(), sleep(), and join() can cause a thread to enter this
state.
5. Terminated (Dead) State:
• A thread is considered dead when it has completed its execution or is stopped using
stop() (deprecated).
• Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
MyThread t = new MyThread();
t.start(); // Thread moves from new -> runnable -> running -> dead

3. Explain the different ways to create a thread in Java with examples.


Answer:
There are two ways to create a thread in Java:

1. By Extending the Thread Class:


• We create a new class that extends Thread and override the run() method.
• Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}

public static void main(String[] args) {


MyThread t1 = new MyThread();
t1.start(); // Starts the execution of the thread
}
}

• The start() method calls run(), executing the thread in a separate call stack.
2. By Implementing the Runnable Interface:
• We create a new class that implements Runnable and override the run() method.
• Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}

public static void main(String[] args) {


MyRunnable obj = new MyRunnable();
Thread t1 = new Thread(obj);
t1.start(); // Starts the thread
}
}

• Key Differences:
• Thread class approach provides more control, but it doesn’t allow multiple
inheritance.
• Runnable interface approach allows flexibility by letting the class extend another
class if needed.

4. What are daemon threads in Java? How are they different from user threads?
Answer:
A daemon thread is a background thread that provides services to user threads. The JVM
terminates daemon threads automatically when no user threads are running.

Difference Between User Thread and Daemon Thread:


Feature User Thread Daemon Thread
Purpose Used for application logic. Supports user threads in the background.
Lifecycle Runs until completion. Stops when all user threads are finished.
Examples Main thread, worker threads. Garbage collector, JVM monitoring thread.
Example of Daemon Thread:
class MyDaemonThread extends Thread {
public void run() {
while (true) {
System.out.println("Daemon thread running...");
}
}

public static void main(String[] args) {


MyDaemonThread dt = new MyDaemonThread();
dt.setDaemon(true); // Must be set before starting the thread
dt.start();

System.out.println("Main thread finished...");


}
}
5. Explain Java Packages. How can we import and use packages in Java?
Answer:
A package in Java is a collection of related classes, interfaces, and sub-packages. It helps organize
code and avoid name conflicts.

Types of Packages:
1. Built-in Packages: Provided by Java (e.g., java.util, java.io).
2. User-defined Packages: Created by the programmer.

Creating a User-Defined Package:


1. Define a package using the package keyword:
package mypackage;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass");
}
}

2. Compile using:
javac -d . MyClass.java

3. Use the package in another class:


import mypackage.MyClass;

public class Test {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}

Ways to Access a Package:


• Using import package.*: Imports all classes of the package.
• Using import package.ClassName: Imports a specific class.
• Using fully qualified name: Accesses a class without import (e.g.,
mypackage.MyClass obj = new mypackage.MyClass();).
1. Explain the differences between arrays and linked lists. When would you
choose a linked list over an array?
Answer:
An array is a collection of elements stored in contiguous memory locations, while a linked list
consists of nodes that are stored randomly in memory and connected via pointers.

Feature Array Linked List


Dynamic (grows/shrinks as
Memory Allocation Static (fixed size)
needed)
Access Time Fast (O(1) using index) Slower (O(n) for traversal)
Expensive (shifting
Insertion/Deletion Efficient (no shifting needed)
required)
Memory Utilization Wastes space if not full Uses only required memory
Data Storage Contiguous memory Non-contiguous memory
Complexity for
O(n) in worst case O(1) at the head, O(n) otherwise
Insertion/Deletion
When to choose a linked list over an array?
• When frequent insertions/deletions are required.
• When memory allocation should be dynamic.
• When a data structure should be resized frequently.

2. Explain different types of linked lists with diagrams.


Answer:
A linked list is a collection of nodes where each node contains data and a pointer to the next node.
There are four main types:
1. Singly Linked List
• Each node has two parts: data and a pointer to the next node.
• Can only be traversed in one direction.
• Last node points to null.
[10|*] → [20|*] → [30|null]

2. Doubly Linked List


• Each node has three parts: data, pointer to the next node, and pointer to the
previous node.
• Can be traversed in both directions.
null ← [10|*|*] ↔ [20|*|*] ↔ [30|*|null]

3. Circular Linked List


• The last node points back to the first node, forming a circle.
• Used in task scheduling and buffers.
[10|*] → [20|*] → [30|*] → back to [10|*]

4. Circular Doubly Linked List


• Similar to a doubly linked list, but last node links back to the first node.
• Allows forward and backward traversal.
[10|*|*] ↔ [20|*|*] ↔ [30|*|*] ↔ back to [10|*|*]

3. Describe the operations on a singly linked list. Provide Java code for insertion
at the beginning and deletion at the end.
Answer:
Operations on a singly linked list:
1. Insertion at the beginning
2. Insertion at the end
3. Insertion after a specific node
4. Deletion at the beginning
5. Deletion at the end
6. Deletion after a specific node
7. Searching for an element
8. Traversing the list
Java code for insertion at the beginning:
class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}

class LinkedList {
Node head;

void insertAtBeginning(int newData) {


Node newNode = new Node(newData);
newNode.next = head;
head = newNode;
}

void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " → ");
temp = temp.next;
}
System.out.println("null");
}

public static void main(String[] args) {


LinkedList list = new LinkedList();
list.insertAtBeginning(10);
list.insertAtBeginning(20);
list.insertAtBeginning(30);
list.display();
}
}

Java code for deletion at the end:


class LinkedList {
Node head;

void deleteAtEnd() {
if (head == null) return;
if (head.next == null) {
head = null;
return;
}
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
}

4. What is an applet? Explain the lifecycle of an applet in Java.


Answer:
An applet is a small Java program that runs inside a web browser or applet viewer.
Advantages of Applets:
• Works on the client-side, reducing server load.
• Secure because it runs in a sandbox.
• Runs on multiple platforms (Windows, Linux, macOS).
Lifecycle of an Applet:
1. init()
• Called once when the applet is initialized.
• Used to set up variables and components.
2. start()
• Called when the applet starts or when the browser is maximized.
3. paint(Graphics g)
• Called whenever the applet needs to be redrawn.
• Used for displaying graphics.
4. stop()
• Called when the applet is stopped or when the browser is minimized.
5. destroy()
• Called when the applet is closed.
• Used for cleaning up resources.
Java Code for a Simple Applet:
import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
}
}

HTML File to Run the Applet:


<html>
<body>
<applet code="MyApplet.class" width="300" height="300"></applet>
</body>
</html>

5. How does Java handle graphics in applets? Provide an example.


Answer:
Java provides the Graphics class in the java.awt package for drawing shapes and text in applets.
Commonly Used Methods of the Graphics Class:
• drawString(String str, int x, int y): Draws a string.
• drawLine(int x1, int y1, int x2, int y2): Draws a line.
• drawRect(int x, int y, int width, int height): Draws a rectangle.
• fillRect(int x, int y, int width, int height): Draws a filled
rectangle.
• drawOval(int x, int y, int width, int height): Draws an oval.
• fillOval(int x, int y, int width, int height): Draws a filled oval.

Example: Drawing Shapes in an Applet


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

public class GraphicsDemo extends Applet {


public void paint(Graphics g) {
g.setColor(Color.RED);
g.drawString("Graphics in Applet", 50, 50);
g.drawLine(20, 30, 20, 300);
g.drawRect(70, 100, 30, 30);
g.fillRect(170, 100, 30, 30);
g.drawOval(70, 200, 30, 30);
g.setColor(Color.BLUE);
g.fillOval(170, 200, 30, 30);
}
}

HTML File to Run the Applet:


<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300"></applet>
</body>
</html>

You might also like