Java 2nd Internal QB
Java 2nd Internal QB
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.
You can define your own exception class by extending the Exception class (for checked
exceptions) or RuntimeException (for unchecked exceptions).
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
This example demonstrates how to create a custom exception and handle it in Java.
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());
}
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.");
}
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 is often used in cases where you want to indicate that a specific condition has
failed in your code.
Example:
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.
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.
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;
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.
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.
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.
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.
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:
Explanation:
Calling thread.start() initiates a new thread, which then calls the run() method.
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.
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.
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.
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
}
}
if (lock1.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
// Critical section
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
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.
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.
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.
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.
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
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.
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
Example of Error
Errors generally indicate severe problems that cannot be recovered from, like
OutOfMemoryError.
Example of Exception
Exceptions are typically issues that the programmer can anticipate and handle, like
ArithmeticException or IOException.
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
Components in Java
Examples of Components:
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.
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.
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.
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.
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:
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:
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:
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).
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.
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.
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.
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.
import java.applet.Applet;
import java.awt.Graphics;
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.
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;
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.
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.
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.
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.
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