Java Programming
Complete Exam Study Guide
Units 1 – 13 | ELI5 Explanations + Exam-Ready Answers + Code
Each unit covers: Simple explanation → Exam Q&A; → Code examples
Unit 1: Introduction to Java
■ Simple Explanation (ELI5):
Imagine you want to talk to different robots — some speak English, some French. Java is a special
language that all robots understand, no matter what country they're from. You write it once, and it runs
anywhere. The JVM (Java Virtual Machine) is like a translator robot sitting inside every computer.
Q: Define Java. Discuss its history and role in the Internet.
Java is a high-level, object-oriented, platform-independent programming language developed by James
Gosling at Sun Microsystems in 1995. It was originally called "Oak" and later renamed Java. Java
follows the principle of "Write Once, Run Anywhere" (WORA), meaning compiled Java code (bytecode)
can run on any device that has a JVM installed. Role in the Internet: Java has been widely used for
building web applications (via Servlets and JSP), enterprise-level server-side applications, Android
apps, and client-side applets (now deprecated). Its security model and platform independence made it
popular for internet-based systems.
Q: Explain Java Virtual Machine (JVM) and Bytecode.
JVM (Java Virtual Machine): The JVM is an abstract computing machine that enables a computer to run
Java programs. It interprets the compiled Java bytecode and translates it into machine-specific code at
runtime. Bytecode: When a Java source file (.java) is compiled using the Java compiler (javac), it is
converted into bytecode (.class file). Bytecode is an intermediate, platform-independent code that is not
machine code but can be executed by any JVM on any platform. Process: .java file → (compiled by
javac) → .class (bytecode) → (interpreted by JVM) → Machine code → Output
Q: Differentiate between Procedure-Oriented and Object-Oriented Programming.
Procedure-Oriented Programming (POP): Program is divided into functions/procedures. Data is global
and shared. Examples: C, Pascal. Object-Oriented Programming (OOP): Program is organized around
objects (data + behavior). Data is encapsulated inside objects. Examples: Java, C++. Key Difference: In
POP, functions are the main focus. In OOP, objects are the main focus.
Q: Describe the steps involved in compiling and running a Java program.
Step 1: Write the source code in a .java file (e.g., [Link]). Step 2: Compile using: javac [Link] →
produces [Link] (bytecode). Step 3: Run using: java Hello → JVM loads and executes the
bytecode. Step 4: Output is displayed on the screen.
Example – Hello World:
// [Link]
public class Hello {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
// Compile: javac [Link]
// Run: java Hello
// Output: Hello, World!
Unit 2: Tokens, Expressions, and Control Structures
■ Simple Explanation (ELI5):
Imagine you're giving commands to a robot: 'If it's raining, stay inside. Otherwise, go play.' Java works
the same way. 'if', 'while', 'for' are words you use to tell the program what to do in different situations.
Data types are like boxes — an int box holds whole numbers, a double box holds decimals.
Q: Explain different control statements (if, switch, while, for, break, continue, return).
if: Executes a block only if a condition is true. switch: Selects one of many code blocks based on a
value. while: Repeats a block as long as a condition is true. for: Repeats a block a fixed number of
times. break: Exits the loop or switch immediately. continue: Skips the rest of the current loop iteration.
return: Exits a method and optionally returns a value.
Q: Discuss primitive data types and type casting with examples.
Java has 8 primitive types: byte, short, int, long, float, double, char, boolean. Type Casting: Converting
one type to another. - Widening (implicit): int to double — no data loss. - Narrowing (explicit): double to
int — possible data loss, done manually. Example: double d = 9.7; int i = (int) d; // i = 9
Q: What are command-line arguments in Java?
Command-line arguments are values passed to the main() method when running a Java program from
the terminal. They are received as String[] args. Example: java MyClass Hello 5 Here, args[0] = "Hello"
and args[1] = "5".
Programming: Find sum of odd numbers in an array
public class OddSum {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int sum = 0;
for (int i = 0; i < [Link]; i++) {
if (numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
[Link]("Sum of odd numbers: " + sum);
// Output: Sum of odd numbers: 25
}
}
Unit 3: Object-Oriented Programming Concepts
■ Simple Explanation (ELI5):
Think of a 'Dog' blueprint. Every dog has a name, breed, and can bark. In Java, this blueprint is called
a Class. An actual dog (like 'Tommy') is an Object. OOP is just about organizing code like real-world
things — they have properties and can do stuff.
Q: Define OOP. Explain Abstraction, Encapsulation, Inheritance, and Polymorphism.
OOP (Object-Oriented Programming): A programming paradigm based on the concept of objects which
contain data (fields) and code (methods). Abstraction: Hiding complex implementation details and
showing only essential features. (e.g., you use a TV remote without knowing the circuit inside.)
Encapsulation: Wrapping data and methods together in a class, restricting direct access using access
modifiers. (e.g., private fields with public getters/setters.) Inheritance: A child class acquiring properties
and behaviors of a parent class using 'extends'. Promotes code reuse. Polymorphism: One thing taking
many forms. A method can behave differently based on the object calling it (method overloading and
overriding).
Q: Explain the use of constructors with an example (including constructor overloading).
A constructor is a special method called automatically when an object is created. It has the same name
as the class and no return type. Constructor Overloading: Having multiple constructors with different
parameters in the same class.
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Alice", 20);
[Link](); // Name: Unknown, Age: 0
[Link](); // Name: Alice, Age: 20
}
}
Q: What is method overloading? Explain with a program.
Method Overloading: Defining multiple methods with the same name but different parameter lists
(number or type of parameters) in the same class.
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; }
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](2, 3)); // 5
[Link]([Link](2.5, 3.5)); // 6.0
[Link]([Link](1, 2, 3)); // 6
}
}
Q: What is the use of 'this' keyword? Show with a code snippet.
'this' keyword refers to the current instance of the class. It is used to distinguish between class fields and
constructor/method parameters with the same name.
class Box {
int length;
Box(int length) {
[Link] = length; // '[Link]' = field, 'length' = parameter
}
void show() {
[Link]("Length: " + [Link]);
}
}
Q: Explain access modifiers in Java.
Java has four access modifiers: - public: Accessible from anywhere. - private: Accessible only within the
same class. - protected: Accessible within the same package and subclasses. - default (no keyword):
Accessible within the same package only.
Unit 4: Inheritance & Packaging
■ Simple Explanation (ELI5):
Inheritance is like a child inheriting traits from parents — a child gets eye color, height from parents. In
Java, a child class gets methods and fields from the parent class. Interface is like a job contract: 'If
you are a Dog, you MUST know how to bark.' A package is like a folder that organizes your code.
Q: What is inheritance? Explain with suitable example.
Inheritance is the mechanism by which one class (child/subclass) acquires the properties and methods
of another class (parent/superclass) using the 'extends' keyword. It promotes code reusability.
class Animal {
void eat() { [Link]("Animal is eating"); }
}
class Dog extends Animal {
void bark() { [Link]("Dog is barking"); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited from Animal
[Link](); // Dog's own method
}
}
Q: Differentiate between abstract class and interface.
Abstract Class: - Can have both abstract and concrete methods. - Can have constructors and instance
variables. - A class can extend only ONE abstract class. - Use when classes share common code.
Interface: - All methods are abstract by default (Java 8+ allows default methods). - Cannot have
constructors or instance variables (only constants). - A class can implement MULTIPLE interfaces. - Use
when unrelated classes need to share a contract.
Q: What is method overriding? Implement multiple inheritance using interface.
Method Overriding: When a child class provides its own implementation of a method that is already
defined in the parent class. The method must have the same name, return type, and parameters.
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
public void fly() { [Link]("Duck is flying"); }
public void swim() { [Link]("Duck is swimming"); }
}
public class Main {
public static void main(String[] args) {
Duck d = new Duck();
[Link]();
[Link]();
}
}
Q: Explain the use of super and extends keywords.
extends: Used to inherit a class. class Child extends Parent super: Refers to the parent class object.
Used to call parent class constructor or methods. - super() — calls parent constructor. -
[Link]() — calls parent method.
Q: Define and implement a Java package.
A package is a namespace that organizes a set of related classes and interfaces. It avoids naming
conflicts and provides access control. Built-in: [Link], [Link], [Link] User-defined: created using
'package' keyword.
// File: mypackage/[Link]
package mypackage;
public class Greet {
public void hello() {
[Link]("Hello from package!");
}
}
// File: [Link]
import [Link];
public class Main {
public static void main(String[] args) {
Greet g = new Greet();
[Link]();
}
}
Unit 5: Handling Errors / Exceptions
■ Simple Explanation (ELI5):
Imagine you're dividing a pizza among friends. If someone says 'divide it among 0 people', your brain
says 'ERROR!' Java has a system to handle these errors gracefully without crashing the whole
program. try is 'attempt this', catch is 'if error happens, do this', finally is 'always do this no matter
what'.
Q: Why is exception handling important? Explain try-catch-finally with example.
Exception handling prevents abnormal termination of programs when runtime errors occur. It allows the
program to respond to errors gracefully. try: Block of code that might throw an exception. catch: Block
that handles the exception. finally: Block that always executes regardless of exception.
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
[Link](result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("This always executes.");
}
}
}
// Output:
// Error: / by zero
// This always executes.
Q: What is the difference between checked and unchecked exceptions?
Checked Exceptions: Exceptions that are checked at compile time. The programmer must handle them
using try-catch or declare them with 'throws'. Examples: IOException, SQLException. Unchecked
Exceptions: Exceptions checked at runtime. They are subclasses of RuntimeException. Examples:
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
Q: Write a program that creates a user-defined exception.
A user-defined exception is created by extending the Exception class.
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or above.");
}
[Link]("Valid age: " + age);
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (AgeException e) {
[Link]("Caught: " + [Link]());
}
}
}
// Output: Caught: Age must be 18 or above.
Q: Explain the use of throw, throws, and finally keywords.
throw: Used to explicitly throw an exception inside a method. throw new ArithmeticException("error");
throws: Used in method signature to declare that a method might throw an exception. Callers must
handle it. public void read() throws IOException {} finally: A block that always executes after try-catch,
used for cleanup (e.g., closing files).
Unit 6: Handling Strings
■ Simple Explanation (ELI5):
A String in Java is like a necklace of beads — each bead is a character. Once you make it, you can't
change the beads (it's immutable). StringBuffer is like a necklace you CAN change — you can add or
remove beads. A palindrome is a word that reads the same forwards and backwards, like 'madam' or
'racecar'.
Q: Differentiate between String and StringBuffer classes.
String: - Immutable (cannot be changed once created). - Stored in String Pool (memory efficient for
same values). - Slower when modifying content (creates new objects). - Example: String s = "hello";
StringBuffer: - Mutable (content can be changed). - Not synchronized — use StringBuilder for single
thread (faster). - Faster for repeated modifications. - Example: StringBuffer sb = new
StringBuffer("hello"); [Link](" world");
Q: Write a Java program to check if a string is a palindrome.
A palindrome reads the same forwards and backwards.
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
if ([Link](rev)) {
[Link](str + " is a palindrome.");
} else {
[Link](str + " is not a palindrome.");
}
}
}
// Output: madam is a palindrome.
Q: Explain string comparison and modification methods.
Comparison Methods: - equals(): Compares content. "abc".equals("abc") → true - equalsIgnoreCase():
Ignores case. - compareTo(): Compares lexicographically. - contains(): Checks if substring exists.
Modification Methods (return new String): - toUpperCase() / toLowerCase() - trim(): Removes
leading/trailing spaces. - replace(old, new): Replaces characters. - substring(start, end): Extracts
portion. - split(delimiter): Splits into array.
Unit 7: Threads
■ Simple Explanation (ELI5):
Imagine you can walk and chew gum at the same time. Your brain does two things at once! A thread
is like a separate task your program can run at the same time as another task. Multithreading lets your
program do multiple things simultaneously — like playing music while downloading a file.
Q: What is multithreading? How do you create and run threads in Java?
Multithreading: The ability of a program to execute multiple threads (lightweight sub-processes)
concurrently, sharing the same process memory. Two ways to create threads: 1. Extending Thread
class. 2. Implementing Runnable interface (preferred).
// Method 1: Extending Thread
class MyThread extends Thread {
public void run() {
[Link]("Thread running: " + getName());
}
}
// Method 2: Implementing Runnable
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread: " + [Link]().getName());
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
Thread t2 = new Thread(new MyRunnable());
[Link]();
}
}
Q: Write a program to print even and odd numbers using two threads.
Two threads coordinate to print even and odd numbers alternatively.
public class EvenOddThread {
static int num = 1;
static final int MAX = 10;
public static void main(String[] args) {
Thread odd = new Thread(() -> {
while (num <= MAX) {
if (num % 2 != 0) {
[Link]("Odd: " + num++);
}
}
});
Thread even = new Thread(() -> {
while (num <= MAX) {
if (num % 2 == 0) {
[Link]("Even: " + num++);
}
}
});
[Link]();
[Link]();
}
}
Q: What is synchronization and inter-thread communication?
Synchronization: A mechanism to control access of multiple threads to shared resources. The
'synchronized' keyword ensures only one thread accesses a block/method at a time, preventing data
inconsistency. Inter-thread Communication: Threads can communicate using wait(), notify(), and
notifyAll() methods (from Object class): - wait(): Causes the current thread to pause and release the
lock. - notify(): Wakes up one waiting thread. - notifyAll(): Wakes up all waiting threads.
Unit 8: I/O and Streams
■ Simple Explanation (ELI5):
Imagine water flowing through pipes. In Java, data flows through Streams — from files to your
program (reading) and from your program to files (writing). Byte streams carry raw data (like images),
while character streams carry text (like letters). Serialization is like packing an object into a box (file)
so you can unpack and use it later.
Q: Write a Java program to copy content from one file to another.
File copy using FileInputStream and FileOutputStream (byte streams).
import [Link].*;
public class FileCopy {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("[Link]");
FileOutputStream out = new FileOutputStream("[Link]");
int byteData;
while ((byteData = [Link]()) != -1) {
[Link](byteData);
}
[Link]();
[Link]();
[Link]("File copied successfully.");
}
}
Q: Explain the difference between byte streams and character streams.
Byte Streams: - Handle data in raw binary format (bytes). - Used for images, audio, and binary files. -
Classes: FileInputStream, FileOutputStream, DataInputStream. Character Streams: - Handle data as
characters (16-bit Unicode). - Used for text files. - Classes: FileReader, FileWriter, BufferedReader,
PrintWriter. - Automatically handle character encoding.
Q: What is serialization? Explain with example.
Serialization: The process of converting a Java object into a byte stream so it can be saved to a file or
transferred over a network. Deserialization: Converting the byte stream back into an object. The class
must implement Serializable interface.
import [Link].*;
class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
[Link] = name; [Link] = age;
}
}
public class SerializeDemo {
public static void main(String[] args) throws Exception {
// Serialize
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("[Link]"));
[Link](new Person("Alice", 25));
[Link]();
// Deserialize
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("[Link]"));
Person p = (Person) [Link]();
[Link]([Link] + ", " + [Link]); // Alice, 25
[Link]();
}
}
Unit 9: Core Packages
■ Simple Explanation (ELI5):
Java comes with a toolbox full of ready-made tools. Wrapper classes are like gift boxes that wrap
primitive numbers (like int) so they can be used as objects. The [Link] package is like a Swiss army
knife — it has collections (like lists), a Random number generator, and much more.
Q: What are wrapper classes? Explain with examples.
Wrapper Classes: Java provides a wrapper class for each primitive data type to convert primitives into
objects. They are found in [Link] package. int → Integer, double → Double, char → Character,
boolean → Boolean Key uses: Converting string to number (parseInt), using generics (ArrayList), null
values.
public class WrapperDemo {
public static void main(String[] args) {
// Boxing: primitive to object
int x = 42;
Integer obj = [Link](x);
// Unboxing: object to primitive
int y = [Link]();
// Useful methods
[Link]([Link]("100")); // 100
[Link](Integer.MAX_VALUE); // 2147483647
[Link]([Link]("3.14")); // 3.14
}
}
Q: How do you generate random numbers in Java?
Random numbers can be generated using [Link] class or [Link]().
import [Link];
public class RandomDemo {
public static void main(String[] args) {
Random rand = new Random();
[Link]([Link](100)); // 0 to 99
[Link]([Link]()); // 0.0 to 1.0
[Link]((int)([Link]() * 50)); // 0 to 49
}
}
Q: Explain commonly used classes in [Link] like Vector, Stack, Hashtable.
Vector: A dynamic array (synchronized, thread-safe). Similar to ArrayList but slower. Vector v = new
Vector<>(); [Link]("A"); Stack: Extends Vector. Follows LIFO (Last In, First Out) principle. Methods:
push(), pop(), peek(), isEmpty(). Hashtable: Stores key-value pairs (synchronized). Similar to HashMap
but thread-safe and doesn't allow null keys/values. Hashtable ht = new Hashtable<>();
Unit 10: Collections
■ Simple Explanation (ELI5):
Collections in Java are like different types of containers. ArrayList is a list you can grow. LinkedList is
like a chain of boxes. HashSet is a bag where duplicates are not allowed. TreeSet is a bag that keeps
items sorted. Iterator is like a finger pointing one-by-one through the container.
Q: Differentiate between ArrayList, LinkedList, HashSet, and TreeSet.
ArrayList: Dynamic array. Fast random access. Allows duplicates. Ordered by insertion. LinkedList:
Doubly linked list. Fast insert/delete. Allows duplicates. Ordered by insertion. HashSet: Uses hash table.
No duplicates. No guaranteed order. O(1) operations. TreeSet: Uses a tree (Red-Black). No duplicates.
Always sorted (ascending by default). O(log n) operations.
Q: What is the role of Iterator and Comparator? Use them in a program.
Iterator: Provides a way to traverse a collection element by element using hasNext() and next()
methods. Comparator: Used to define custom sorting logic for objects. Implement the compare()
method.
import [Link].*;
public class CollectionDemo {
public static void main(String[] args) {
// Iterator example
ArrayList<String> list = new ArrayList<>([Link]("Banana","Apple","Cherry"));
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]() + " ");
}
[Link]();
// Comparator: sort by length
[Link]([Link](String::length));
[Link](list); // [Apple, Banana, Cherry]
}
}
Q: Write a program to sort names using collections.
Using [Link]() to sort a list of names alphabetically.
import [Link].*;
public class SortNames {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
[Link]("Zara"); [Link]("Alice"); [Link]("Mike");
[Link](names);
[Link]("Sorted: " + names);
// Output: Sorted: [Alice, Mike, Zara]
}
}
Unit 11: Java Applications (AWT & Swing)
■ Simple Explanation (ELI5):
AWT and Swing are Java's toolkits for making windows, buttons, and forms — the visual stuff you
click on. Swing is the newer, better-looking version. JFrame is like the window of your house. JButton
is a button. JLabel is a text sign. JTable shows data in rows and columns like Excel.
Q: What is Swing? List and explain any five Swing components.
Swing is a Java GUI (Graphical User Interface) toolkit that provides platform-independent, lightweight
components for building desktop applications. It is part of [Link] package. Five Key Components:
1. JFrame: The main window container of a Swing application. 2. JButton: A clickable button that
triggers an action. 3. JLabel: Displays text or an image (non-editable). 4. JTextField: Single-line text
input field for user input. 5. JTable: Displays data in a tabular format with rows and columns.
Q: Write a GUI program to calculate the sum and difference of two numbers.
A simple Swing application with text fields and buttons.
import [Link].*;
import [Link].*;
import [Link].*;
public class Calculator extends JFrame {
JTextField t1 = new JTextField(5), t2 = new JTextField(5);
JLabel result = new JLabel("Result: ");
JButton sum = new JButton("Sum"), diff = new JButton("Diff");
Calculator() {
setLayout(new FlowLayout());
add(new JLabel("Num1:")); add(t1);
add(new JLabel("Num2:")); add(t2);
add(sum); add(diff); add(result);
[Link](e -> {
int a = [Link]([Link]());
int b = [Link]([Link]());
[Link]("Sum: " + (a + b));
});
[Link](e -> {
int a = [Link]([Link]());
int b = [Link]([Link]());
[Link]("Diff: " + (a - b));
});
setSize(300, 150); setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) { new Calculator(); }
}
Q: What is JTable? How is it used to display tabular data?
JTable is a Swing component used to display data in a grid of rows and columns, similar to a
spreadsheet. It takes data as a 2D array and column names.
import [Link].*;
public class TableDemo {
public static void main(String[] args) {
String[] cols = {"ID", "Name", "Marks"};
Object[][] data = {{1,"Alice",90},{2,"Bob",85},{3,"Carol",92}};
JTable table = new JTable(data, cols);
JFrame f = new JFrame("Student Table");
[Link](new JScrollPane(table));
[Link](300, 200); [Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Q: What is MDI in Java Swing? Explain with components like JDesktopPane and JInternalFrame.
MDI (Multiple Document Interface): An interface design where multiple child windows (documents) exist
within a single parent window. JDesktopPane: Acts as the parent container (desktop) for multiple
internal frames. JInternalFrame: A lightweight window that resides inside JDesktopPane. It can be
minimized, maximized, and closed within the desktop pane.
Unit 12: Applets
■ Simple Explanation (ELI5):
A Java Applet is like a tiny program that used to run inside a web browser. Imagine a mini-game
embedded in a webpage. Applets have a lifecycle — they are born (init), started (start), paused (stop),
and die (destroy). Note: Applets are now deprecated and no longer supported in modern browsers.
Q: Define Java Applet. Explain its lifecycle.
Java Applet: A small Java program that was designed to run inside a web browser using the Java
Plugin. It extends the [Link] class. Note: Applets are now obsolete and deprecated since
Java 9+. Lifecycle Methods: 1. init(): Called once when the applet is first loaded. Used for initialization. 2.
start(): Called after init() and every time the applet becomes visible. Used to start execution. 3.
paint(Graphics g): Called to render the applet's output on screen. 4. stop(): Called when the user leaves
the page. Pauses execution. 5. destroy(): Called when the browser is closed. Performs cleanup.
Q: Write a simple applet program and explain its execution.
A basic applet that displays a message.
import [Link].*;
import [Link].*;
/*
<applet code="[Link]" width=300 height=200>
</applet>
*/
public class HelloApplet extends Applet {
public void init() {
setBackground([Link]);
}
public void paint(Graphics g) {
[Link]([Link]);
[Link](new Font("Arial", [Link], 20));
[Link]("Hello from Java Applet!", 50, 100);
}
}
// To run: appletviewer [Link]
// Note: Applets are deprecated in modern Java.
Unit 13: JDBC
■ Simple Explanation (ELI5):
JDBC (Java Database Connectivity) is like a telephone line between your Java program and a
database. You use it to ask the database questions ('Give me all students') and get answers back.
Think of it like ordering food at a restaurant: Java is you (the customer), JDBC is the waiter, and the
database is the kitchen.
Q: What is JDBC? Explain its components: Connection, Statement, ResultSet.
JDBC (Java Database Connectivity): An API that allows Java programs to interact with relational
databases (MySQL, Oracle, SQLite) using SQL queries. Connection: Represents a session/link between
Java and the database. Created using [Link](). Statement: Used to execute
SQL queries. Types: Statement (static), PreparedStatement (parameterized, safer), CallableStatement
(stored procedures). ResultSet: Holds the data returned from a SELECT query. You iterate through it
using [Link]() to read rows.
Q: Write a Java program to connect to a database and display records.
Connecting to MySQL and fetching data using JDBC.
import [Link].*;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String pass = "password";
try {
// Step 1: Load driver (auto in Java 6+)
[Link]("[Link]");
// Step 2: Establish connection
Connection con = [Link](url, user, pass);
// 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]("id") + " | " +
[Link]("name") + " | " +
[Link]("marks"));
}
// Step 6: Close
[Link](); [Link](); [Link]();
} catch (Exception e) {
[Link]();
}
}
}
Q: What are the types of JDBC drivers?
There are 4 types of JDBC drivers: Type 1 – JDBC-ODBC Bridge Driver: Converts JDBC calls to ODBC
calls. Platform-dependent. Deprecated. Type 2 – Native-API Driver: Converts JDBC calls to native
database API calls. Requires native library on client. Not fully portable. Type 3 – Network Protocol
Driver: Converts JDBC calls to middleware-specific protocol. Middleware then communicates with the
database. Flexible. Type 4 – Thin Driver (Pure Java Driver): Converts JDBC calls directly into
database-specific protocol. Fully Java, most commonly used today (e.g., MySQL Connector/J).
Study Tips
For your exam, focus on understanding the WHY behind each concept, not just memorizing syntax. For
programming questions, always structure your answer as: (1) Brief definition, (2) Key points, (3) Code
example, (4) Output/explanation. Good luck, Sangharsha!