100% found this document useful (1 vote)
9 views35 pages

OOP Java QuestionBank BEU

The document is a comprehensive question bank for a course on Object-Oriented Programming using Java, covering various topics such as OOP concepts, Java data types, control structures, classes, objects, constructors, and access modifiers. It includes detailed questions with explanations, comparison tables, and examples to illustrate key concepts. The content is structured into units, providing a thorough overview of Java programming principles and practices.
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
100% found this document useful (1 vote)
9 views35 pages

OOP Java QuestionBank BEU

The document is a comprehensive question bank for a course on Object-Oriented Programming using Java, covering various topics such as OOP concepts, Java data types, control structures, classes, objects, constructors, and access modifiers. It includes detailed questions with explanations, comparison tables, and examples to illustrate key concepts. The content is structured into units, providing a thorough overview of Java programming principles and practices.
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

BIHAR ENGINEERING UNIVERSITY (BEU)

Course Code: 105303

OBJECT ORIENTED PROGRAMMING


USING JAVA
Comprehensive Question Bank
All Units Covered | 7 & 14 Marks Questions | 50+ Questions

Made by Nikhilkumar_absolute

Made by Nikhilkumar_absolute Page


UNIT 1: OOP CONCEPTS AND JAVA
PROGRAMMING

Unit 1: OOP Concepts and Java Programming

Q1. [7 Marks] Define Java and explain its history. Describe the Java Buzzwords in
detail.

• Java: A high-level, platform-independent, object-oriented programming language developed


by Sun Microsystems (now Oracle) in 1991 by James Gosling and his team.
• History Timeline:
– 1991 – Project 'Oak' initiated by James Gosling at Sun Microsystems for embedded systems.
– 1995 – 'Oak' renamed to 'Java'; first public release as Java 1.0.
– 1996 – JDK 1.0 released; Sun launches HotJava browser.
– 1998 – Java 2 (J2SE, J2EE, J2ME) introduced.
– 2004 – Java 5 (Tiger) with generics, annotations, autoboxing.
– 2010 – Oracle acquires Sun Microsystems; Java under Oracle.
– 2017 onwards – Java 9–21 with modules, records, pattern matching.
• Java Buzzwords (11 key features):
– Simple – Easy syntax derived from C/C++, no pointers, automatic memory management.
– Object-Oriented – Everything is an object; supports encapsulation, inheritance, polymorphism,
abstraction.
– Platform-Independent (Write Once Run Anywhere) – Bytecode compiled by JVM, runs on any OS.
– Robust – Strong type checking, exception handling, garbage collection.
– Multithreaded – Built-in support for concurrent execution of threads.
– Architecture Neutral – .class bytecode format works across platforms.
– Interpreted – JVM interprets bytecode at runtime.
– High Performance – JIT (Just-In-Time) compiler improves speed.
– Distributed – Supports networking with RMI and socket programming.
– Secure – No explicit pointer arithmetic; bytecode verifier checks code.
– Dynamic – Classes loaded dynamically as needed at runtime.

Q2. [14 Marks] Explain the differences between Procedural Programming and
Object-Oriented Programming with a detailed comparison table. Also explain the need
for OOP paradigm.

Procedural Programming (PP) follows a top-down approach where the program is divided into
functions. Object-Oriented Programming (OOP) organizes the program into objects that
encapsulate data and behavior together.
Comparison Table: Procedural vs Object-Oriented Programming

Object-Oriented
Feature Procedural Programming
Programming

Approach Top-down, function-focused Bottom-up, object-focused

Basic Unit Function / Procedure Object (data + methods)

Data Security Data is global; less secure Data is encapsulated; more


secure

Reusability Limited (function reuse only) High (inheritance,


polymorphism)

Data & Function Separate entities Combined in objects/classes

Maintenance Harder for large programs Easier due to modularity

Real World Poor mapping to real objects Natural mapping to


real-world entities

Examples C, Pascal, FORTRAN Java, C++, Python, C#

Inheritance Not supported Supported

Polymorphism Not supported Supported (method


overloading/overriding)

Abstraction Limited Fully supported via abstract


classes/interfaces

Problem Solving Algorithmic / step-by-step Modeling entities and their


interactions

• Need for OOP Paradigm:


– Real-world problem modeling: Software can mirror actual entities (Car, Account, Student) more
naturally.
– Code reusability: Inheritance allows existing code to be extended without modification.
– Data hiding: Encapsulation protects internal data, reducing bugs from unintended access.
– Extensibility: New features can be added without disturbing existing code.
– Maintainability: Modular design makes debugging and updating easier.
– Large-scale development: OOP supports team-based development through modular classes.

Q3. [7 Marks] What are the four main features (pillars) of OOP? Explain each with a neat
diagram/sketch.

• The four pillars of OOP:


– 1. Encapsulation – Wrapping data (fields) and methods together in a class; hiding internal details.
– 2. Inheritance – Deriving new classes from existing ones to reuse code.
– 3. Polymorphism – Same method name behaves differently in different contexts.
– 4. Abstraction – Showing only essential features; hiding implementation details.
Diagram – OOP Pillars:
+-----------------------------+
| Object-Oriented Programming |
+-------------+---------------+
+----------+ +------+------+ +-----------+
|Encapsulation| | Inheritance | |Polymorphism|
| (Data Hide) | | (is-a / has-a)| | (Overload/ |
+----------+ +--------------+ | Override) |
+-----------+
+------------+
| Abstraction|
| (Abstract/ |
| Interface) |
+------------+
• Encapsulation example: private fields + public getters/setters.

Made by Nikhilkumar_absolute Page


• Inheritance example: class Dog extends Animal
• Polymorphism example: draw() in Circle, Rectangle, Triangle behaves differently.
• Abstraction example: abstract class Shape with abstract area() method.

Q4. [7 Marks] Explain JDK, JRE, and JVM in detail with a diagram showing their
relationship.

• JVM (Java Virtual Machine):


– Software-based virtual machine that executes Java bytecode (.class files).
– JVM is platform-specific (different JVMs for Windows, Linux, Mac).
– Components: Class Loader, Bytecode Verifier, Interpreter, JIT Compiler, Garbage Collector.
• JRE (Java Runtime Environment):
– JRE = JVM + Java Class Libraries ([Link], [Link], etc.)
– Used to run compiled Java programs; does NOT include development tools.
• JDK (Java Development Kit):
– JDK = JRE + Development Tools (javac compiler, javadoc, jar, debugger).
– Used by developers to write, compile, and debug Java programs.
+----------------------------------------------------------+
| JDK |
| +--------------------------------------------------+ |
| | JRE | |
| | +--------------------------------------------+ | |
| | | JVM | | |
| | | Class Loader | Bytecode Verifier | JIT | | |
| | +--------------------------------------------+ | |
| | Java Class Libraries ([Link], [Link]...) | |
| +--------------------------------------------------+ |
| Development Tools: javac, javadoc, jar, jdb, jshell | |
+----------------------------------------------------------+

Q5. [7 Marks] Describe all Java Data Types with their size and default values. Explain
type casting in Java.

Java has two categories of data types: Primitive (built-in) and Non-Primitive (reference/object
types).
Data Type Size (Bits) Range Default Value Example

byte 8 -128 to 127 0 byte b = 10;

short 16 -32768 to 32767 0 short s = 100;

int 32 -2^31 to 2^31-1 0 int i = 5000;

long 64 -2^63 to 2^63-1 0L long l = 9L;

float 32 ~3.4e-38 to 0.0f float f = 3.14f;


3.4e+38

double 64 ~1.7e-308 to 0.0d double d = 9.99;


1.7e+308

char 16 0 to 65535 '\u0000' char c = 'A';


(Unicode)
boolean 1 true / false false boolean flag =
true;

• Non-Primitive Types: String, Array, Class, Interface — all are reference types (default: null).
• Type Casting:
– Widening (Implicit): Lower to higher type — int to long, float to double. No data loss. Automatic.
– Narrowing (Explicit): Higher to lower — requires explicit cast: int x = (int) 9.99; (result: 9)

Q6. [7 Marks] Explain the control structures in Java: selection (if-else, switch) and
looping (for, while, do-while) with syntax and examples.

• Selection Structures:
– if-else: Executes a block if condition is true, else another block.
if (condition) {
// executed if true
} else {
// executed if false
}
– switch: Multi-way branch based on value of variable.
switch (day) {
case 1: [Link]("Monday"); break;
default: [Link]("Other");
}
• Looping Structures:
– for loop: Used when number of iterations is known.
for (int i = 0; i < 5; i++) { [Link](i); }
– while loop: Checks condition before executing body.
while (i < 5) { [Link](i); i++; }
– do-while loop: Executes body at least once, then checks condition.
do { [Link](i); i++; } while (i < 5);

Q7. [14 Marks] Write and explain a simple Java program demonstrating basic OOP
features including class, object, method, variables, and the compilation/execution
process.

• Compilation & Execution Process:


– 1. Write source code: [Link]
– 2. Compile: javac [Link] → Generates [Link] (bytecode)
– 3. Execute: java HelloWorld → JVM loads & interprets .class file
Source Code (.java)
|
v javac (Compiler)
Bytecode (.class)
|
v java (JVM Interpreter/JIT)
Output / Execution
// [Link]
public class HelloWorld {
// Instance variable
String name;
int rollNo;

// Constructor

Made by Nikhilkumar_absolute Page


HelloWorld(String n, int r) {
[Link] = n;
[Link] = r;
}

// Method
void display() {
[Link]("Name: " + name + ", Roll: " + rollNo);
}

public static void main(String[] args) {


HelloWorld obj = new HelloWorld("Alice", 101);
[Link]();
}
}
• Key elements: class keyword, main method (entry point), new keyword for object creation, this
keyword, [Link] for output.
UNIT 2: OBJECTS, CLASSES, AND CONSTRUCTORS

Unit 2: Objects, Classes, and Constructors

Q8. [7 Marks] Define Class and Object in Java. Explain the 'new' keyword, how objects
are declared, and the lifecycle of an object.

• Class: A blueprint or template that defines the properties (fields) and behaviors (methods) of
objects. Defined using the class keyword.
• Object: A real-world entity created from a class. An object has state (fields), behavior
(methods), and identity (unique reference).
• new keyword: Allocates memory in heap for the object and calls the constructor to initialize it.
class Student { // Class definition
int rollNo; // Field (state)
String name;
void display() { // Method (behavior)
[Link](rollNo + " " + name);
}
}

// Object Declaration & Creation:


Student s1 = new Student(); // Declaration + instantiation
[Link] = 101;
[Link] = "Ravi";
[Link]();
• Object Lifecycle: Creation (new) → Usage (method calls) → Unreachable (no references) →
Garbage Collection (finalize/destroy).

Q9. [14 Marks] What are Constructors in Java? Explain all types of constructors with
examples and diagrams. Also explain Constructor Overloading.

• Constructor: A special method with the same name as the class, no return type, called
automatically when an object is created. Used for initialization.
• Types of Constructors:
– 1. Default Constructor – No parameters; Java provides implicitly if none defined.
– 2. Parameterized Constructor – Accepts arguments to initialize object with specific values.
– 3. Copy Constructor – Creates a new object as a copy of an existing object.
class Box {
int length, breadth, height;

// Default Constructor
Box() { length = breadth = height = 0; }

// Parameterized Constructor
Box(int l, int b, int h) {
[Link] = l; [Link] = b; [Link] = h;
}

// Copy Constructor

Made by Nikhilkumar_absolute Page


Box(Box b) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}
}
• Constructor Overloading: Multiple constructors with the same name but different parameter
lists. Java differentiates by signature.
Type Parameters Purpose Explicit Call

Default None Set default values No

Parameterized One or more args Initialize with custom Yes


values

Copy Object of same class Duplicate object Yes

Q10. [7 Marks] Explain Method Overloading in Java with examples. How does it differ
from Method Overriding?

• Method Overloading (Compile-Time Polymorphism): Same method name, different parameters


(number, type, or order). Resolved at compile time.
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
Feature Method Overloading Method Overriding

Definition Same name, different Same name, same signature


parameters in same class in subclass

Polymorphism Compile-time (Static) Runtime (Dynamic)

Inheritance Not required Required

Return Type Can differ Must be same or covariant

Access Modifier Can be different Cannot reduce visibility

Keyword No special keyword needed Uses @Override annotation

Q11. [7 Marks] Explain Access Modifiers in Java (public, private, protected, default)
with a comparison table and visibility diagram.

• Access modifiers control the visibility/scope of class members (fields, methods, constructors).
Subclass (diff
Modifier Same Class Same Package Other Package
pkg)

private Yes No No No

default (no Yes Yes No No


modifier)
protected Yes Yes Yes No

public Yes Yes Yes Yes

• private: Most restrictive. Use for data hiding (encapsulation).


• default: Package-level access. No keyword needed.
• protected: Allows subclass access even from different packages.
• public: Least restrictive. Accessible from anywhere.

Q12. [7 Marks] Explain the 'this' keyword, static members, garbage collection, and
finalize() method in Java with examples.

• 'this' keyword: Refers to the current object inside an instance method or constructor. Used to
avoid ambiguity between instance variables and parameters.
class Student {
String name;
Student(String name) { [Link] = name; } // '[Link]' = field
}
• Static Members:
– static field: Shared across all objects (class-level variable).
– static method: Can be called without creating an object. Cannot access instance variables directly.
– Example: [Link](), [Link]() are static methods.
• Garbage Collection: Automatic process in Java where JVM reclaims memory of
unreachable/unused objects. Programmer cannot force GC but can call [Link]() as a hint.
• finalize() method: Called by garbage collector before destroying an object. Used to release
external resources (file handles, connections). Deprecated in Java 9+.
protected void finalize() {
[Link]("Object destroyed!");
}

Q13. [14 Marks] Explain Nested and Inner Classes in Java with all types, diagrams, and
examples. Also explain the String class and its important methods.

• Nested Class: A class defined inside another class. Helps logically group classes used together.
• Types of Nested Classes:
– 1. Static Nested Class: Declared static; can be accessed without outer class instance.
– 2. Inner Class (Non-static): Requires outer class instance to access.
– 3. Local Inner Class: Defined inside a method; scope limited to that method.
– 4. Anonymous Inner Class: No name; used for one-time implementation of interface or class.
+------------------------------+
| OuterClass |
| +--------------------------+|
| | StaticNestedClass ||
| +--------------------------+|
| +--------------------------+|
| | InnerClass (non-static) ||
| +--------------------------+|
| void method() { |
| +----------------------+ |
| | LocalInnerClass | |
| +----------------------+ |
| } |
+------------------------------+

Made by Nikhilkumar_absolute Page


• String Class: Immutable sequence of characters. Stored in String Pool.
Method Description Example

length() Returns string length "Java".length() → 4

charAt(i) Returns char at index i "Java".charAt(0) → 'J'

substring(s,e) Extracts substring "Hello".substring(1,3) → 'el'

equals(s) Checks equality [Link](s2)


(case-sensitive)

equalsIgnoreCase(s) Case-insensitive comparison [Link](s2)

toUpperCase() Converts to uppercase "java".toUpperCase() →


'JAVA'

indexOf(ch) First occurrence index "Java".indexOf('a') → 1

replace(old,new) Replace characters "Hello".replace('l','r') → 'Herro'

concat(s) Appends string [Link](s2)

trim() Removes leading/trailing " hi ".trim() → 'hi'


spaces

Q14. [7 Marks] Explain Array of Objects in Java. Write a program to create an array of
Student objects and display their details.

• Array of Objects: An array where each element is an object (reference) of a class.


– Declaration: ClassName[] array = new ClassName[size];
– Each element must be separately instantiated with new.
class Student {
int id; String name;
Student(int i, String n) { id = i; name = n; }
void show() { [Link](id + " " + name); }
}
public class Main {
public static void main(String[] args) {
Student[] arr = new Student[3];
arr[0] = new Student(1, "Alice");
arr[1] = new Student(2, "Bob");
arr[2] = new Student(3, "Charlie");
for (Student s : arr) [Link]();
}
}
UNIT 3: INHERITANCE, INTERFACES AND
PACKAGES

Unit 3: Inheritance, Interfaces and Packages

Q15. [14 Marks] Explain Inheritance in Java in detail — types, hierarchy, member
access rules, super keyword, and preventing inheritance.

• Inheritance: Mechanism where a subclass (child) acquires properties and methods of a


superclass (parent). Uses the 'extends' keyword.
• Benefits: Code reusability, method overriding, hierarchical classification.
• Types of Inheritance:
– 1. Single: One subclass extends one superclass. (A → B)
– 2. Multilevel: A → B → C (chain of inheritance)
– 3. Hierarchical: One superclass, multiple subclasses. (A → B, A → C)
– 4. Multiple: Not directly supported in Java (use Interfaces). C → A, B
– 5. Hybrid: Combination of the above types.
Single: Multilevel: Hierarchical:
[Animal] [Animal] [Animal]
| | / \
[Dog] [Mammal] [Dog] [Cat]
|
[Human]
• Member Access Rules:
– public/protected members → inherited by subclass.
– private members → NOT inherited (accessible only within the defining class).
– default members → accessible only within same package.
• super keyword: Refers to the immediate parent class.
– super() – Calls parent constructor (must be first statement in child constructor).
– [Link]() – Calls overridden parent method.
– [Link] – Accesses parent class field hidden by child.
• Preventing Inheritance:
– final class: Cannot be subclassed. Example: public final class MyClass {}
– final method: Cannot be overridden in subclass.

Q16. [7 Marks] Explain Polymorphism in Java — Dynamic Binding, Method Overriding,


and Abstract Classes with examples.

• Polymorphism: 'Many forms' — the same method call behaves differently for different objects.
• Dynamic Binding (Late Binding): The method call is resolved at runtime based on the actual
object type, not the reference type.
Animal a = new Dog(); // Reference of Animal, object of Dog
[Link](); // Calls Dog's sound() at runtime (dynamic binding)
• Method Overriding: Subclass provides its own implementation of a superclass method with the
same signature.
– Use @Override annotation for clarity and compile-time checking.
– Overridden method must have same name, return type, parameters.
– Access modifier cannot be more restrictive in child.

Made by Nikhilkumar_absolute Page


• Abstract Classes:
– Declared with abstract keyword. Cannot be instantiated directly.
– Can contain both abstract (no body) and concrete (with body) methods.
– Subclass must implement all abstract methods.
abstract class Shape {
abstract double area(); // abstract method
void show() { [Link]("Shape"); } // concrete
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return [Link] * r * r; }
}

Q17. [14 Marks] Explain Interfaces in Java in detail — defining, implementing, accessing
through references, extending interfaces. Compare Interface vs Abstract Class.

• Interface: A fully abstract type that defines a contract (set of methods) that implementing
classes must fulfill. Declared with interface keyword.
• Key rules:
– All methods are public and abstract by default (Java 7).
– All fields are public, static, and final (constants).
– Java 8+: default and static methods allowed.
– Java 9+: private methods allowed.
interface Drawable {
void draw(); // implicitly public abstract
int MAX = 100; // implicitly public static final
}
class Circle implements Drawable {
public void draw() { [Link]("Drawing Circle"); }
}
Drawable d = new Circle(); // interface reference
[Link](); // Runtime polymorphism
• Extending Interface:
– An interface can extend another interface using extends.
interface Shape extends Drawable { double area(); }
Feature Interface Abstract Class

Instantiation Cannot be instantiated Cannot be instantiated

Methods Only abstract (Java 7); Abstract + concrete methods


default/static (Java 8+)

Variables public static final (constants) Any type (instance, static)

Constructors Not allowed Allowed

Inheritance A class can implement A class can extend only one


multiple interfaces class

Access Modifiers Methods are public by default Any access modifier

Use Case 100% abstraction, multiple Partial abstraction, shared


inheritance code

extends/implements interface extends interface class extends abstract class


Q18. [7 Marks] Explain Packages in Java — defining, creating, accessing, CLASSPATH,
and importing packages.

• Package: A namespace that organizes related classes and interfaces. Prevents name conflicts
and controls access.
• Creating a Package:
package [Link]; // First statement in source file
public class MathUtil {
public static int add(int a, int b) { return a + b; }
}
• Accessing Packages:
– 1. Fully qualified name: [Link] obj = new [Link]();
– 2. Import class: import [Link];
– 3. Import all: import [Link].*;
• CLASSPATH: An environment variable that tells JVM where to look for .class files.
– Set via: set CLASSPATH=C:\myproject;.
• Built-in Packages: [Link] (auto-imported), [Link], [Link], [Link], [Link].

Q19. [7 Marks] Explain the Object class in Java and its important methods. What role
does it play in Java's class hierarchy?

• [Link] is the root class of all Java classes. Every class implicitly extends Object.
Method Description

toString() Returns string representation of object; often


overridden.

equals(Object o) Checks logical equality; default checks


reference equality.

hashCode() Returns integer hash code for object (used in


collections).

getClass() Returns runtime class of the object.

clone() Creates copy of object (must implement


Cloneable).

finalize() Called by GC before destroying object.


Deprecated in Java 9.

wait() / notify() / notifyAll() Used in thread synchronization (inter-thread


communication).

Made by Nikhilkumar_absolute Page


UNIT 4: EXCEPTION HANDLING

Unit 4: Exception Handling

Q20. [7 Marks] What is an Exception? Differentiate between Error and Exception in


Java with examples. Explain the Exception Hierarchy.

• Exception: An abnormal condition that disrupts normal program execution. Java provides a
mechanism to handle such conditions gracefully.
Feature Error Exception

Definition Serious problem, usually Abnormal condition, typically


unrecoverable recoverable

Class [Link] [Link]

Cause JVM/System level Program logic (NullPointer,


(OutOfMemoryError, ArrayIndexOutOfBounds)
StackOverflow)

Handling Generally NOT caught Should be caught and


handled

Examples OutOfMemoryError, IOException,


VirtualMachineError ArithmeticException

Checked? Unchecked (extends Both checked and unchecked


Throwable)

• Exception Hierarchy Diagram:


[Link]
/ \
Error Exception
/ \ / \
OutOfMemory StackOverflow IOException RuntimeException
/ / \ \
FileNotFound ArithmeticEx NullPointerEx ArrayIndexEx
• Checked Exceptions: Must be declared in throws clause or caught. E.g., IOException,
SQLException.
• Unchecked Exceptions (RuntimeException): Not mandatory to handle. E.g.,
NullPointerException, ArrayIndexOutOfBoundsException.

Q21. [14 Marks] Explain the usage of try, catch, throw, throws, and finally with
examples. Explain multiple catch clauses and nested try statements.

• try block: Encloses risky code that may throw an exception.


• catch block: Handles the specific exception. Multiple catch blocks allowed.
• finally block: Always executes regardless of exception (used to release resources).
• throw: Used to explicitly throw an exception object inside a method.
• throws: Declares that a method may throw a specified exception; caller must handle it.
// Multiple catch + finally
try {
int[] a = new int[5];
a[10] = 5; // ArrayIndexOutOfBoundsException
int x = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Error: " + [Link]());
} catch (ArithmeticException e) {
[Link]("Math Error: " + [Link]());
} catch (Exception e) { // General catch (always last)
[Link]("General: " + [Link]());
} finally {
[Link]("Cleanup done"); // Always runs
}

// throw example
void checkAge(int age) {
if (age < 18) throw new IllegalArgumentException("Underage!");
}

// throws example
void readFile() throws IOException {
FileReader f = new FileReader("[Link]");
}
• Nested try: A try block inside another try block. Inner catch handles specific exceptions; outer
catch handles broader exceptions.

Q22. [7 Marks] Explain how to create a user-defined (custom) Exception class in Java.
Give a complete example with re-throwing exceptions.

• Custom Exception: Extend Exception (for checked) or RuntimeException (for unchecked).


// Custom Checked Exception
class InsufficientFundsException extends Exception {
double amount;
InsufficientFundsException(double amt) {
super("Insufficient funds: need Rs." + amt);
[Link] = amt;
}
}

class BankAccount {
double balance = 1000;
void withdraw(double amt) throws InsufficientFundsException {
if (amt > balance) throw new InsufficientFundsException(amt - balance);
balance -= amt;
}
}

// Re-throwing: catch, process partially, then throw again


try {
[Link](5000);
} catch (InsufficientFundsException e) {
[Link]("Caught: " + [Link]());
throw e; // re-throw
}

Made by Nikhilkumar_absolute Page


Q23. [7 Marks] Differentiate between Checked and Unchecked exceptions in Java with
examples and a table.

Feature Checked Exceptions Unchecked Exceptions

Inherits from [Link] [Link]

Detection Detected at compile time Detected at runtime

Mandatory handling Yes — try/catch or throws No — optional

Examples IOException, NullPointerException,


SQLException, ArithmeticException,
ClassNotFoundException ArrayIndexOutOfBoundsException

Caused by External resources (files, Programming errors (null, wrong


DB) index)
UNIT 5: INTRODUCTION TO MULTITHREADING

Unit 5: Introduction to Multithreading

Q24. [7 Marks] What is Multithreading? Differentiate between Multiple Processes and


Multiple Threads. Explain Thread States with a diagram.

• Multithreading: Executing multiple threads simultaneously within a single process, sharing the
same memory space.
Feature Multiple Processes Multiple Threads

Definition Independent programs Multiple execution paths in


running concurrently same program

Memory Separate memory space for Shared memory space within


each process the process

Communication Complex (IPC — pipes, Simple (shared variables,


sockets) synchronized blocks)

Overhead High (process creation is Low (threads are lightweight)


expensive)

Crash Impact One process crash doesn't One thread crash can affect
affect others the whole process

Context Switch Slow Fast

Example Running browser + music Downloading + rendering in


player browser simultaneously

• Thread States (Life Cycle):


[New]
| start()
v
[Runnable] <------- notify() / notifyAll()
| CPU allocated ^
v |
[Running] --- wait() --> [Waiting/Blocked]
| sleep()/join()
v
[Timed Waiting]
|
v run() completes
[Terminated/Dead]
– New: Thread object created but start() not called.
– Runnable: Thread is ready to run; waiting for CPU.
– Running: Thread is executing.
– Waiting/Blocked: Waiting for resource or notification.
– Timed Waiting: Waiting for specified time (sleep(), join()).
– Terminated: Thread has finished execution.

Q25. [14 Marks] Explain the two ways to create threads in Java — extending Thread

Made by Nikhilkumar_absolute Page


class and implementing Runnable interface. Compare both approaches.

• Method 1: Extending Thread class


class MyThread extends Thread {
public void run() {
[Link]("Thread: " + [Link]().getName());
}
}
MyThread t = new MyThread();
[Link](); // Starts thread (calls run() in new thread)
• Method 2: Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread running");
}
}
Thread t = new Thread(new MyRunnable());
[Link]();
Feature extends Thread implements Runnable

Inheritance Cannot extend any other Can extend other class


class simultaneously

Flexibility Less flexible More flexible (preferred


approach)

Object Sharing Separate Thread objects Same Runnable object


shared by multiple threads

Code Reuse Limited Better (separation of task and


thread)

Java convention Less preferred Preferred (better OOP


design)

Q26. [7 Marks] Explain Thread Priorities, Thread Interruption, and Synchronization in


Java with examples.

• Thread Priority: Integer value (1–10) determining which thread gets CPU first. Higher priority =
higher preference.
– MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10
– Set: [Link](Thread.MAX_PRIORITY); Get: [Link]()
• Thread Interruption: Request to stop a thread gracefully.
[Link](); // Sets interrupt flag
if ([Link]()) { /* stop running */ }
• Synchronization: Mechanism to ensure only one thread accesses a shared resource at a time.
Prevents race conditions and data inconsistency.
– synchronized method: Entire method is locked.
– synchronized block: Only specific block is locked (more efficient).
class Counter {
int count = 0;
synchronized void increment() { count++; } // Synchronized method
}
// Synchronized block
synchronized(this) { count++; }

Q27. [7 Marks] Explain Inter-Thread Communication in Java using wait(), notify(), and
notifyAll() with the Producer-Consumer problem example.

• Inter-Thread Communication: Mechanism for threads to coordinate/communicate with each


other.
Method Description

wait() Releases lock and waits until notified. Must


be inside synchronized block.

notify() Wakes up one thread waiting on the same


object.

notifyAll() Wakes up all threads waiting on the same


object.
class SharedResource {
int item; boolean available = false;
synchronized void produce(int i) throws InterruptedException {
while (available) wait(); // Wait if item not consumed
item = i; available = true;
notify(); // Notify consumer
}
synchronized void consume() throws InterruptedException {
while (!available) wait(); // Wait if nothing produced
[Link]("Consumed: " + item);
available = false;
notify(); // Notify producer
}
}

Made by Nikhilkumar_absolute Page


UNIT 6: FILES, COLLECTIONS FRAMEWORK &
DATABASE

Unit 6: Files, Collections Framework and Database

Q28. [7 Marks] Explain Streams in Java. Differentiate between Byte Streams and
Character Streams with class hierarchies.

• Stream: A sequence of data flowing from a source (input) to a destination (output).


Feature Byte Streams Character Streams

Unit of Transfer 8-bit bytes 16-bit Unicode characters

Base Classes InputStream / OutputStream Reader / Writer

Use Case Binary data (images, audio) Text data (files, strings)

Key Classes FileInputStream, FileReader, FileWriter,


FileOutputStream, BufferedReader, PrintWriter
BufferedInputStream

Efficiency Works with raw bytes Handles encoding/decoding


automatically
Byte Stream Hierarchy:
InputStream OutputStream
/ | \ / | \
FileIS BufferedIS DataIS FileOS BufferedOS DataOS

Character Stream Hierarchy:


Reader Writer
/ \ / \
FileReader BufferedReader FileWriter BufferedWriter

Q29. [7 Marks] Explain Text and Binary I/O in Java with examples. Also explain
Random Access File operations.

• Text I/O: Used for reading/writing human-readable text. Uses BufferedReader and PrintWriter.
// Writing text
PrintWriter pw = new PrintWriter(new FileWriter("[Link]"));
[Link]("Hello Java"); [Link]();

// Reading text
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line = [Link](); [Link]();
• Binary I/O: Reads/writes primitive data types in binary format using
DataInputStream/DataOutputStream.
DataOutputStream dos = new DataOutputStream(new FileOutputStream("[Link]"));
[Link](42); [Link](3.14); [Link]();
• Random Access File: Allows reading/writing at any position in a file using seek().
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");
[Link](10); // Move pointer to byte 10
[Link](999); [Link]();

Q30. [7 Marks] Explain the File class in Java. What are its important methods for file
management? Write a program to demonstrate file operations.

• [Link]: Represents a file or directory path in the filesystem. Does NOT handle I/O directly —
only file metadata.
Method Description

exists() Returns true if file/directory exists

getName() Returns name of file/directory

getPath() Returns path of file

length() Returns file size in bytes

createNewFile() Creates new empty file; returns boolean

delete() Deletes file/directory

mkdir() Creates directory

list() Returns array of file/dir names in directory

isFile() Returns true if it is a file

isDirectory() Returns true if it is a directory


File f = new File("[Link]");
if ([Link]()) [Link]("Created: " + [Link]());
[Link]("Size: " + [Link]() + " bytes");
[Link]();

Q31. [14 Marks] Explain the Java Collections Framework in detail — hierarchy,
interfaces, and classes (ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue,
ArrayDeque).

• Collections Framework: A unified architecture for storing and manipulating groups of objects.
Package: [Link].
<<interface>> Iterable
|
<<interface>> Collection
/ | \
<<interface>> <<interface>> <<interface>>
List Set Queue
/ \ / \ / \
ArrayList LinkedList HashSet TreeSet PriorityQueue ArrayDeque
Allows
Class Ordered Thread-Safe Null Elements
Duplicates

ArrayList Yes Insertion order No Yes

LinkedList Yes Insertion order No Yes

HashSet No No (unordered) No One null

Made by Nikhilkumar_absolute Page


TreeSet No Sorted No No
(natural/comparator)

PriorityQueue Yes Priority order No No

ArrayDeque Yes Insertion order No No


(deque)
ArrayList<String> list = new ArrayList<>();
[Link]("Apple"); [Link]("Banana"); [Link]("Apple");
[Link](list); // [Apple, Banana, Apple]

HashSet<Integer> set = new HashSet<>();


[Link](3); [Link](1); [Link](3);
[Link](set); // [1, 3] (no duplicates)

TreeSet<Integer> ts = new TreeSet<>();


[Link](5); [Link](2); [Link](8);
[Link](ts); // [2, 5, 8] (sorted)

Q32. [14 Marks] Explain JDBC in Java — how to connect to a database, query it, process
results, and update data. Include the complete JDBC architecture.

• JDBC (Java Database Connectivity): API for connecting Java applications to relational
databases (MySQL, Oracle, PostgreSQL, etc.).
Java Application
|
JDBC API ([Link] package)
|
JDBC Driver Manager
|
JDBC Driver (Type 1 / 2 / 3 / 4)
|
Database (MySQL / Oracle / PostgreSQL)
• Steps to Connect & Query:
– 1. Load Driver: [Link]("[Link]");
– 2. Create Connection: Connection con = [Link](url, user, pass);
– 3. Create Statement: Statement stmt = [Link]();
– 4. Execute Query: ResultSet rs = [Link]("SELECT * FROM students");
– 5. Process Results: while ([Link]()) { [Link]([Link](1)); }
– 6. Close: [Link](); [Link](); [Link]();
import [Link].*;
public class JDBCDemo {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/college";
Connection con = [Link](url, "root", "pass");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT id, name FROM students");
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
// Update
PreparedStatement ps = [Link](
"UPDATE students SET name=? WHERE id=?");
[Link](1, "Ravi"); [Link](2, 1);
[Link]();
[Link](); [Link](); [Link]();
}
}
Interface Purpose

DriverManager Manages JDBC drivers, creates connections

Connection Represents a session with the database

Statement Executes static SQL queries

PreparedStatement Pre-compiled SQL with parameters; prevents


SQL injection

ResultSet Holds query results; iterate with next()

CallableStatement Calls stored procedures in database

Made by Nikhilkumar_absolute Page


ADDITIONAL IMPORTANT QUESTIONS
Q33. [7 Marks] What is method binding in Java? Explain Early Binding vs Late Binding
with examples.

Feature Early Binding (Static) Late Binding (Dynamic)

Resolution Compile time Runtime

Polymorphism Overloading Overriding

Keyword No special keyword Based on actual object type

Performance Faster Slightly slower

Example int add(int, int) vs add(double, Animal ref = new Dog();


double) [Link]();

Q34. [7 Marks] Explain Passing Object as Parameter and Returning an Object from a
method in Java with examples.

• Passing Object as Parameter: The reference of the object is passed. Changes inside the
method affect the original object.
class Rectangle {
int w, h;
Rectangle(int w, int h) { this.w = w; this.h = h; }
int area() { return w * h; }
// Returning object from method
Rectangle scale(int factor) {
return new Rectangle(w * factor, h * factor);
}
}
Rectangle r1 = new Rectangle(3, 4);
Rectangle r2 = [Link](2); // Returns new object

Q35. [7 Marks] Explain the 'final' keyword in Java. How is it used with variables,
methods, and classes?

Usage Meaning Example

final variable Value cannot be changed final int MAX = 100;


after initialization (constant)

final method Cannot be overridden by any public final void show() {}


subclass

final class Cannot be public final class String {}


subclassed/extended

final parameter Parameter value cannot be void show(final int x) {}


modified in method
Q36. [7 Marks] Describe Java's Collection Interfaces — Collection, List, Set, Queue —
and their key differences.

Interface Extends Key Property Implementations

Iterable - Root; enables -


for-each loop

Collection Iterable Basic group of All collection classes


objects

List Collection Ordered, indexed, ArrayList, LinkedList,


duplicates allowed Vector

Set Collection No duplicates, HashSet,


unordered LinkedHashSet,
TreeSet

Queue Collection FIFO ordering PriorityQueue,


ArrayDeque

Deque Queue Double-ended queue ArrayDeque,


LinkedList

Map - Key-value pairs, HashMap, TreeMap,


unique keys LinkedHashMap

Q37. [7 Marks] Write a Java program demonstrating Multilevel Inheritance with super
keyword usage and method overriding.

class Animal {
String name;
Animal(String name) { [Link] = name; }
void sound() { [Link](name + " makes a sound"); }
}

class Mammal extends Animal {


Mammal(String name) { super(name); } // calls Animal constructor
void breathe() { [Link](name + " breathes air"); }
}

class Dog extends Mammal {


Dog(String name) { super(name); }
@Override
void sound() {
[Link](); // calls Animal's sound()
[Link](name + " says: Woof!");
}
}
Dog d = new Dog("Rex");
[Link](); [Link]();

Q38. [14 Marks] Explain Abstract Classes vs Interfaces — when to use each. Write a
complete program demonstrating both.

Made by Nikhilkumar_absolute Page


Use Abstract Class when: classes share common code and state (fields). Use Interface when: you
need to define a contract, especially for multiple types of unrelated classes.
// Interface
interface Flyable {
void fly();
default void land() { [Link]("Landing..."); }
}

// Abstract class
abstract class Vehicle {
String brand;
Vehicle(String b) { brand = b; }
abstract void move(); // abstract
void fuel() { [Link](brand + " needs fuel"); } // concrete
}

class FlyingCar extends Vehicle implements Flyable {


FlyingCar(String b) { super(b); }
public void move() { [Link](brand + " drives"); }
public void fly() { [Link](brand + " flies!"); }
}
FlyingCar fc = new FlyingCar("AeroCar");
[Link](); [Link](); [Link](); [Link]();

Q39. [7 Marks] Explain Thread sleep(), join(), and yield() methods with code examples.

Method Description Signature

sleep(ms) Pauses current thread for [Link](1000);


specified milliseconds.
Throws InterruptedException.

join() Calling thread waits until this [Link]();


thread completes execution.

yield() Hints scheduler to give CPU [Link]();


to other threads of same
priority. No guarantee.
Thread t1 = new Thread(() -> {
for (int i = 0; i < 3; i++) {
[Link]("T1: " + i);
try { [Link](500); } catch (Exception e) {}
}
});
[Link]();
[Link](); // Main thread waits for t1 to finish
[Link]("Main continues after T1");

Q40. [7 Marks] Explain the difference between ArrayList and LinkedList in Java with
memory diagrams and use cases.

Feature ArrayList LinkedList


Internal Structure Dynamic array (contiguous Doubly linked list (nodes with
memory) prev/next pointers)

Access O(1) – Random access via O(n) – Sequential traversal


index needed

Insertion/Deletion O(n) – Shifting required O(1) – Only pointer update


needed (if reference known)

Memory Less overhead (only data) More overhead (data + 2


pointers per node)

Implements List, Cloneable, Serializable List, Deque, Cloneable,


Serializable

Best Use Case Frequent read/search Frequent insert/delete


operations operations

Null Allowed Yes Yes


ArrayList: [ A | B | C | D ] (contiguous array)

LinkedList: [A|next] --> [B|prev|next] --> [C|prev|next] --> [D|prev]

Q41. [7 Marks] What is the difference between HashMap and TreeMap? Explain with
examples.

Feature HashMap TreeMap

Ordering No ordering guarantee Sorted by key (natural or


Comparator)

Implementation Hash table Red-Black Tree

Performance O(1) average for get/put O(log n) for get/put

Null Keys One null key allowed No null keys allowed

Use Case Fast lookup without order Sorted key traversal needed
needed

Q42. [7 Marks] Explain PreparedStatement in JDBC. How does it prevent SQL


Injection? Compare with Statement.

Feature Statement PreparedStatement

Compilation Compiled each execution Pre-compiled once;


executed multiple times

Parameters Literal values in SQL string Placeholders (?) filled with


setXxx()

SQL Injection Vulnerable Safe — parameters treated as


data, not SQL

Performance Slower for repeated Faster for repeated execution


execution

Made by Nikhilkumar_absolute Page


Usage One-time, simple queries Parameterized, repeated
queries
// SQL Injection vulnerable (Statement):
String q = "SELECT * FROM users WHERE name='" + input + "'";

// Safe (PreparedStatement):
PreparedStatement ps = [Link](
"SELECT * FROM users WHERE name=?");
[Link](1, input); // Properly escaped
ResultSet rs = [Link]();

Q43. [7 Marks] Explain the concept of Exception Propagation in Java with a diagram
and example.

• Exception Propagation: When an exception is not caught in the current method, it propagates
to the calling method up the call stack until caught or JVM handles it.
main() calls methodA()
methodA() calls methodB()
methodB() throws Exception
↑ not caught in methodB
Exception propagates to methodA
↑ not caught in methodA
Exception propagates to main()
main() catches it (or JVM terminates)
void methodB() throws ArithmeticException { int x = 1/0; }
void methodA() { methodB(); } // exception propagates
void main() { try { methodA(); } catch(ArithmeticException e) { ... } }

Q44. [14 Marks] Explain the Iterator and for-each loop usage with Collections. Write a
program using Iterator to traverse ArrayList and remove elements.

• Iterator: An object from [Link] that allows traversal of collections without exposing
internal structure.
• Methods: hasNext() — returns true if more elements; next() — returns next element; remove() —
removes last element returned.
ArrayList<String> fruits = new ArrayList<>();
[Link]("Apple"); [Link]("Banana"); [Link]("Mango");

// Using Iterator
Iterator<String> it = [Link]();
while ([Link]()) {
String f = [Link]();
if ([Link]("Banana")) [Link](); // Safe removal during iteration
}
[Link](fruits); // [Apple, Mango]

// for-each loop (uses Iterator internally)


for (String fruit : fruits) {
[Link](fruit);
}

Q45. [7 Marks] What are the advantages of the OOP paradigm over procedural
programming? Explain with practical real-world scenarios.

• Real-world modeling: Objects like Car, BankAccount, Student directly map to real entities.
• Encapsulation: A BankAccount hides its balance; only deposit()/withdraw() methods expose it.
• Inheritance: ElectricCar extends Car — inherits engine, wheels; adds battery.
• Polymorphism: A Shape[] can hold Circle, Square — all have area() but compute differently.
• Maintainability: Changing Circle's area calculation doesn't affect Square.
• Security: private data cannot be directly accessed from outside the class.

Q46. [7 Marks] Explain the difference between String, StringBuffer, and StringBuilder in
Java.

Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread Safety Yes (immutable) Yes (synchronized) No (not


synchronized)

Performance Slow (new obj on Moderate Fast


change)

Usage Constant strings Multi-threaded Single-threaded


environment operations

Storage String Pool (heap) Heap Heap

Q47. [7 Marks] Write a Java program to demonstrate File reading and writing using
BufferedReader and BufferedWriter.

import [Link].*;
public class FileDemo {
public static void main(String[] args) throws IOException {
// Writing
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));
[Link]("Java is powerful.");
[Link]();
[Link]("OOP makes coding elegant.");
[Link]();

// Reading
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
}
}

Q48. [14 Marks] Explain Deadlock in multithreading. What are its conditions and how
can it be prevented in Java?

Made by Nikhilkumar_absolute Page


• Deadlock: A situation where two or more threads are blocked forever, each waiting for a lock
held by the other.
Thread 1 holds Lock A, waits for Lock B
Thread 2 holds Lock B, waits for Lock A
--> Neither can proceed --> DEADLOCK
• Four Conditions for Deadlock (Coffman Conditions):
– 1. Mutual Exclusion: Resource can be held by only one thread.
– 2. Hold and Wait: Thread holds one lock and waits for another.
– 3. No Preemption: Locks cannot be forcibly taken from a thread.
– 4. Circular Wait: Thread A waits for B, B waits for A.
• Prevention Strategies:
– Lock ordering: Always acquire locks in the same fixed order.
– tryLock(): Use [Link]() with timeout.
– Avoid nested locks: Minimize use of multiple locks.
– Use thread-safe collections: ConcurrentHashMap, etc.

Q49. [7 Marks] Explain JDBC Driver Types (Type 1 to Type 4) with a comparison table.

Type Name Description Performance

Type 1 JDBC-ODBC Bridge Translates JDBC calls Slowest


to ODBC; requires
ODBC driver

Type 2 Native API Driver Uses native DB client Moderate


libraries; translates
JDBC to native API

Type 3 Network Protocol Translates JDBC to Moderate


Driver middleware server
protocol

Type 4 Thin Driver (Pure Direct connection to Fastest (Preferred)


Java) DB using Java; no
native code

Q50. [14 Marks] Write a comprehensive Java program that demonstrates: class, object,
constructor overloading, inheritance, method overriding, interface, and exception
handling together.

// Interface
interface Printable { void print(); }

// Abstract superclass
abstract class Employee {
String name; int id;
Employee(String n, int i) { name = n; id = i; }
Employee(String n) { this(n, 0); } // Constructor overloading
abstract double salary();
}

// Concrete subclass
class Developer extends Employee implements Printable {
double hourlyRate; int hours;
Developer(String n, int i, double r, int h) {
super(n, i); hourlyRate = r; hours = h;
}
@Override
public double salary() { return hourlyRate * hours; }
@Override
public void print() {
[Link]("Dev: %s | ID: %d | Salary: %.2f%n", name, id,
salary());
}
}

public class CompanyApp {


public static void main(String[] args) {
try {
Developer dev = new Developer("Alice", 101, 500.0, 160);
[Link]();
if ([Link]() < 0) throw new ArithmeticException("Negative
salary!");
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Program completed.");
}
}
}

Made by Nikhilkumar_absolute Page


QUICK REFERENCE — DEFINITION SUMMARY
Term Definition

Class A blueprint/template defining properties and


behavior of objects.

Object An instance of a class with state, behavior,


and identity.

Encapsulation Bundling data and methods together; hiding


internal details using access modifiers.

Inheritance Mechanism for a subclass to acquire


properties/methods of a superclass
(extends).

Polymorphism Ability of a method/object to take many


forms (overloading = compile-time;
overriding = runtime).

Abstraction Hiding implementation details; showing only


essential features via abstract class/interface.

Constructor Special method called at object creation;


same name as class, no return type.

this Reference to the current object inside a


method or constructor.

super Reference to the immediate parent class;


used to call parent constructor or method.

final Makes variable constant, prevents method


override, prevents class subclassing.

static Member belongs to class (not instance);


shared across all objects.

Interface Fully abstract type defining a contract; class


implements interface.

Abstract Class Class with at least one abstract method;


cannot be instantiated.

Package Namespace grouping related


classes/interfaces; controls access and
prevents conflicts.

Exception Runtime abnormality disrupting normal flow;


caught using try-catch.

checked Exception Checked at compile time; must be caught or


declared with throws.

Unchecked Exception Subclass of RuntimeException; not


mandatory to handle.

Thread Lightweight sub-process; enables concurrent


execution within a program.
Synchronization Controls thread access to shared resources;
prevents race conditions.

Stream Sequence of data; byte stream (8-bit) or


character stream (16-bit Unicode).

JDBC Java Database Connectivity; API to connect


Java programs to relational databases.

Collections [Link] framework providing data structures:


List, Set, Queue, Map.

ArrayList Resizable array; O(1) access; allows


duplicates and null.

HashMap Key-value store; O(1) average operations;


one null key allowed.

JVM Java Virtual Machine; executes bytecode;


platform-specific.

JRE Java Runtime Environment; JVM + class


libraries.

JDK Java Development Kit; JRE + development


tools (javac, javadoc, jdb).

Garbage Collection Automatic memory management in Java;


JVM reclaims memory of unreachable
objects.

Method Overloading Same method name, different parameters in


same class; resolved at compile time.

Method Overriding Subclass provides new implementation of


superclass method; resolved at runtime.

Made by Nikhilkumar_absolute Page


IMPORTANT FACTS, FORMULAS & MEMORY AIDS
Java Primitive Data Type Sizes:
byte(1B) < short(2B) < int(4B) < long(8B) < float(4B) < double(8B) < char(2B) < boolean(1bit)
Thread Priority Range:
MIN_PRIORITY = 1 | NORM_PRIORITY = 5 | MAX_PRIORITY = 10 | Default = 5
Access Modifier Scope (ascending):
private < default < protected < public
Exception Hierarchy Key:
Throwable → Error (unrecoverable) | Exception → RuntimeException (unchecked) | Others
(checked)
Collections Complexity:
ArrayList: get O(1), add O(1) amortized, remove O(n) | LinkedList: add/remove O(1), get O(n)
HashMap: get/put/remove O(1) avg | TreeMap: O(log n) all ops | HashSet: O(1) avg
JDBC Steps Mnemonic: 'LCSERC':
Load driver → Create Connection → Statement → Execute → ResultSet → Close
OOP Pillars Mnemonic: 'APIE':
A – Abstraction | P – Polymorphism | I – Inheritance | E – Encapsulation
String vs StringBuffer vs StringBuilder:
String (immutable, thread-safe) | StringBuffer (mutable, thread-safe, slow) | StringBuilder (mutable,
not thread-safe, fast)
try-catch-finally Rules:
1. try must be followed by catch or finally (or both). 2. finally always executes (even with
return/exception). 3. Multiple catch blocks: most specific first, most general last.
END OF QUESTION BANK

Made by Nikhilkumar_absolute

Made by Nikhilkumar_absolute Page

You might also like