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

Java 2nd Internal QB

Thankyou

Uploaded by

kishore gogikar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java 2nd Internal QB

Thankyou

Uploaded by

kishore gogikar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

Question Bank for Java- Part-2 BCA-Sem-3 by Kishore Gogikar


1.What are exceptions? Write an example for exception class.

Exceptions in Java are events that occur during the execution of a program, disrupting the normal
flow of instructions. They are used to handle runtime errors, providing a mechanism to detect
and deal with them gracefully rather than allowing the program to crash.

An exception can be checked or unchecked:

 Checked exceptions must be handled (e.g., IOException, SQLException).


 Unchecked exceptions (runtime exceptions) don’t require explicit handling (e.g.,
NullPointerException, ArrayIndexOutOfBoundsException).

Example of an Exception Class in Java:

You can define your own exception class by extending the Exception class (for checked
exceptions) or RuntimeException (for unchecked exceptions).

Here’s an example of a custom exception class:

// Custom Exception Class


class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); // Call constructor of parent Exception class
}
}

public class Main {


// Method to check the validity of age
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is less than 18, not
eligible.");
} else {
System.out.println("Age is valid, you are eligible.");
}
}

public static void main(String[] args) {


try {
validateAge(16); // This will throw the custom exception
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Explanation:

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 1 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

 InvalidAgeException: A custom exception that inherits from Exception.


 validateAge(int age): A method that checks if the age is less than 18, throws
InvalidAgeException if it is.
 try-catch block: The code attempts to validate the age and catch the custom exception
when thrown.

Output when you run the program:

Caught Exception: Age is less than 18, not eligible.

This example demonstrates how to create a custom exception and handle it in Java.

2.Write about try, catch, throw key words in details.


In Java, try, catch, and throw are keywords used for exception handling. They allow developers to
handle errors and exceptional conditions gracefully, ensuring that the program can recover from certain
types of errors without crashing

1. The try Block

The try block is used to enclose code that might throw an exception. It serves as the starting
point for exception handling. If an exception occurs within a try block, the program
immediately jumps to the corresponding catch block.

 Syntax:

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

 Example:

try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An error occurred: " + e.getMessage());
}

2. The catch Block

The catch block is used to handle exceptions that occur in the associated try block. Each catch
block catches a specific type of exception, allowing you to handle different exceptions in
different ways.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 2 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

 Syntax:

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the specific type of exception
}

 Multiple catch blocks can follow a single try block, allowing for more specific
exception handling.
 Example:

try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds!");
} catch (Exception e) {
System.out.println("An error occurred.");
}

3. The throw Keyword

The throw keyword is used to explicitly throw an exception. This can be an existing exception
(like NullPointerException) or a custom one defined by the developer.

 Syntax:

throw new ExceptionType("Error message");

 throw is often used in cases where you want to indicate that a specific condition has
failed in your code.
 Example:

public void checkAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
} else {
System.out.println("You are eligible.");
}
}

3.What are checked exceptions.

Checked Exceptions in Java

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 3 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

In Java, checked exceptions are exceptions that are checked at compile-time. This means that
the Java compiler ensures that the programmer handles these exceptions properly, either by
catching them or by declaring them using the throws clause in the method signature.

Checked exceptions typically represent conditions that a program should be able to recover from,
such as file input/output errors or network failures.

Key Characteristics of Checked Exceptions:

1. Compile-Time Checking:
o The compiler forces the handling of checked exceptions. If a method can throw a
checked exception, the code must explicitly handle it using try-catch or declare
it using the throws keyword in the method signature.
2. Recoverable Conditions:
o Checked exceptions often represent conditions that could be handled
programmatically, allowing the application to recover from the error.
3. Must Be Handled or Declared:
o The method that throws a checked exception must either:
 Handle the exception using a try-catch block.
 Declare the exception using the throws keyword.

Common Checked Exceptions in Java

 IOException: This exception is thrown during input/output operations (such as file


handling) when something goes wrong, such as a file not being found or the file system
failing.

Example: File handling errors, like trying to open a file that doesn’t exist.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CheckedExceptionExample {


public static void main(String[] args) {
try {
File file = new File("nonexistentfile.txt");
Scanner sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}

4.What are unchecked exceptions.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 4 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

Unchecked exceptions in Java are exceptions that are not checked at compile-time. This means
the compiler does not force the programmer to handle or declare them explicitly. They occur
during runtime, and unlike checked exceptions, they are typically caused by programming errors
or logical mistakes that the program might not be able to recover from.

Unchecked exceptions are subclasses of RuntimeException, which in turn is a subclass of


Exception. These exceptions usually indicate serious problems like invalid data or illegal
operations within the code.

Key Characteristics of Unchecked Exceptions:

1. No Compile-Time Checking:
o Unchecked exceptions are not checked by the Java compiler, meaning the
programmer is not required to handle or declare them explicitly in the code.
2. Runtime Errors:
o These exceptions occur during the execution of a program and are often the result
of bugs in the program logic, such as trying to access an array index out of bounds
or calling a method on a null reference.
3. Programming Mistakes:
o Unchecked exceptions typically occur due to programming mistakes like
improper use of data structures or logic errors.
4. Optional Handling:
o While you are not required to handle unchecked exceptions, it is still good
practice to anticipate and handle situations where they may occur.

Here’s an example of an unchecked exception caused by a NullPointerException:

public class UncheckedExceptionExample {


public static void main(String[] args) {
String str = null;

try {
System.out.println(str.length()); // This will throw a
NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught a NullPointerException: " +
e.getMessage());
}
}
}

5.Define Thread.
A thread in Java is a lightweight subprocess or smallest unit of a process that can run concurrently with
other threads within the same application. Threads allow multiple tasks to execute simultaneously in a
program, improving the efficiency and responsiveness of applications.

6.How to create thread? Write an example.


Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 5 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

A thread in Java is a lightweight subprocess or smallest unit of a process that can run
concurrently with other threads within the same application. Threads allow multiple tasks to
execute simultaneously in a program, improving the efficiency and responsiveness of
applications. In Java, threads can perform operations independently and share resources, making
them useful for handling tasks like multitasking, parallel processing, and concurrent
programming.

Java provides built-in support for multithreading through the java.lang.Thread class and the
Runnable interface.

Ways to Create a Thread in Java

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

1. By Extending the Thread Class


2. By Implementing the Runnable Interface

1. Creating a Thread by Extending the Thread Class

To create a thread by extending the Thread class, you define a class that inherits from Thread
and override its run() method. The run() method contains the code that the thread will execute.

Example:

class MyThread extends Thread {


@Override
public void run() {
// Code to execute in this thread
for (int i = 1; i <= 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread thread = new MyThread(); // Create thread instance
thread.start(); // Start the thread
}
}

Explanation:

 MyThread extends Thread and overrides the run() method.


 Inside run(), the code that should run in parallel is defined.
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 6 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

 Calling thread.start() initiates a new thread, which then calls the run() method.

7.What are uses of synchronized keyword.

The synchronized keyword in Java is used to control access to critical sections of code by
multiple threads, ensuring thread safety. It allows only one thread to execute a synchronized
block or method at a time, thus preventing race conditions and data inconsistency. The
synchronized keyword is primarily used in multithreaded applications where multiple threads
share resources and need coordinated access to prevent conflicts.

Uses of the synchronized Keyword:

1. Mutual Exclusion:
o Ensures that only one thread can access a synchronized block of code or method
at a time.
o By locking on an object or class, synchronized prevents other threads from
entering the synchronized code until the lock is released.
o Helps in situations where shared resources, like counters or collections, need
protection against concurrent modifications.
2. Data Consistency:
o Ensures data consistency by controlling access to shared variables or objects.
o Useful when multiple threads read and write shared data and can lead to
inconsistent states.
3. Coordination Between Threads:
o The synchronized keyword can also help in coordinating actions between
threads.
o By locking critical sections of code, it can act as a gatekeeper, ensuring that
certain tasks complete before another thread proceeds.
4. Deadlock Prevention:
o By using synchronization wisely, it helps prevent deadlocks, although poor
synchronization can also cause deadlocks. Deadlocks occur when two or more
threads wait indefinitely for each other to release resources.
o Correctly managing synchronized blocks and object locks helps to avoid
situations where threads lock up, waiting for resources held by each other.
5. Atomicity:
o Synchronization makes a section of code atomic, meaning it will execute as a
single unit without interruption. This is essential for operations that require
multiple steps, such as incrementing a counter or modifying complex data
structures, where intermediate states should not be visible to other threads.

8.How to avoid deadlock.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 7 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

Deadlock in Java occurs when two or more threads are blocked forever, each waiting for
resources held by the other threads, leading to a state where the program cannot proceed. This
happens when multiple threads lock resources in such a way that a circular dependency is
created, where each thread waits for a resource locked by another.

To avoid deadlock in Java, you can follow certain programming practices:

1. Acquire Locks in a Consistent Order

 Solution: Ensure that all threads acquire locks in a specific, predefined order. By
following a consistent lock acquisition order across threads, the risk of circular
dependency decreases.
 Example: Suppose two threads need to access ResourceA and ResourceB. If each thread
locks ResourceA before ResourceB, the potential for deadlock is reduced because they
won’t be waiting on each other indefinitely.

synchronized(resourceA) {
synchronized(resourceB) {
// Critical section
}
}

2. Use tryLock() with Timeout

 Java’s ReentrantLock class (in java.util.concurrent.locks) offers a tryLock()


method, which attempts to acquire a lock only if it is available. You can specify a
timeout, after which the thread stops waiting if the lock is still unavailable.
 Solution: Using tryLock() with a timeout helps prevent indefinite blocking, as threads
can back out if they fail to acquire the lock within a specified time, reducing the
likelihood of deadlocks.

Lock lock1 = new ReentrantLock();


Lock lock2 = new ReentrantLock();

if (lock1.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
// Critical section
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}

3. Avoid Nested Locks

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 8 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

 Solution: Avoid acquiring multiple locks within a single thread whenever possible. When
only one lock is acquired at a time, there is no possibility of deadlock. If your application
can manage to perform tasks with single-lock operations, the risk of deadlocks decreases.

4. Use Timed Locks for Deadlock Detection

 Regularly check if all required locks are obtained within a given period; if not, it can
be assumed that a deadlock might have occurred, and corrective actions can be taken
(e.g., logging, releasing resources).
 Solution: Monitor threads’ status using tools like the Java ThreadMXBean to detect
deadlocks programmatically. This way, you can attempt to log or terminate the
problematic threads in real-time.

ThreadMXBean bean = ManagementFactory.getThreadMXBean();


long[] threadIds = bean.findDeadlockedThreads();
if (threadIds != null) {
// Deadlock detected, handle it accordingly
}

5. Use Minimal Locks (Lock-Only Required Resources)

 Solution: Only lock the specific resources that are absolutely necessary to execute a
particular critical section. Avoid unnecessarily locking objects, which might restrict other
threads from progressing.

6. Apply Timeout for Threads

 When using a thread that acquires multiple locks, ensure each lock acquisition has a
timeout. If the thread fails to acquire a lock within the timeout, it can back out, thus
reducing the chances of a deadlock.
 Solution: Set reasonable timeouts so that the threads release locks if they cannot acquire
the needed resources in time.

7. Use Java’s High-Level Concurrency Utilities

 Java provides several high-level concurrency utilities, such as ExecutorService,


Semaphore, CountDownLatch, and CyclicBarrier, in the java.util.concurrent
package. These tools can handle synchronization needs in ways that avoid the traditional
locking mechanisms, often making deadlock less likely.
 Example: A Semaphore can restrict access to a limited number of threads and avoid
waiting indefinitely.

Example of Avoiding Deadlock by Acquiring Locks in a Specific Order

In this example, deadlock is avoided by ensuring that threads always lock resources in a
consistent order.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 9 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

public class AvoidDeadlock {


private final Object resourceA = new Object();
private final Object resourceB = new Object();

public void method1() {


synchronized (resourceA) { // Always lock resourceA first
System.out.println("Thread 1 locked ResourceA");
synchronized (resourceB) { // Then lock resourceB
System.out.println("Thread 1 locked ResourceB");
}
}
}

public void method2() {


synchronized (resourceA) { // Lock resourceA first consistently
System.out.println("Thread 2 locked ResourceA");
synchronized (resourceB) { // Then lock resourceB
System.out.println("Thread 2 locked ResourceB");
}
}
}
}

9.Write difference between error and exception.

In Java, both errors and exceptions are subclasses of Throwable, but they represent different
kinds of issues that can occur during the execution of a program. Understanding the differences
between them is essential for proper error handling and debugging.

Differences between Error and Exception in Java

Feature Error Exception


Errors are serious issues that
typically indicate problems Exceptions are conditions that a program
with the Java runtime might want to handle to ensure correct
Definition environment (JVM). They program execution. They usually indicate
often represent system-level issues within the program itself, like invalid
issues that are out of the input or logical errors.
programmer's control.
OutOfMemoryError, NullPointerException, IOException,
Examples StackOverflowError, ArithmeticException,
VirtualMachineError ArrayIndexOutOfBoundsException
Errors are generally
unrecoverable. The Exceptions are often recoverable. With
Recoverability application usually cannot proper exception handling, the application
continue running after an can continue running.
error occurs.
Handling Errors are usually not caught Exceptions can be caught and handled
Mechanism or handled in the code using using try-catch blocks. Programmers can

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 10 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

Feature Error Exception


try-catch blocks. They are
unhandled by default because define custom handling routines for specific
they typically indicate critical exceptions.
system-level failures.
Errors are part of the Error
Exceptions can be checked or unchecked,
Types class, which is a subclass of
based on the type of exception.
Throwable.
Hierarchy Error extends Throwable. Exception extends Throwable.
Errors are unchecked, Exceptions can be checked or unchecked.
meaning they are not checked Checked exceptions must be either caught
Checked/Unchecked at compile time and cannot or declared in the method signature.
be forced to be caught or
declared.
Errors usually signal Exceptions usually indicate issues in the
conditions that are outside program logic or user input and can be
Usage in
the application’s control and handled to maintain application flow.
Programming
are caused by the
environment.

Example of Error

Errors generally indicate severe problems that cannot be recovered from, like
OutOfMemoryError.

public class ErrorExample {


public static void main(String[] args) {
// Causes OutOfMemoryError by attempting to create an excessively
large array
int[] largeArray = new int[Integer.MAX_VALUE];
}
}

Example of Exception

Exceptions are typically issues that the programmer can anticipate and handle, like
ArithmeticException or IOException.

public class ExceptionExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // Will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Division by zero
is not allowed.");
}
}

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 11 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

10.Write about components and containers.

Components in Java

A component is an individual UI element in Java, representing a part of the graphical user


interface that the user can interact with, such as buttons, text fields, labels, checkboxes, etc.
Components are derived from the Component class in AWT or the JComponent class in Swing.

Examples of Components:

 AWT Components: Button, Label, TextField, Checkbox, List


 Swing Components: JButton, JLabel, JTextField, JCheckBox, JList

Components are typically used to:

 Display information to the user (e.g., Label, JLabel)


 Allow user interaction (e.g., Button, JButton, TextField, JTextField)
 Enable user input (e.g., TextArea, JTextArea, Choice, JComboBox)

A container is a special type of component that can hold other components or containers.
Containers provide a way to manage multiple components in a GUI, organizing them based on
specific layout managers. Containers themselves are also components, allowing them to be
nested within other containers.

Containers in Java can be classified into two main categories:

Top-level Containers: These are the main containers that hold all other components in
the GUI. They include:

o JFrame:A basic window with title, borders, and the ability to hold other
components.
o JDialog: A popup window used to capture user input or display information.
o JApplet: Used for creating applets, though applets are largely obsolete.

Lightweight Containers: These can be nested inside top-level containers to organize


components further. Examples include:

o JPanel: A flexible, general-purpose container used to group components.


o JScrollPane: Adds scrolling capability to components.

11.What is GUI control? Explain layout manager.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 12 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

A GUI control in Java (also known as a GUI component) is an interactive or display element
within a graphical user interface (GUI). These controls allow users to interact with the
application by clicking buttons, entering text, selecting options, etc. Java provides these GUI
controls through both the AWT (Abstract Window Toolkit) and Swing libraries, allowing
developers to build responsive and user-friendly interfaces.

Common Examples of GUI Controls

 Buttons: For initiating actions (e.g., JButton in Swing)


 Text Fields: For entering single lines of text (e.g., JTextField)
 Labels: For displaying non-editable text (e.g., JLabel)
 Checkboxes: For selecting or deselecting options (e.g., JCheckBox)
 Radio Buttons: For selecting one option from a group (e.g., JRadioButton)
 Combo Boxes: For dropdown selection (e.g., JComboBox)
 Text Areas: For entering multi-line text (e.g., JTextArea)

A Layout Manager in Java is responsible for arranging GUI controls in a container. Layout
managers automate the process of component positioning and sizing, making GUIs adaptable to
different screen sizes and resolutions. Different layout managers use various strategies to
organize components, and Java provides several built-in layout managers.

Common Layout Managers in Java

1. FlowLayout
o Description: Arranges components in a line, from left to right, and wraps to the
next line when there is no more space.
o Usage: Suitable for simple layouts and is the default for JPanel.
o Example:

JPanel panel = new JPanel(new FlowLayout());


panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));

2. BorderLayout
o Description: Divides the container into five regions: NORTH, SOUTH, EAST, WEST,
and CENTER. Each component added to a region occupies the entire space of that
region.
o Usage: Often used for main application windows, as it allows clear separation of
areas (e.g., header, footer, main content).
o Example:

JFrame frame = new JFrame();


frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);

3. GridLayout

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 13 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

o Description: Arranges components in a grid of rows and columns where each cell
has the same size.
o Usage: Useful for form layouts or when all components need to be equally
spaced.
o Example:

JPanel panel = new JPanel(new GridLayout(2, 2)); // 2 rows, 2


columns
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));

12.Define event Listeners.

n Java, event listeners are interfaces used to handle and respond to specific events that occur
during program execution, especially within graphical user interfaces (GUIs). Event listeners
play a central role in the event-driven programming model, where the flow of the application
is determined by events such as user actions (clicking a button, selecting an option, entering text)
or system-generated actions (window opening or closing).

What is an Event Listener

An event listener in Java is an interface in the java.awt.event or javax.swing.event


package, which contains methods that are invoked when a particular event occurs. Each event
type has a corresponding listener interface, and to handle an event, a listener must implement the
interface's methods.

13.What is Icon Interface.

In Java, the Icon interface is part of the javax.swing package and is used to represent
graphical icons or images that can be displayed within Swing components, such as buttons,
labels, or menus. The Icon interface is often used to add images to GUIs, helping to enhance the
visual representation and user experience of Java applications.

Key Characteristics of the Icon Interface

 Basic Purpose: It provides a structure for rendering graphical images within Swing
components.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 14 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

 Implementations: Java does not directly instantiate the Icon interface; rather, it uses
implementations of Icon, such as ImageIcon, which is commonly used for image-based
icons.
 Methods: The Icon interface has only three methods, which must be implemented by
any class that implements Icon:
1. int getIconWidth(): Returns the width of the icon in pixels.
2. int getIconHeight(): Returns the height of the icon in pixels.
3. void paintIcon(Component c, Graphics g, int x, int y): Draws the
icon at the specified location (x, y) within the component using the provided
Graphics object.

14.What is GUI design.


GUI design in Java involves creating graphical user interfaces for Java applications using libraries like
Swing and JavaFX. It enables developers to build interactive components—such as buttons, text fields,
labels, and menus—that users can interact with visually. Java's GUI design relies on layout managers to
organize these components and event listeners to handle user actions. Swing, being platform-
independent, is widely used for desktop applications, while JavaFX offers modern, rich UIs with support
for advanced graphics, media, and CSS styling.

15.What is event handling.


Event handling in Java is a mechanism that manages user interactions and system-generated events
within a Java application, particularly in GUIs. Java uses event listeners to capture events (like button
clicks, key presses, or mouse movements) and respond to them with specific actions. This is
accomplished by implementing listener interfaces (such as ActionListener, MouseListener) and
associating them with GUI components, allowing the program to react dynamically to user inputs.

16.What is applet.

An applet in Java is a small, lightweight Java program that runs inside a web browser or an
applet viewer. Applets were initially used to create dynamic and interactive web content, similar
to how JavaScript is used today. They are part of the java.applet package and were embedded
in HTML pages to be loaded and executed by the browser.

Key Features of Java Applets

 Embedded in HTML: Applets are embedded in HTML pages using the <applet> or
<object> tags.
 Security Restrictions: Applets run in a sandboxed environment, which restricts their
access to the system for security reasons.
 Lifecycle Methods: Applets have a defined lifecycle (init(), start(), stop(), and
destroy() methods) that manage their initialization, execution, and termination.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 15 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

 Outdated Technology: Due to security concerns and the rise of more efficient
technologies, Java applets are now considered obsolete. Modern browsers have removed
support for applets, favoring alternatives like JavaScript and HTML5.

Basic Structure of an Applet

Here is a simple example of an applet:

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {


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

Applet Lifecycle Methods

1. init(): Called once when the applet is first loaded.


2. start(): Called each time the applet becomes visible.
3. stop(): Called when the applet is no longer visible.
4. destroy(): Called when the applet is about to be destroyed.

17. Write about running applet.

Running a Java applet involves compiling the applet code and then executing it either in an
applet viewer or a web browser. However, it’s important to note that most modern browsers no
longer support Java applets due to security concerns and the deprecation of the applet
technology. Java applets are largely obsolete and have been replaced by other technologies like
JavaScript, HTML5, and JavaFX for web applications.

Steps to Run an Applet in Java

1. Write the Applet Code: Create a Java class that extends Applet or JApplet (for Swing-
based applets) and override its lifecycle methods (like init(), start(), paint(), etc.).

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {


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

2. Compile the Applet: Compile the Java code to create a .class file.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 16 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

javac MyApplet.java

3. Create an HTML File to Embed the Applet (Optional if using applet viewer): Create
an HTML file with an <applet> tag to embed the applet.

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

Note: The <applet> tag is deprecated and may not work in modern HTML documents.

4. Run the Applet Using Applet Viewer: Since most browsers no longer support Java
applets, you can use the appletviewer tool to run the applet.

appletviewer MyApplet.html

This will open the applet in a simple viewer that can interpret the applet’s graphical output.

18.What are deadlocks?


a deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a
lock. This happens when multiple threads need the same set of resources and acquire them in a way that
results in a circular dependency. Deadlocks can cause programs to freeze or hang indefinitely, making
them critical to avoid in concurrent programming. Proper synchronization practices, lock ordering, and
timeout mechanisms can help prevent deadlocks

19.What is Thread and explain the life cycle?

A thread in Java is a lightweight subprocess that allows concurrent execution of code within a
program. It is the smallest unit of processing that can be scheduled by the operating system. Java
supports multithreading, enabling multiple threads to run simultaneously, improving application
performance and responsiveness.

Thread Life Cycle

The lifecycle of a thread in Java consists of several states:

1. New: A thread is in this state when it is created but not yet started. It is represented by an
instance of the Thread class.
2. Runnable: After calling the start() method, the thread enters the runnable state, where
it is eligible to run. It may be running or waiting for CPU time.
3. Blocked: A thread enters this state when it is waiting to acquire a lock or resource held
by another thread, effectively pausing its execution.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 17 of 18
Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar

4. Waiting: A thread is in this state when it is waiting for another thread to perform a
particular action (e.g., wait(), join()).
5. Timed Waiting: Similar to the waiting state, but with a specified waiting time (e.g.,
sleep(milliseconds), wait(milliseconds)).
6. Terminated: A thread reaches this state when it has completed its execution or has been
terminated due to an unhandled exception.

20.Write about Swings in Java?

Swing is a powerful GUI toolkit in Java that provides a set of components for building rich
desktop applications. It is part of the Java Foundation Classes (JFC) and is built on top of the
AWT (Abstract Window Toolkit). Swing offers a wide range of lightweight components, such as
buttons, labels, text fields, tables, and trees, which are platform-independent and can be
customized for different look-and-feels.

Key Features of Swing:

1. Lightweight Components: Swing components are lightweight, meaning they do not rely
on native system resources, allowing for greater portability across different platforms.
2. Pluggable Look-and-Feel: Swing supports various look-and-feel options, enabling
developers to change the appearance of the application without altering its functionality.
3. Rich User Interface: It provides advanced features such as tooltips, tables, progress bars,
and rich text support, enhancing the user experience.
4. Event Handling: Swing has a robust event-handling mechanism, allowing developers to
create interactive applications that respond to user actions.
5. MVC Architecture: Swing follows the Model-View-Controller (MVC) design pattern,
promoting separation of concerns and easier management of complex applications.

Material/Question Bank for Java part 2 BCA Sem -3 OU-2024 by Kishore Gogikar Page 18 of 18

You might also like