Java Notes
Java Notes
Key Characteristics
● Platform Independence: Java programs run on any device with a JVM, thanks to the "write once, run
anywhere" (WORA) principle. Code is compiled to bytecode, which the JVM interprets or compiles to
machine code.
● Object-Oriented: Everything in Java is an object (except primitives). Supports encapsulation, inheritance,
polymorphism, and abstraction.
● Robust: Strong type-checking, exception handling, and automatic memory management (garbage collection)
prevent common errors like memory leaks or pointer issues.
● Secure: The JVM’s sandbox model, class loader, and bytecode verification ensure safe execution, even for
untrusted code.
● Multithreaded: Built-in support for concurrent programming via threads.
● Simple: No pointers, operator overloading, or manual memory management, making it easier to learn than
C++.
● High Performance: Just-In-Time (JIT) compilation converts bytecode to native code at runtime, boosting
performance.
● Distributed: Supports networking and distributed systems (e.g., RMI, JDBC).
● Dynamic: Classes can be loaded at runtime, enabling flexibility (e.g., applets, plugins).
Example: A Java program to print "Hello, World!" runs identically on Windows, Linux, or macOS because the JVM
translates bytecode to the platform’s native instructions.
Exam Tip: Memorize key characteristics (e.g., platform independence, security, multithreading) and be ready to
explain WORA with an example.
Compilation
Example:
● Write HelloWorld.java.
● Compile: javac HelloWorld.java → produces HelloWorld.class.
● Run: java HelloWorld → JVM loads, verifies, and executes, printing "Hello, World!".
Diagram:
Source Code (.java) → [javac] → Bytecode (.class) → [JVM: Verify, Interpret/JIT Compile] →
Native Code → Execution
Exam Tip: Be ready to explain the role of javac vs. JVM and how JIT compilation improves performance. Practice
drawing the compilation-execution flow.
JVM Components
Example: When running HelloWorld, the class loader loads HelloWorld.class, the method area stores its code, the
heap stores the String object for "Hello, World!", and the Java stack tracks the main method’s execution.
Exam Tip: Understand the role of each JVM component. Be ready to describe how memory areas interact during
program execution.
4. JVM as an Interpreter and Emulator
● Interpreter: The JVM interprets bytecode by translating each instruction to native code at runtime. This is
slower but ensures portability.
○ Example: The instruction iload_1 (load integer from variable 1) is interpreted for the specific CPU.
● Emulator: The JVM emulates a standardized machine, executing bytecode consistently across platforms. It
abstracts hardware differences (e.g., CPU, OS).
○ Example: A Java program runs identically on x86 (Windows) and ARM (Linux) because the JVM
emulates the same instruction set.
Key Advantage: Interpretation allows immediate execution, while JIT compilation (emulation + optimization) boosts
performance.
Exam Tip: Explain the trade-offs of interpretation (portability, slower) vs. JIT compilation (faster, platform-specific).
Be ready to define emulation in the JVM context.
5. Instruction Set
The JVM uses a stack-based instruction set, where operations manipulate a stack of operands. Instructions
(opcodes) are compact, typically 1 byte, ensuring portability.
● Types of Instructions:
○ Load/Store: Move data between stack and local variables (e.g., iload_1, istore_2).
○ Arithmetic: Perform operations (e.g., iadd for integer addition).
○ Control: Manage flow (e.g., if_icmpeq for conditional branching).
○ Object Operations: Create objects, access fields (e.g., new, getfield).
○ Method Invocation: Call methods (e.g., invokevirtual).
Exam Tip: Understand stack-based execution and common opcodes. Practice translating simple Java code to
bytecode (e.g., arithmetic or method calls).
● Structure:
○ Magic Number: 0xCAFEBABE (identifies class file).
○ Version: Compiler and JVM version.
○ Constant Pool: Literals, class names, method references.
○ Access Flags: Public, final, etc.
○ Fields and Methods: Definitions and bytecode.
● Example: HelloWorld.class stores the main method’s bytecode and the string "Hello, World!" in the constant
pool.
Verification
The bytecode verifier checks .class files for safety before execution:
● Stores per-class data: bytecode, constant pool, method tables, and static variables.
● Shared across threads but thread-safe for access.
● Example: The System.out object’s metadata resides here.
Java Stack
Heap
Exam Tip: Understand the class file structure, verification process, and memory areas. Be ready to explain GC steps
and why the heap is shared but the stack is thread-specific.
● Key Promises:
○ Type Safety: Prevents illegal operations (e.g., casting String to int).
○ Memory Safety: No direct memory access (no pointers).
○ Sandboxing: Restricts untrusted code to a controlled environment.
○ Verification: Ensures bytecode is safe before execution.
○ Access Control: Enforces permissions via security policies.
Example: An applet cannot access the local file system unless explicitly permitted, thanks to the JVM’s sandbox.
Exam Tip: List JVM security features and explain how they protect against malicious code.
Example: A Java program trying to read a file triggers the Security Manager, which checks the policy file for
permission.
Security Policy
● A configuration file (java.policy) defines permissions for code based on its source, signer, or class.
● Permissions: File read/write, network access, etc.
Example Policy:
grant codeBase "file:/trusted/" {
permission java.io.FilePermission "/data/*", "read,write";
};
Grants file access to code from the trusted directory.
Exam Tip: Understand the roles of the Security Manager and policy file. Be ready to write a simple policy or explain
permission checks.
Sandbox Model
Practice Problem: Explain how the class loader delegation model prevents a malicious class from impersonating
java.lang.System.
Exam Tip: Understand the delegation model and sandbox restrictions. Be ready to explain how class loaders
enhance security.
Exam-Focused Tips
● Common Questions:
○ Explain WORA and the JVM’s role in portability.
○ Describe the compilation-execution process with a diagram.
○ List JVM memory areas and their purposes.
○ Translate Java code to bytecode.
○ Explain GC or security mechanisms (e.g., sandbox, class loaders).
● Key Examples to Master:
○ Compilation-execution flow for a program.
○ Bytecode for arithmetic or method calls.
○ GC process for a program with objects.
○ Security policy for file access.
1. Java Fundamentals: Data Types & Literals, Variables
Data Types
Java is a strongly typed language, meaning every variable has a specific type. Data types are divided into
primitive and reference types.
Literals
Variables
Example:
int age = 25; // Local variable
Practice Problem: Declare variables for a student’s ID (int), name (String), and GPA (double), and initialize them.
Exam Tip: Memorize primitive type ranges and literal formats. Be ready to spot invalid literals (e.g., int x = 3.14; //
Error).
2. Wrapper Classes
Wrapper classes provide object representations for primitive types, enabling their use in collections (e.g., ArrayList)
and methods requiring objects.
● Wrapper Classes:
○ Byte, Short, Integer, Long, Float, Double, Character, Boolean.
● Autoboxing: Automatic conversion from primitive to wrapper (e.g., Integer i = 5; converts int to Integer).
● Unboxing: Wrapper to primitive (e.g., int j = i;).
● Methods: Provide utilities (e.g., Integer.parseInt("123") converts String to int).
Example:
Practice Problem: Write code to convert a String "3.14" to a double using a wrapper class.
Exam Tip: Understand autoboxing/unboxing and common wrapper methods (e.g., valueOf, parseXxx). Expect
questions like “What is the output of Integer x = 5; x += 10;?”
3. Arrays
Arrays are fixed-size, ordered collections of elements of the same type.
Example:
scores[0] = 90;
scores[1] = 85;
scores[2] = 88;
System.out.println(scores[i]);
4. Arithmetic Operators
Perform mathematical operations:
Example:
int a = 10, b = 3;
int sum = a + b; // 13
int mod = a % b; // 1
a += 5; // a = 15
Exam Tip: Understand integer vs. floating-point division (e.g., 5 / 2 = 2, 5.0 / 2 = 2.5). Practice operator precedence.
5. Logical Operators
Evaluate boolean expressions:
Example:
int x = 5, y = 10;
if (x > 0 || y < 0) {
6. Control of Flow
Control flow directs program execution using conditionals and loops.
● Conditionals:
○ if-else: if (condition) { ... } else { ... }.
switch: Matches a value to cases (supports int, String, enum in Java 7+).
int day = 2;
switch (day) {
default: System.out.println("Invalid");
}
● Loops:
○ for: for (int i = 0; i < 5; i++) { ... }.
○ while: while (condition) { ... }.
○ do-while: do { ... } while (condition);.
○ Enhanced for: for (int num : array) { ... }.
● Control Statements:
○ break: Exits a loop or switch.
○ continue: Skips to the next iteration.
○ return: Exits a method.
Example:
if (i % 2 == 0) {
System.out.println(i);
Practice Problem: Write a program to print the first 10 Fibonacci numbers using a loop.
Exam Tip: Practice nested loops and switch statements. Be ready to debug flow control errors (e.g., missing break in
switch).
Class Declaration:
public class Student {
int id;
}
s1.name = "Alice";
s1.id = 101;
this.name = name;
this.id = id;
}
Practice Problem: Create a Car class with fields model and speed, a constructor, and a method accelerate.
Exam Tip: Understand the difference between class (blueprint) and object (instance). Practice constructor
overloading.
8. Class Member Modifiers
Modifiers control access and behavior of class members (fields, methods, constructors).
● Access Modifiers:
○ public: Accessible everywhere.
○ protected: Accessible in the same package or subclasses.
○ default (package-private): Accessible in the same package (no modifier).
○ private: Accessible only within the class.
● Non-Access Modifiers:
○ static: Belongs to the class, not instances (e.g., static int count;).
○ final: Cannot be modified (e.g., final double PI = 3.14;).
○ abstract: Cannot be instantiated; used for abstract classes/methods.
○ synchronized: Thread-safe method.
○ transient: Excluded from serialization.
○ volatile: Ensures visibility in multithreading.
Example:
count++;
Exam Tip: Know the scope of each modifier. Expect questions like “What happens if a method is private?” or “Why
use static?”
Syntax:
interface Action {
void perform();
}
System.out.println("Action performed!");
};
action.perform();
● Use Case: Event handling, lambda expressions (Java 8+ often replace anonymous classes).
Example:
button.addActionListener(new ActionListener() {
System.out.println("Button clicked!");
});
Exam Tip: Understand when to use anonymous classes vs. named classes. Be ready to write simple examples for
interfaces.
Example:
interface Vehicle {
void start();
System.out.println("Vehicle stopped.");
}
System.out.println("Car started.");
}
● Abstract Class: A class that cannot be instantiated, may contain abstract methods (no implementation) and
concrete methods.
Example:
abstract class Animal {
void sleep() {
System.out.println("Sleeping...");
void makeSound() {
System.out.println("Woof!");
}
Practice Problem: Create an interface Shape with a method area(), implemented by classes Circle and Rectangle.
Exam Tip: Compare interfaces (multiple inheritance) vs. abstract classes (single inheritance). Know default methods
in interfaces.
● Allows a class (subclass) to inherit fields and methods from another (superclass) using extends.
● super: Access superclass methods/constructors.
● Method Overriding: Subclass redefines a superclass method (same signature, @Override annotation
recommended).
Example:
class Animal {
void eat() {
System.out.println("Eating...");
@Override
void eat() {
}
User-Defined Exceptions
Example:
class InvalidAgeException extends Exception {
super(message);
}
}
class Person {
if (age < 0) {
}
Exam Tip: Understand checked vs. unchecked exceptions and overriding rules (subclass methods can’t throw
broader exceptions). Practice writing custom exceptions.
● Key Methods:
○ append(): Adds data.
○ insert(): Inserts data at a position.
○ delete(): Removes characters.
○ reverse(): Reverses the string.
Example:
StringBuffer sb = new StringBuffer("Hello");
Note: Use StringBuilder (non-synchronized) for single-threaded applications for better performance.
Exam Tip: Compare String, StringBuffer, and StringBuilder. Know when to use each.
13. StringTokenizer
StringTokenizer breaks a string into tokens based on delimiters (e.g., spaces, commas).
● Key Methods:
○ hasMoreTokens(): Checks for more tokens.
○ nextToken(): Returns the next token.
Example:
StringTokenizer st = new StringTokenizer("apple,banana,orange", ",");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
Exam Tip: Know StringTokenizer methods and when to use split() instead.
Applets are small Java programs embedded in web pages, executed by a browser’s JVM.
Structure:
import java.applet.Applet;
import java.awt.Graphics;
}
● HTML Embedding:
<applet code="MyApplet.class" width="200" height="200"></applet>
Example:
System.out.println("Applet initialized");
System.out.println("Applet started");
System.out.println("Applet stopped");
System.out.println("Applet destroyed");
Security Concerns
Practice Problem: Write an applet to draw a rectangle and display its life cycle methods.
import java.applet.Applet;
import java.awt.Graphics;
System.out"'Applet initialized");
System.out.println("Applet started");
System.out.println("Applet stopped");
System.out.println("Applet destroyed");
Exam Tip: Memorize the applet life cycle and sandbox restrictions. Be ready to write a simple applet or explain
security concerns.
Exam-Focused Tips
● Common Questions:
○ Write code for a class with inheritance and overridden methods.
○ Create a user-defined exception and handle it.
○ Explain the applet life cycle or write a simple applet.
○ Compare String vs. StringBuffer vs. StringBuilder.
○ Debug control flow or operator errors.
● Key Examples to Master:
○ Class with constructor, methods, and inheritance.
○ Custom exception handling.
○ Applet with life cycle methods.
○ String manipulation with StringBuffer.
1. Threads: Creating Threads, Thread Priority, Blocked States,
Extending Thread Class, Runnable Interface
Threads Overview
A thread is a lightweight unit of execution within a process, enabling concurrent task execution. Java’s
java.lang.Thread class and multithreading APIs support thread creation and management.
Creating Threads
Example:
class MyThread extends Thread {
}
Example:
class MyRunnable implements Runnable {
}
Starting Threads
● Call start() to schedule the thread (invokes run()). Direct run() calls execute in the current thread, not a new
one.
Example:
MyThread t1 = new MyThread();
t1.start(); // Starts thread
t2.start();
Thread Priority
Example:
t1.setPriority(Thread.MAX_PRIORITY); // Priority 10
Blocked States
Practice Problem: Create a thread using Runnable to print numbers 1 to 5 with a 1-second delay between each.
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t.start();
Show in sidebar
Exam Tip: Understand the differences between extending Thread vs. implementing Runnable. Be ready to explain
thread states and priorities with examples.
Multiple threads accessing shared resources can cause race conditions (inconsistent data). Synchronization
ensures thread-safe access.
● Synchronized Methods: Use the synchronized keyword to lock the object’s monitor.
Example:
class Counter {
count++;
return count;
}
}
Example:
java
Copy
public void increment() {
synchronized(this) {
count++;
}
● A subclass can override a synchronized method, but synchronization isn’t inherited. Explicitly use
synchronized in the subclass if needed.
Example:
class Parent {
synchronized(this) { ... }
}
Thread Communication
Threads communicate using wait(), notify(), and notifyAll() within synchronized blocks:
class Buffer {
while (!empty) {
data = value;
empty = false;
while (empty) {
empty = true;
return data;
Practice Problem: Write a program with two threads: one producing numbers (1 to 5) and another consuming them
using wait and notify.
Exam Tip: Understand race conditions and how synchronization prevents them. Practice producer-consumer
scenarios and know the difference between notify and notifyAll.
3. AWT Components, Component Class, Container Class, Layout
Manager Interface, Default Layouts, Insets, and Dimensions
AWT Components
AWT (Abstract Window Toolkit) provides GUI components for building cross-platform interfaces.
● Component Class: Base class for all visual components (e.g., Button, Label, TextField).
○ Methods: setSize(), setLocation(), setVisible(), addMouseListener().
○ Example: Button btn = new Button("Click Me");
● Container Class: A component that can hold other components (e.g., Frame, Panel).
○ Methods: add(Component), setLayout(LayoutManager).
Example:
Frame frame = new Frame("My Window");
frame.add(new Button("OK"));
● Default Layouts:
○ Frame: BorderLayout.
○ Panel: FlowLayout.
● Common Layouts:
○ FlowLayout: Arranges components left-to-right, wraps to next line.
○ BorderLayout: Divides container into North, South, East, West, Center.
○ GridLayout: Arranges components in a grid (equal-sized cells).
○ CardLayout: Stacks components, showing one at a time.
○ GridBagLayout: Flexible grid with customizable cell sizes and spans.
import java.awt.*;
public MyFrame() {
setLayout(new BorderLayout());
add(new Button("Click"), BorderLayout.CENTER);
setSize(300, 200);
setVisible(true);
new MyFrame();
Practice Problem: Create a frame with three buttons arranged using GridLayout (1 row, 3 columns).
Exam Tip: Memorize default layouts and practice creating GUIs with different layout managers. Understand how
Insets affect component placement.
● Divides container into five regions: North, South, East, West, Center.
● Components stretch to fill their region.
Example:
Frame f = new Frame();
f.setLayout(new BorderLayout());
Flow Layout
Example:
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER));
p.add(new Button("One"));
p.add(new Button("Two"));
Grid Layout
Example:
Frame f = new Frame();
f.add(new Button("1"));
f.add(new Button("2"));
f.add(new Button("3"));
f.add(new Button("4"));
Card Layout
Example:
Panel cards = new Panel();
cards.setLayout(cl);
GridBagLayout
● Flexible grid where components can span multiple cells and have custom weights.
● Uses GridBagConstraints to specify position (gridx, gridy), size (gridwidth, gridheight), and weight (weightx,
weighty).
Example:
Frame f = new Frame();
f.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 1;
Practice Problem: Create a frame with a GridBagLayout containing two buttons spanning different cells.
import java.awt.*;
public GridBagExample() {
setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
setSize(300, 200);
setVisible(true);
new GridBagExample();
Exam Tip: Practice creating layouts and know the unique features of each (e.g., GridBagLayout’s flexibility). Be
ready to write code for a specific layout.
Events represent user interactions (e.g., mouse clicks, key presses) or system actions (e.g., window closing).
Event Models
import java.awt.*;
import java.awt.event.*;
public EventDemo() {
setLayout(new FlowLayout());
btn.addActionListener(new ActionListener() {
System.out.println("Button clicked!");
});
add(btn);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
setSize(200, 100);
setVisible(true);
new EventDemo();
}
Specific Events
Practice Problem: Create a frame with a button that changes its label to “Clicked” when pressed, and closes the
window on window close.
import java.awt.*;
import java.awt.event.*;
public ButtonEventDemo() {
setLayout(new FlowLayout());
btn.addActionListener(new ActionListener() {
btn.setLabel("Clicked");
});
add(btn);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
setSize(200, 100);
setVisible(true);
new ButtonEventDemo();
Exam Tip: Memorize key listener interfaces and their methods. Practice writing event handlers for buttons, mouse
clicks, and window events.
○
Exam-Focused Tips
● Common Questions:
○ Write code to create and synchronize threads.
○ Explain wait, notify, and thread states.
○ Create a GUI with a specific layout and event handling.
○ Compare layout managers or implement event listeners.
Stream Filters
Filter streams wrap other streams to add functionality (e.g., buffering, data conversion).
Buffered Streams
Example:
import java.io.*;
String line;
writer.write(line + "\n");
reader.close();
writer.close();
}
Example:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"));
dos.writeInt(42);
dos.writeDouble(3.14);
dos.close();
System.out.println(dis.readInt()); // 42
System.out.println(dis.readDouble()); // 3.14
dis.close();
Print Stream
Example:
PrintStream ps = new PrintStream(new FileOutputStream("log.txt"));
ps.close();
Example:
]
RandomAccessFile raf = new RandomAccessFile("data.dat", "rw");
System.out.println(raf.readInt()); // 100
raf.close();
Practice Problem: Write a program to read a text file using BufferedReader and write its contents to another file in
reverse order.
Exam Tip: Understand the hierarchy of stream classes (byte vs. character, buffered vs. unbuffered). Practice
combining streams (e.g., DataInputStream with BufferedInputStream).
JDBC Steps
import java.sql.*;
try {
// Load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Connect
// Create statement
// Execute query
ResultSet rs = stmt.executeQuery("SELECT id, name FROM employees");
// Process results
while (rs.next()) {
// Close resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
Notes:
Practice Problem: Write a JDBC program to insert a record into a students table using PreparedStatement.
Exam Tip: Memorize the JDBC steps and know driver classes/URLs for Oracle and MS-SQL. Practice writing
queries with PreparedStatement and handling SQLException.
3. Object Serialization
Object serialization converts an object’s state to a byte stream for storage or transmission, and deserialization
reconstructs the object.
Example:
import java.io.*;
class Person implements Serializable {
String name;
int age;
this.name = name;
this.age = age;
// Serialize
oos.writeObject(p);
oos.close();
// Deserialize
ois.close();
}
Practice Problem: Serialize a Student object with fields id, name, and grade (make grade transient).
Exam Tip: Understand Serializable and transient. Be ready to explain why serialization is useful for networking or
persistence.
4. Sockets
Sockets enable network communication between client and server using TCP or UDP.
● TCP Sockets:
○ ServerSocket: Listens for client connections.
○ Socket: Represents a client or server connection.
● UDP Sockets: Use DatagramSocket and DatagramPacket (connectionless).
import java.io.*;
import java.net.*;
out.println("Hello, Client!");
client.close();
server.close();
// Client
System.out.println(in.readLine());
socket.close();
}
Practice Problem: Modify the server to echo back client messages until the client sends “exit”.
Exam Tip: Understand TCP socket setup (client connects, server accepts). Practice simple client-server
communication.
import java.io.*;
import java.net.*;
while (true) {
this.client = client;
try {
String input;
if (input.equals("exit")) break;
client.close();
} catch (IOException e) {
e.printStackTrace();
Exam Tip: Practice writing a multithreaded server with proper synchronization if shared resources are involved.
Understand client-server interaction.
● Components:
○ Remote Interface: Extends java.rmi.Remote, declares methods with throws RemoteException.
○ Server: Implements the interface, registers with RMI registry.
○ Client: Looks up the remote object and invokes methods.
Example:
// Remote Interface
import java.rmi.Remote;
import java.rmi.RemoteException;
// Server Implementation
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
registry.bind("Hello", obj);
// Client
import java.rmi.registry.*;
System.out.println(stub.sayHello());
}
Practice Problem: Create an RMI application for a calculator service with add and subtract methods.
Exam Tip: Understand RMI setup (interface, server, client, registry). Be ready to write a simple RMI program or
explain the role of the registry.
● Steps:
1. Write Java class with native methods.
2. Compile to generate header file (javah or javac -h).
3. Implement native methods in C/C++.
4. Compile native code into a shared library (e.g., .dll, .so).
5. Load library in Java using System.loadLibrary().
Example:
// Java
static {
System.loadLibrary("NativeLib");
new NativeExample().sayHello();
}
// C (NativeLib.c)
#include <jni.h>
#include <stdio.h>
#include "NativeExample.h"
Practice Problem: Write a JNI program to call a C function that returns the square of a number.
Exam Tip: Understand JNI’s purpose (e.g., accessing hardware, performance). Be ready to outline the steps or write
a simple JNI declaration.
The java.util package provides the Collections Framework for managing groups of objects.
● Core Interfaces:
○ Collection: Root interface (e.g., Set, List).
○ Set: No duplicates (e.g., HashSet, TreeSet).
○ List: Ordered, allows duplicates (e.g., ArrayList, LinkedList).
○ Map: Key-value pairs (e.g., HashMap, TreeMap).
○ Iterator: Traverses collections (hasNext(), next()).
○ ListIterator: Bidirectional traversal for List.
Legacy Classes
Example:
Vector<String> v = new Vector<>();
v.add("A");
v.add("B");
Enumeration<String> e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
Modern Collections
Example:
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
set.add(1);
set.add(2);
map.put("Alice", 25);
map.put("Bob", 30);
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Practice Problem: Write a program to store student names and scores in a HashMap and iterate over it using an
Iterator.
Exam Tip: Compare legacy (Vector, Hashtable) vs. modern (ArrayList, HashMap) collections. Practice iterating with
Iterator and for-each.
Exam-Focused Tips
● Common Questions:
○ Write code for file I/O using buffered streams or RandomAccessFile.
○ Implement a JDBC program with PreparedStatement.
○ Create a client-server application or RMI service.
○ Use collections to solve a problem (e.g., remove duplicates with HashSet).
○ Explain JNI steps or serialization.
● Key Examples to Master:
○ File copy with BufferedInputStream.
○ JDBC query with error handling.
○ Multithreaded echo server.
○ RMI calculator service.
○ Collection iteration with HashMap.