Java Programming
Complete Question Bank with Answers
Topics: Basics | OOP | Collections | Exception Handling | Threads | File I/O | JDBC
TOPIC 1: Java Basics & Architecture
───────────────────────────────────────────────────────────────────────────────
─
Q1. What is platform independence in Java?
Ans: Platform independence means Java code written once can run on any operating system without
modification. Java compiles source code into bytecode (.class file), and the JVM (Java Virtual Machine)
on each platform executes this bytecode. This is also called WORA — Write Once, Run Anywhere.
Q2. What is WORA?
Ans: WORA stands for "Write Once, Run Anywhere." Java programs are compiled into bytecode that
can run on any platform that has a JVM installed, without recompiling.
Q3. What is JVM (Java Virtual Machine)?
Ans: JVM is an abstract machine that provides a runtime environment to execute Java bytecode. It
performs memory management, garbage collection, and translates bytecode to machine-specific
instructions. JVM is platform-dependent but makes Java platform-independent.
Q4. What is JRE (Java Runtime Environment)?
Ans: JRE = JVM + Libraries (class libraries). It provides the minimum requirements to run a Java
application. It does NOT include development tools like compiler.
Q5. What is JDK (Java Development Kit)?
Ans: JDK = JRE + Development Tools (javac compiler, debugger, javadoc, etc.). It is used by
developers to write, compile, and debug Java programs.
Hierarchy: JDK ⊃ JRE ⊃ JVM
Q6. What is Portability in Java?
Ans: Portability means the same Java program can be moved (ported) and executed on different
hardware/OS environments without changes. Java achieves portability through bytecode and JVM.
Q7. Who created Java?
Ans: Java was created by James Gosling at Sun Microsystems in 1995. It was later acquired by Oracle
Corporation.
Q8. What are the main features of Java?
Ans: Main features of Java:
1. Platform Independent – WORA via bytecode and JVM
2. Object-Oriented – Everything is an object (class, inheritance, polymorphism, encapsulation)
3. Simple – Familiar C/C++ syntax, no pointers
4. Secure – No explicit pointers; bytecode verifier checks code
5. Robust – Strong type checking, exception handling, garbage collection
6. Multithreaded – Built-in support for threads
7. Distributed – Supports networking (RMI, CORBA)
8. High Performance – JIT compiler improves speed
9. Dynamic – Classes loaded at runtime
Q9. What is a Package in Java?
Ans: A package is a namespace that organizes a set of related classes and interfaces. Packages
prevent naming conflicts and help in access control.
Example: [Link], [Link], [Link]
package mypackage;
import [Link];
Q10. Write the syntax of a Java program and explain the structure.
// 1. Package declaration (optional)
package [Link];
// 2. Import statements
import [Link];
// 3. Class definition
public class HelloWorld {
// 4. Main method - entry point
public static void main(String[] args) {
// 5. Statements
[Link]("Hello, World!");
}
}
Explanation:
• public class HelloWorld → class name must match file name
• public static void main(String[] args) → JVM calls this to start execution
• [Link]() → prints to console
TOPIC 2: OOP — Class, Object & Constructor
───────────────────────────────────────────────────────────────────────────────
─
Q11. What is a Class in Java?
Ans: A class is a blueprint/template for creating objects. It defines attributes (fields) and behaviors
(methods) that its objects will have.
class Car {
String make; // attribute
int year;
void drive() { // behavior
[Link]("Driving...");
}
}
Q12. What is an Object in Java?
Ans: An object is an instance of a class. It is a real-world entity that has state (attributes) and behavior
(methods). Objects are created using the 'new' keyword.
Car myCar = new Car(); // object creation
[Link] = "Toyota"; // setting attribute
Q13. Write the syntax to create an object.
ClassName objectName = new ClassName();
// Example:
Car c = new Car();
Q14. What is the difference between a Class and an Object?
Class: A blueprint/template (logical entity). Defined once. No memory allocated.
Object: An instance of a class (physical entity). Multiple objects can be created. Memory is allocated.
Example: 'Car' is a class. 'myCar', 'yourCar' are objects of class Car.
Q15. What is a Constructor?
Ans: A constructor is a special method that is automatically called when an object is created. It is used
to initialize object attributes. A constructor has the same name as the class and has no return type.
Q16. What is the Default Constructor?
Ans: A default constructor is a constructor with no parameters. If you don't write any constructor, Java
automatically provides a default constructor that initializes fields to default values (0, null, false).
class Car {
String make;
Car() { // default constructor
make = "Unknown";
}
}
Q17. Can a class have more than one constructor? (Constructor Overloading)
Ans: Yes! A class can have multiple constructors with different parameters. This is called Constructor
Overloading.
class Car {
String make; String model; int year;
Car() { // default
make = "Unknown"; model = "N/A"; year = 0;
}
Car(String m, String mo, int y) { // parameterized
make = m; model = mo; year = y;
}
}
// Usage:
Car c1 = new Car();
Car c2 = new Car("Toyota", "Corolla", 2023);
Q18. What is the use of the main() method in Java?
Ans: main() is the entry point of any Java program. JVM calls main() to start execution. Signature:
public static void main(String[] args)
• public → accessible by JVM from outside
• static → can be called without creating an object
• void → no return value
• String[] args → command-line arguments
Q19. What is Static in Java?
Ans: The 'static' keyword means the member belongs to the class itself, not to any specific object.
Static members are shared among all instances.
class Counter {
static int count = 0; // shared by all objects
Counter() { count++; }
}
// Access: [Link] (no object needed)
Q20. What is the use of a Constructor in a class?
Ans: Constructors are used to: (1) Initialize object attributes when an object is created. (2) Allocate
resources. (3) Set default values. They ensure an object is always in a valid state.
Q21. What is the default parent class of every Java class?
Ans: [Link] is the default parent class of every Java class. If a class doesn't explicitly extend
any class, it implicitly extends Object. Object provides methods like toString(), equals(), hashCode(),
getClass().
Programs: Car Class & Person-Student Inheritance
Q22. Design a Car class with make, model, year. Create objects using both constructors.
class Car {
String make, model;
int year;
// Default constructor
Car() {
make = "Unknown"; model = "Unknown"; year = 0;
}
// Parameterized constructor
Car(String make, String model, int year) {
[Link] = make;
[Link] = model;
[Link] = year;
}
void display() {
[Link](year + " " + make + " " + model);
}
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car("Toyota", "Corolla", 2023);
[Link](); // 0 Unknown Unknown
[Link](); // 2023 Toyota Corolla
}
}
TOPIC 3: Inheritance
───────────────────────────────────────────────────────────────────────────────
─
Q23. What is Inheritance? Define and give example.
Ans: Inheritance is the mechanism by which one class (child/subclass) acquires the properties and
behaviors of another class (parent/superclass). It promotes code reuse.
Keyword: extends
class Animal {
void eat() { [Link]("Animal eats"); }
}
class Dog extends Animal { // Dog inherits from Animal
void bark() { [Link]("Dog barks"); }
}
Dog d = new Dog();
[Link](); // inherited method
[Link](); // own method
Q24. Explain types of Inheritance in Java.
1. Single Inheritance: One child class inherits from one parent.
class B extends A {}
2. Multilevel Inheritance: A chain of inheritance.
class A{} class B extends A{} class C extends B{}
3. Hierarchical Inheritance: Multiple child classes inherit from one parent.
class A{} class B extends A{} class C extends A{}
4. Multiple Inheritance: Java does NOT support multiple class inheritance (to avoid Diamond problem).
Achieved via interfaces.
interface A{} interface B{} class C implements A, B{}
Q25. Design a Person → Student inheritance program.
class Person {
String name; int age;
Person(String name, int age) {
[Link] = name; [Link] = age;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
class Student extends Person {
String studentId, major;
Student(String name, int age, String id, String major) {
super(name, age); // call parent constructor
[Link] = id;
[Link] = major;
}
void display() {
[Link]();
[Link]("ID: " + studentId + ", Major: " + major);
}
public static void main(String[] args) {
Student s = new Student("Ravi", 20, "S101", "CS");
[Link]();
}
}
Q26. Write a program to demonstrate inheritance and constructors in base and derived classes.
class Base {
Base() { [Link]("Base constructor called"); }
void show() { [Link]("Base show()"); }
}
class Derived extends Base {
Derived() {
super(); // calls Base()
[Link]("Derived constructor called");
}
public static void main(String[] args) {
Derived d = new Derived();
[Link]();
}
}
// Output:
// Base constructor called
// Derived constructor called
// Base show()
TOPIC 4: Polymorphism — Method Overloading &
Overriding
───────────────────────────────────────────────────────────────────────────────
─
Q27. What is Method Overloading?
Ans: Method overloading means having multiple methods with the same name but different parameters
(number, type, or order) in the same class. It is compile-time (static) polymorphism.
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; }
}
Calculator c = new Calculator();
[Link](2, 3); // calls first
[Link](2.5, 3.5); // calls second
Q28. What is Method Overriding?
Ans: Method overriding means a subclass provides its own implementation of a method that is already
defined in the parent class. Same name, same parameters. It is runtime (dynamic) polymorphism.
class Animal {
void sound() { [Link]("Some sound"); }
}
class Cat extends Animal {
@Override
void sound() { [Link]("Meow"); } // overrides
}
Animal a = new Cat();
[Link](); // Output: Meow (runtime polymorphism)
Q29. Difference between Method Overloading and Method Overriding
Overloading: Same class, different parameters, compile-time, no @Override needed.
Overriding: Parent-child classes, same parameters, runtime, @Override annotation used.
Overloading = 'many forms in same class'. Overriding = 'redefine parent method in child'.
Q30. What is Static vs Dynamic Binding?
Static Binding (Early Binding): Method call resolved at compile time. Example: method overloading,
static methods, final methods.
Dynamic Binding (Late Binding): Method call resolved at runtime. Example: method overriding — JVM
decides which version to call based on actual object type.
TOPIC 5: Encapsulation & Access Specifiers
───────────────────────────────────────────────────────────────────────────────
─
Q31. What is Encapsulation?
Ans: Encapsulation is the process of wrapping data (fields) and methods into a single unit (class), and
restricting direct access to data using access modifiers. Data is accessed only through public
getter/setter methods.
Q32. Implement a program to demonstrate Encapsulation.
class BankAccount {
private double balance; // private - hidden
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) balance -= amount;
else [Link]("Insufficient funds!");
}
public double getBalance() { return balance; } // getter
public static void main(String[] args) {
BankAccount acc = new BankAccount();
[Link](5000);
[Link](2000);
[Link]("Balance: " + [Link]()); // 3000.0
}
}
Q33. What are Access Specifiers in Java?
Access specifiers control visibility of class members:
• private → accessible only within the class
• default (no keyword) → accessible within same package
• protected → accessible within package + subclasses
• public → accessible from everywhere
TOPIC 6: Abstract Classes & Interfaces
───────────────────────────────────────────────────────────────────────────────
─
Q34. What is an Abstract Class?
Ans: An abstract class cannot be instantiated. It may have abstract methods (no body) and concrete
methods (with body). Subclasses must implement all abstract methods. Declared with 'abstract'
keyword.
abstract class Shape {
abstract double area(); // abstract method
void display() { // concrete method
[Link]("Area: " + area());
}
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return [Link] * r * r; }
}
// Shape s = new Shape(); // ERROR! Cannot instantiate
Shape c = new Circle(5);
[Link](); // Area: 78.53...
Q35. What is an Interface? Implement Shape Interface.
Ans: An interface is a fully abstract type. It contains only abstract methods (Java 7) and default/static
methods (Java 8+). A class implements an interface using 'implements'.
interface Shape {
double getArea();
double getPerimeter();
}
class Circle implements Shape {
double r;
Circle(double r) { this.r = r; }
public double getArea() { return [Link] * r * r; }
public double getPerimeter() { return 2 * [Link] * r; }
}
class Rectangle implements Shape {
double l, w;
Rectangle(double l, double w) { this.l = l; this.w = w; }
public double getArea() { return l * w; }
public double getPerimeter() { return 2 * (l + w); }
}
public class Test {
public static void main(String[] args) {
Shape c = new Circle(7);
Shape r = new Rectangle(4, 6);
[Link]("Circle Area: " + [Link]());
[Link]("Rect Area: " + [Link]());
}
}
TOPIC 7: Operators, Loops & Output Questions
───────────────────────────────────────────────────────────────────────────────
─
Q36. Output Question — Predict the output:
class Test {
public static void main(String[] args) {
int a = 10, b = 5, c = 20;
[Link](a > b && a < c); // true (10>5 && 10<20)
[Link](a + b * c); // 110 (5*20=100, 10+100=110)
[Link]("Sum: " + (a+b+c)); // Sum: 35
}
}
Output:
true
110
Sum: 35
Q37. Predict the output of the nested loop (star pattern):
class Loop {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}
}
}
Output:
*
**
***
Q38. Write a program for arithmetic operators taking input from user.
import [Link];
class Arithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter two numbers: ");
int a = [Link](), b = [Link]();
[Link]("Add: " + (a+b));
[Link]("Sub: " + (a-b));
[Link]("Mul: " + (a*b));
[Link]("Div: " + (a/b));
[Link]("Mod: " + (a%b));
[Link]();
}
}
Q39. Write a program to print multiplication table of a number.
import [Link];
class MultiTable {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
int n = [Link]();
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n*i));
}
[Link]();
}
}
Q40. Write a program to swap two numbers WITHOUT temp variable.
class Swap {
public static void main(String[] args) {
int a = 10, b = 20;
[Link]("Before: a=" + a + " b=" + b);
a = a + b; // a=30
b = a - b; // b=10
a = a - b; // a=20
[Link]("After: a=" + a + " b=" + b);
}
}
Q41. Check if a number is Prime using loops.
class PrimeCheck {
public static void main(String[] args) {
int n = 17;
boolean isPrime = (n > 1);
for (int i = 2; i <= [Link](n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
[Link](n + (isPrime ? " is Prime" : " is Not Prime"));
}
}
Q42. Generate Fibonacci series up to N terms.
import [Link];
class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
[Link](a + " ");
int next = a + b;
a = b; b = next;
}
}
}
Q43. Binary Search using Recursion.
class BinarySearch {
static int binarySearch(int[] arr, int low, int high, int target) {
if (low > high) return -1;
int mid = (low + high) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] > target) return binarySearch(arr, low, mid-1, target);
return binarySearch(arr, mid+1, high, target);
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10, 14, 18};
int idx = binarySearch(arr, 0, [Link]-1, 10);
[Link]("Found at index: " + idx); // 4
}
}
Q44. Count vowels and consonants in a string.
class VowelCount {
public static void main(String[] args) {
String s = "Hello World";
int v = 0, c = 0;
for (char ch : [Link]().toCharArray()) {
if ("aeiou".indexOf(ch) >= 0) v++;
else if ([Link](ch)) c++;
}
[Link]("Vowels: " + v + ", Consonants: " + c);
}
}
TOPIC 8: Collections Framework
───────────────────────────────────────────────────────────────────────────────
─
Q45. What is a Collection in Java?
Ans: Collections Framework provides classes and interfaces to store, manipulate, and retrieve groups
of objects. Key interfaces: List, Set, Queue, Map.
Key classes: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap
Q46. Difference between ArrayList and LinkedList
ArrayList: Uses dynamic array. Fast random access O(1). Slow insert/delete in middle O(n). Best for
frequent reading.
LinkedList: Uses doubly linked list. Slow random access O(n). Fast insert/delete O(1). Best for frequent
modifications.
Q47. Difference between ArrayList, LinkedList, and HashSet
ArrayList → ordered, allows duplicates, index-based access
LinkedList → ordered, allows duplicates, sequential access
HashSet → unordered, NO duplicates, no index access (uses hashing)
Q48. How to add, remove, retrieve from ArrayList? Write a program.
import [Link].*;
class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
// Add
[Link]("Ravi");
[Link]("Priya");
[Link]("Arjun");
[Link]("Sita");
[Link]("Kumar");
// Retrieve
[Link]("Element at 2: " + [Link](2));
// Print all with enhanced for loop
for (String n : names) [Link](n);
// Remove
[Link]("Sita");
[Link]("After remove: " + names);
}
}
Q49. Write a program to create a HashSet and observe no duplicates.
import [Link].*;
class HashSetDemo {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
[Link](10); [Link](20); [Link](30);
[Link](10); [Link](20); // duplicates - ignored
[Link](set); // [20, 10, 30] order varies
}
}
Q50. Write a program to demonstrate TreeSet.
import [Link].*;
class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
[Link](50); [Link](10); [Link](30); [Link](20);
[Link](ts); // [10, 20, 30, 50] sorted
[Link]([Link]()); // 10
[Link]([Link]()); // 50
}
}
Q51. Write a program to create HashMap with String keys and Integer values.
import [Link].*;
class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
[Link]("Apple", 10);
[Link]("Banana", 25);
[Link]("Mango", 15);
// Retrieve by key
[Link]("Banana: " + [Link]("Banana")); // 25
// Iterate all pairs
for ([Link]<String,Integer> e : [Link]()) {
[Link]([Link]() + " = " + [Link]());
}
}
}
TOPIC 9: Exception Handling
───────────────────────────────────────────────────────────────────────────────
─
Q52. What is Exception Handling in Java?
Ans: Exception handling is a mechanism to handle runtime errors so program flow is maintained. Java
uses try-catch-finally blocks, and throw/throws keywords.
Q53. What are Checked and Unchecked Exceptions?
Checked Exceptions: Checked at compile time. Must be handled or declared. Examples: IOException,
SQLException, ClassNotFoundException.
Unchecked Exceptions: Occur at runtime. Not required to handle. Examples: NullPointerException,
ArrayIndexOutOfBoundsException, NumberFormatException.
Q54. Describe complete exception handling mechanism in Java.
// Custom Exception
class AgeException extends Exception {
AgeException(String msg) { super(msg); }
}
class ExceptionDemo {
// throws declares checked exception
static void checkAge(int age) throws AgeException {
if (age < 18) throw new AgeException("Age must be >= 18");
[Link]("Valid age");
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (AgeException e) {
[Link]("Caught: " + [Link]());
} catch (Exception e) {
[Link]("General: " + [Link]());
} finally {
[Link]("Finally always runs");
}
}
}
Q55. What is the purpose of the finally block?
Ans: finally block always executes regardless of whether an exception occurred or not. It is used for
cleanup code: closing files, database connections, releasing resources. Even if catch doesn't handle
the exception, finally still runs.
Q56. What is NullPointerException?
Ans: NullPointerException is an unchecked exception thrown when you try to use a null reference to
call a method or access a field.
String s = null;
[Link](); // throws NullPointerException
Q57. Handle ArrayIndexOutOfBoundsException.
class ArrayException {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
[Link](arr[10]); // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: " + [Link]());
}
}
}
Q58. Handle NumberFormatException.
class NumberFormatDemo {
public static void main(String[] args) {
try {
int n = [Link]("abc"); // invalid
} catch (NumberFormatException e) {
[Link]("Invalid number: " + [Link]());
}
}
}
Q59. Demonstrate throw and throws keywords.
class ThrowDemo {
// throws = method declaration
static void divide(int a, int b) throws ArithmeticException {
if (b == 0) throw new ArithmeticException("Cannot divide by zero");
[Link](a / b);
}
public static void main(String[] args) {
try { divide(10, 0); }
catch (ArithmeticException e) { [Link]([Link]()); }
}
}
Q60. Demonstrate nested try blocks.
class NestedTry {
public static void main(String[] args) {
try {
[Link]("Outer try");
try {
int[] a = new int[3];
a[5] = 10; // throws exception
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch: " + [Link]());
}
[Link]("After inner try");
} catch (Exception e) {
[Link]("Outer catch: " + [Link]());
}
}
}
TOPIC 10: Multithreading
───────────────────────────────────────────────────────────────────────────────
─
Q61. What is Multithreading in Java?
Ans: Multithreading is a process of executing multiple threads simultaneously. A thread is the smallest
unit of execution. Java supports built-in multithreading via Thread class and Runnable interface.
Benefits: Better CPU utilization, improved performance, concurrent tasks.
Q62. Thread Life Cycle in Java
1. New → Thread object created but start() not called
2. Runnable → start() called, ready to run
3. Running → CPU executing the thread
4. Blocked/Waiting → waiting for resource or sleep()
5. Terminated/Dead → run() completed
Q63. What is the purpose of Thread class?
Ans: The Thread class provides methods to create and control threads: start(), run(), sleep(), join(),
interrupt(), getPriority(), setName() etc. A class can extend Thread and override run() to define thread
behavior.
Q64. Write a program to create thread using Runnable interface.
class MyRunnable implements Runnable {
String name;
MyRunnable(String name) { [Link] = name; }
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](name + " - Message " + i);
try { [Link](500); } catch (InterruptedException e) {}
}
}
}
class ThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable("Thread-1"));
Thread t2 = new Thread(new MyRunnable("Thread-2"));
[Link]();
[Link]();
}
}
Q65. Demonstrate Thread Pooling in Java.
import [Link].*;
class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService pool = [Link](3);
for (int i = 1; i <= 6; i++) {
final int task = i;
[Link](() -> {
[Link]("Task " + task + " by " +
[Link]().getName());
});
}
[Link]();
}
}
Q66. What is Concurrency in Java?
Ans: Concurrency means multiple tasks progress simultaneously. Java provides [Link]
package with thread-safe classes: ExecutorService, ConcurrentHashMap, BlockingQueue,
CountDownLatch, Semaphore. Synchronization prevents race conditions when threads share data.
TOPIC 11: File Handling
───────────────────────────────────────────────────────────────────────────────
─
Q67. What is File Handling in Java?
Ans: File handling is reading from and writing to files using I/O streams. Key classes: FileReader,
FileWriter, BufferedReader, BufferedWriter, FileInputStream, FileOutputStream.
Q68. Difference between FileWriter and BufferedWriter
FileWriter: Writes directly to file, character by character. Slower, no internal buffer.
BufferedWriter: Wraps FileWriter, uses internal buffer. Faster — writes in chunks. Has newLine()
method.
Best practice: Use BufferedWriter(new FileWriter(file)) for better performance.
Q69. Write a program to read from one file and write to another using FileReader/FileWriter.
import [Link].*;
class FileCopy {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("[Link]");
FileWriter writer = new FileWriter("[Link]");
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
[Link](); [Link]();
[Link]("File copied successfully!");
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
TOPIC 12: JDBC (Java Database Connectivity)
───────────────────────────────────────────────────────────────────────────────
─
Q70. What is JDBC? Explain architecture and steps.
Ans: JDBC is an API to connect Java programs to relational databases (MySQL, Oracle, etc.).
JDBC Architecture:
Java App → JDBC API → JDBC Driver Manager → JDBC Driver → Database
Steps to connect Java with Database:
import [Link].*;
class JdbcDemo {
public static void main(String[] args) throws Exception {
// Step 1: Load Driver
[Link]("[Link]");
// Step 2: Establish Connection
String url = "jdbc:mysql://localhost:3306/mydb";
Connection con = [Link](url, "root", "password");
// Step 3: Create Statement
Statement stmt = [Link]();
// Step 4: Execute Query
ResultSet rs = [Link]("SELECT * FROM students");
// Step 5: Process Results
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
// Step 6: Close Connection
[Link]();
}
}
TOPIC 13: Lambda Expressions (Java 8)
───────────────────────────────────────────────────────────────────────────────
─
Q71. Write a program to demonstrate Lambda Expression for a Functional Interface.
Ans: A lambda expression is a short block of code with no name — used to implement functional
interfaces (single-method interfaces).
// Functional Interface
@FunctionalInterface
interface Greeting {
void greet(String name);
}
class LambdaDemo {
public static void main(String[] args) {
// Lambda expression implements greet()
Greeting g = name -> [Link]("Hello, " + name + "!");
[Link]("Ravi"); // Hello, Ravi!
[Link]("Priya"); // Hello, Priya!
// Lambda with ArrayList sort
[Link]<Integer> nums = new [Link]<>();
[Link](5); [Link](2); [Link](8); [Link](1);
[Link]((a, b) -> a - b); // ascending sort lambda
[Link](nums); // [1, 2, 5, 8]
}
}
TOPIC 14: Serialization & Recursion (Short Notes)
───────────────────────────────────────────────────────────────────────────────
─
Q72. What is Serialization in Java?
Ans: Serialization is converting an object's state to a byte stream (to save to file or send over network).
Deserialization is the reverse. Implement [Link] interface. Use ObjectOutputStream to
serialize, ObjectInputStream to deserialize.
Q73. What is Recursion?
Ans: Recursion is a technique where a method calls itself to solve a problem. Every recursive method
must have a base case (stopping condition) to avoid infinite loops.
int factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive call
}
SHORT NOTES (Quick Reference)
───────────────────────────────────────────────────────────────────────────────
─
1. Access Specifiers
private → same class only | default → same package | protected → package + subclass | public →
everywhere
2. Constructor vs Method
Constructor: same name as class, no return type, called at object creation, initializes object.
Method: any name, has return type, called explicitly, performs actions.
3. Object-Oriented Programming (OOP)
4 pillars: Encapsulation (data hiding), Inheritance (code reuse), Polymorphism (many forms),
Abstraction (hiding implementation).
4. JRE (Java Runtime Environment)
JRE = JVM + class libraries. Provides runtime to execute Java programs. Does NOT include compiler
(javac).
5. Encapsulation
Wrapping data + methods. Private fields + public getters/setters. Protects data integrity.
6. WORA (Write Once Run Anywhere)
Java compiles to bytecode. JVM on any platform runs same bytecode. Platform independent.
7. Object
Instance of a class. Has state (fields) and behavior (methods). Created with 'new'. Occupies memory in
heap.
8. Recursion
Method calling itself. Needs base case. Examples: factorial, Fibonacci, binary search, tower of Hanoi.
9. Inheritance
Child class inherits parent's fields and methods. Uses 'extends'. Promotes reuse. Types: single,
multilevel, hierarchical.
10. Serialization
Convert object → byte stream → save/transmit. Implement Serializable. Use
ObjectOutputStream/InputStream.
11. Concurrency
Multiple threads executing simultaneously. Uses [Link] package. Synchronization
prevents race conditions.
12. HashSet
Set implementation using hashing. No duplicates. Unordered. O(1) add/remove/contains. Does not
allow null keys.
13. Abstract Class
Cannot be instantiated. May have abstract (no-body) + concrete methods. Subclass must implement all
abstract methods.
14. Static vs Dynamic Binding
Static: Resolved at compile time (overloading, static methods). Dynamic: Resolved at runtime
(overriding, polymorphism).
15. Polymorphism
One interface, many implementations. Compile-time: method overloading. Runtime: method overriding
via inheritance.
16. Thread Life Cycle
New → Runnable → Running → Blocked/Waiting → Terminated
17. Interface
100% abstract (Java 7). Use 'implements'. Multiple interfaces allowed. All methods public abstract by
default.
18. JDBC (Java Database Connectivity)
API to connect Java to databases. Steps: Load Driver → Get Connection → Create Statement →
Execute Query → Process Results → Close.
Java Complete Q&A | All topics covered | Best of luck for your exam! 🎯