Java Programming - Important Questions with Answers
1. What is multithreading? Explain life cycle of thread?
Multithreading in Java:
Multithreading is a core feature in Java that allows the concurrent execution of two or more threads. A thread
is a lightweight sub-process, the smallest unit of processing. Multithreading enables better CPU utilization
and helps in performing multiple operations simultaneously.
For example, while one thread is downloading a file, another can update the user interface. This improves the
responsiveness of an application.
Java provides built-in support for multithreaded programming through the Thread class and the Runnable
interface.
Advantages of Multithreading:
- Improved Performance: Tasks can be completed faster as threads run concurrently.
- Resource Sharing: Threads share the same memory space, which makes communication between them
easy.
- Responsiveness: Useful for GUI-based applications, where the UI remains responsive even when other
operations are running.
- Simplified Program Structure: Easier to manage multiple tasks inside a single application.
Life Cycle of a Thread in Java:
A thread in Java can be in one of the following states:
1. New:
A thread is in the new state when an instance of the Thread class is created but the start() method is not
yet called.
2. Runnable:
After calling the start() method, the thread is ready to run and moves to the runnable state. It waits for the
Java Programming - Important Questions with Answers
thread scheduler to allocate CPU time.
3. Running:
When the thread scheduler picks a thread from the runnable pool, it moves to the running state. In this
state, the thread executes its task (code in the run() method).
4. Blocked/Waiting:
A thread enters this state if it waits for a resource or condition (like waiting for I/O or synchronization lock). It
will return to runnable when the condition is met.
5. Terminated (Dead):
A thread is in the terminated or dead state when its execution is complete or it is forcibly stopped.
Thread Life Cycle Diagram (Conceptual):
New --> Runnable --> Running --> Terminated
| |
Waiting Blocked
Creating Threads in Java:
There are two common ways to create threads:
1. By Extending Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running...");
2. By Implementing Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running...");
Java Programming - Important Questions with Answers
2. What is exception handling? Explain different types of exception handling?
Exception Handling in Java:
Exception handling is a mechanism in Java to handle runtime errors so the normal flow of the application can
be maintained. It allows a program to deal with unexpected situations such as file not found, division by zero,
etc., without crashing.
An exception is an object that represents an error or abnormal condition. All exception classes in Java are
derived from the Throwable class.
Types of Exceptions:
1. Checked Exceptions: These are exceptions that are checked at compile-time. Example: IOException,
SQLException.
2. Unchecked Exceptions: These are exceptions that are checked at runtime. Example: ArithmeticException,
NullPointerException.
Exception Handling Keywords:
- try: Used to write code that might throw an exception.
- catch: Used to handle the exception.
- finally: A block that always executes, regardless of an exception.
- throw: Used to explicitly throw an exception.
- throws: Declares exceptions a method might throw.
Syntax Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
Java Programming - Important Questions with Answers
} finally {
System.out.println("This will always execute.");
Custom Exception:
Java allows creation of custom exceptions by extending the Exception class.
class MyException extends Exception {
MyException(String message) {
super(message);
In summary, exception handling improves code reliability, readability, and flow control by catching and
managing unexpected conditions effectively.
3. What is stream? Explain different types of streams?
Streams in Java:
In Java, a stream is a sequence of data. Java provides streams to perform input and output operations. The
stream is a continuous flow of data. Java uses the concept of streams to make input and output operations
faster and more efficient.
Types of Streams:
1. Byte Streams:
- Used to perform input and output of 8-bit bytes.
- Classes: FileInputStream, FileOutputStream
- Example:
FileInputStream fin = new FileInputStream("file.txt");
Java Programming - Important Questions with Answers
2. Character Streams:
- Used to perform input and output for 16-bit Unicode.
- Classes: FileReader, FileWriter
- Example:
FileReader fr = new FileReader("file.txt");
3. Data Streams:
- Used to read and write primitive Java data types.
- Classes: DataInputStream, DataOutputStream
4. Buffered Streams:
- Improves performance by buffering data.
- Classes: BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream
5. Object Streams:
- Used for serialization of objects.
- Classes: ObjectInputStream, ObjectOutputStream
Stream Hierarchy:
- java.io.InputStream (abstract class)
- java.io.OutputStream (abstract class)
- java.io.Reader (abstract class)
- java.io.Writer (abstract class)
Input and output streams can be used with files, memory, or network connections. Streams are crucial for
reading and writing data in various formats.
4. What is Swing? Explain at least 3 components of Swing.
Swing in Java:
Swing is a part of Java Foundation Classes (JFC) used to create window-based applications. It is a
Java Programming - Important Questions with Answers
lightweight GUI toolkit that is platform-independent and provides a richer set of components than the AWT
(Abstract Window Toolkit).
Swing components are written entirely in Java and are more flexible. It supports pluggable look and feel and
MVC (Model-View-Controller) architecture.
Common Swing Components:
1. JButton:
- Used to create a button.
- Example:
JButton b = new JButton("Click Me");
2. JLabel:
- Displays a short string or image icon.
- Example:
JLabel label = new JLabel("Welcome");
3. JTextField:
- Allows user to enter a single line of text.
- Example:
JTextField textField = new JTextField("Type here", 20);
4. JCheckBox, JRadioButton, JComboBox, JTable are also commonly used.
Creating a Swing Application:
- Import javax.swing.* package
- Extend JFrame class
- Add components like JButton, JLabel, etc.
- Set layout and visibility
Example:
Java Programming - Important Questions with Answers
JFrame f = new JFrame("My Swing App");
JButton b = new JButton("Click");
f.add(b);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
Swing offers advanced controls and better UI features, making it preferred for GUI development in Java.
5. Explain different types of containers (Panel, Window, Frame)?
Containers in Java:
In Java Swing, a container is a component that can hold other components. Containers play a crucial role in
GUI development, allowing the arrangement of components like buttons, labels, text fields, etc.
Types of Containers:
1. Panel (JPanel):
- It is a generic container used to group related components.
- Cannot be displayed on its own; it must be added to another container like a JFrame.
- Lightweight and often used for organizing components.
- Example:
JPanel panel = new JPanel();
2. Window (Window Class):
- It is an abstract class that provides a top-level window with no borders or menus.
- Not commonly used directly.
- Extended by Frame and Dialog classes.
3. Frame (JFrame):
- Most commonly used top-level container.
Java Programming - Important Questions with Answers
- Can contain menus, toolbars, buttons, etc.
- It has a title bar, border, and buttons like minimize, maximize, and close.
- Example:
JFrame frame = new JFrame("My Frame");
Hierarchy:
Component Container Window Frame
Frame is used to create full-fledged windows, whereas Panel is used to divide the window into smaller areas
for better layout and organization.