0% found this document useful (0 votes)
3 views4 pages

Java 2mark Questions

The document is a Java question bank focused on Exception Handling and Multithreading, covering key concepts such as the differences between throw and throws, checked and unchecked exceptions, and the life cycle of a thread. It also discusses the purpose of multithreading, synchronization, inter-thread communication, and the Executor framework. Additionally, it includes a section on Generics and Collections, explaining concepts like generics, the Collection interface, and differences between various collection types.

Uploaded by

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

Java 2mark Questions

The document is a Java question bank focused on Exception Handling and Multithreading, covering key concepts such as the differences between throw and throws, checked and unchecked exceptions, and the life cycle of a thread. It also discusses the purpose of multithreading, synchronization, inter-thread communication, and the Executor framework. Additionally, it includes a section on Generics and Collections, explaining concepts like generics, the Collection interface, and differences between various collection types.

Uploaded by

maharishi6002
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Question Bank: 2-Mark Collection

Module IV: Exception Handling & Multithreading


 Q: Explain the difference between throw and throws.
A: The 'throw' keyword is used to explicitly throw a single exception from a method
or block of code and is followed by an instance of the exception class. Conversely,
'throws' is used in the method signature to declare that a method might throw one or
more exceptions, delegating the responsibility of handling it to the caller.
 Q: Differentiate checked and unchecked exceptions with example.
A: Checked exceptions are checked at compile-time (e.g., IOException, SQLException),
and the compiler ensures they are either caught or declared. Unchecked exceptions
occur at runtime and are not verified by the compiler (e.g., NullPointerException,
ArithmeticException); they typically result from programming logic errors.
 Q: Explain how try-catch works in Java.
A: The 'try' block contains code that might throw an exception. If an exception occurs,
the execution of the try block stops, and the 'catch' block matching the exception type is
executed, preventing abrupt termination and allowing for graceful error handling.
 Q: Why is the finally block used?
A: The 'finally' block is used to execute important code such as closing connections or
releasing resources. It is guaranteed to execute regardless of whether an exception was
thrown or caught, ensuring system stability.
 Q: Explain the need for exception handling in Java.
A: It is essential to maintain the normal flow of the application even when unexpected
errors occur. It provides a structured way to separate error-handling code from regular
business logic, making the code more readable and robust.
 Q: How are built-in exceptions different from user-defined exceptions?
A: Built-in exceptions are provided by the Java API (like ClassNotFoundException) to
handle common error scenarios. User-defined (custom) exceptions are created by
developers by extending the Exception class to handle specific application-level
business errors.
 Q: Explain how to create a custom exception.
A: To create a custom exception, you must create a class that extends the 'Exception'
(for checked) or 'RuntimeException' (for unchecked) class. Example: class MyException
extends Exception { public MyException(String s) { super(s); } }
 Q: Explain the life cycle of a thread.
A: A thread's life cycle includes: New (created but not started), Runnable (ready to
run), Running (executing), Blocked/Waiting (waiting for resource/another thread), and
Terminated (finished execution).
 Q: Differentiate between process and thread.
A: A process is an independent execution unit with its own memory space, whereas a
thread is a subset of a process that shares memory with other threads of the same
process. Threads are lightweight and easier to context switch compared to processes.
 Q: Explain the purpose of multithreading.
A: Multithreading allows the concurrent execution of two or more parts of a program
for maximum utilization of the CPU, which is vital for developing interactive
applications and high-performance servers.
 Q: Compare creating a thread using Thread class and Runnable interface.
A: Extending the 'Thread' class is simpler but limits inheritance since Java doesn't
support multiple inheritance. Implementing 'Runnable' is more flexible as it allows the
class to extend another class while still being a thread.
 Q: Explain the role of the start() method in threads.
A: The 'start()' method is used to register the thread with the thread scheduler and
move it to the Runnable state. Internally, it calls the 'run()' method; calling 'run()'
directly executes it in the current thread instead of a new one.
 Q: Why is synchronization needed in multithreading?
A: It is needed to prevent 'thread interference' and 'consistency errors' when multiple
threads access shared resources simultaneously, ensuring only one thread can access a
critical section at a time.
 Q: Explain how the synchronized keyword works.
A: It acquires a lock on the object or class. While a thread holds this lock, no other
thread can enter any synchronized method/block on that same object.
 Q: Differentiate between synchronized method and synchronized block.
A: A synchronized method locks the entire object for the duration of the method call.
A synchronized block locks only a specific object for a specific portion of the code,
providing finer-grained control and better performance.
 Q: Explain inter-thread communication with example methods.
A: It allows synchronized threads to communicate via wait(), notify(), and notifyAll().
One thread pauses its execution (wait) until another thread signals it to resume (notify).
 Q: What is the role of wait() and notify() methods?
A: wait() tells the calling thread to give up the lock and go to sleep until another
thread calls notify(). notify() wakes up a single thread that is waiting on that object’s
monitor.
 Q: Explain the concept of thread pool.
A: A thread pool is a managed collection of worker threads that are reused to execute
tasks, reducing the overhead of creating and destroying threads for every task and
improving system performance.
 Q: Why is Executor framework used?
A: It decouples task submission from task execution and manages thread creation,
scheduling, and lifecycle automatically, making concurrent programming easier and
more efficient.
 Q: Differentiate Runnable and Callable.
A: Runnable's run() method does not return a result and cannot throw checked
exceptions. Callable's call() method returns a result (Future) and can throw checked
exceptions.
 Q: Explain how Future is used in Java.
A: A 'Future' represents the result of an asynchronous computation and provides
methods to check if the computation is complete, to wait for its completion, and to
retrieve the result.
 Q: Explain the purpose of Fork/Join framework.
A: It is designed for work-stealing and parallelizing tasks that can be broken into
smaller subtasks (divide-and-conquer), utilizing all available processor cores to speed
up large computations.
 Q: What is deadlock? Explain with a situation.
A: Deadlock is a situation where two or more threads are blocked forever, each
waiting for the other. Example: Thread A holds Lock 1 and waits for Lock 2, while
Thread B holds Lock 2 and waits for Lock 1.
 Q: Explain the four conditions required for deadlock.
A: 1. Mutual Exclusion (non-shareable resources), 2. Hold and Wait (holding one and
waiting for another), 3. No Preemption (resources cannot be forcibly taken), 4. Circular
Wait (threads wait in a circle).
 Q: Explain the use of Enumeration interface.
A: Enumeration is a legacy interface used to iterate through elements of a collection
(like Vector or Stack) using hasMoreElements() and nextElement().
 Q: Differentiate Enumeration and Iterator.
A: Enumeration is legacy, read-only, and only for legacy classes. Iterator is part of the
modern Collection framework, supports the 'remove()' operation, and works with all
Collection types.

Module V: Generics & Collections


 Q: Explain the concept of generics in Java.
A: Generics allow classes, interfaces, and methods to be parameterized with types,
allowing the same code to be reused for different data types while providing strong type
checking at compile-time.
 Q: Summarize the advantages of generic programming.
A: 1. Type-safety: Catch errors at compile-time. 2. Elimination of Type Casting: No
need to manually cast objects. 3. Code Reusability: Write a logic once for any type.
 Q: Describe how generics ensure type safety.
A: Generics ensure that you only put the correct type of object into a collection (e.g.,
List<String> will not allow an Integer), preventing ClassCastException at runtime.
 Q: Explain the structure of a generic class with an example.
A: A generic class is defined with a type parameter in angle brackets. Example: class
Box<T> { T value; void set(T t) { value = t; } T get() { return value; } }
 Q: Explain the role of the Collection interface in Java.
A: It is the root interface of the Collection hierarchy and defines basic operations like
add, remove, size, and clear that all concrete collections (List, Set, Queue) must
implement.
 Q: Differentiate between List and Set interfaces.
A: List is an ordered collection that allows duplicate elements (e.g., ArrayList). Set is
an unordered collection that prohibits duplicate elements (e.g., HashSet.
 Q: Explain the working of Queue interface.
A: Queue follows the First-In-First-Out (FIFO) principle and is used to hold elements
prior to processing (e.g., PriorityQueue and LinkedList).
 Q: Differentiate between ArrayList and HashSet.
A: ArrayList is index-based, maintains insertion order, and allows duplicates. HashSet
is hash-table-based, does not maintain order, and allows only unique elements.
 Q: Explain how TreeSet maintains sorted order.
A: TreeSet uses a Red-Black tree internally, where elements are sorted according to
their natural ordering or by a provided Comparator.
 Q: Differentiate between HashMap and TreeMap.
A: HashMap is faster and doesn't guarantee any order. TreeMap is slower because it
maintains keys in a sorted (natural or comparator) order.

You might also like