I. Core Java Fundamentals
Control Flow Statements
-
Iteration statements:
-
for:for(init; condition; update) { // body }– use when number of iterations known. -
while:while(condition) { // body }– check before execution. -
do-while:do { // body } while(condition);– executes at least once.
-
-
Jump statements:
-
break: exits loop or switch immediately. -
continue: skips current iteration, proceeds to next. -
return: exits method, optionally returns value.
-
[!TIP] Common Pitfall: Using
continueindo-whilemay skip update, causing infinite loop.
Object-Oriented Programming (OOP) Concepts
Java supports OOP via:
-
Encapsulation: Bundling data (private fields) and methods (public getters/setters).
-
Inheritance:
extendskeyword for single inheritance; multiple inheritance via interfaces. -
Polymorphism: Method overloading (compile-time) and overriding (runtime).
-
Abstraction: Abstract classes/interfaces hide implementation.
Multiple Inheritance in Java:
-
Achieved using interfaces (a class can
implementmultiple interfaces). -
Interfaces can have
default/staticmethods (Java 8+).
Abstract Class vs Interface:
| Feature | Abstract Class | Interface |
|---|---|---|
| Inheritance | Single (extends) |
Multiple (implements) |
| Methods | Abstract + concrete | Abstract + default/static (Java 8+) |
| Variables | Any access modifier | public static final by default |
| Constructor | Yes | No |
| Purpose | Share code among related classes | Define contract for unrelated classes |
Classes and Objects
-
Class declaration:
class ClassName { // fields, methods } -
Object creation:
ClassName obj = new ClassName(); -
Instance variables/methods: Non-static, belong to each object.
Constructors
-
Types:
-
Default: No-arg, provided by JVM if no other constructor.
-
Parameterized: Accepts arguments.
-
Copy constructor: Takes object of same class (Java doesn't have built-in; must define manually).
-
-
Example: Area of Circle using Constructor
class Circle { double radius; Circle(double r) { radius = r; } double area() { return Math.PI * radius * radius; } }
Methods and Polymorphism
-
Method overloading: Same method name, different parameters (compile-time).
-
Method overriding: Subclass redefines superclass method (runtime).
-
Dynamic Method Dispatch: Overridden method called based on object type at runtime.
class Animal { void sound() { System.out.println("Animal"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } Animal a = new Dog(); a.sound(); // Output: Bark
Keywords
-
static:-
Static variables: Class-level, shared among all objects.
-
Static methods: Can access only static members; called via
ClassName.method(). -
Static block: Executes once when class loads.
-
-
final:-
Final variable: Constant (cannot reassign).
-
Final method: Cannot be overridden.
-
Final class: Cannot be inherited.
-
[!TIP]
staticmembers belong to class, not instance;finalensures immutability/restriction.
Packages and Access Protection
-
Creating package:
package com.example;at file start. -
Using package:
import com.example.*;or specific class. -
Access levels:
| Modifier | Same Class | Same Package | Subclass | Everywhere |
|---|---|---|---|---|
private |
Yes | No | No | No |
| (default) | Yes | Yes | No | No |
protected |
Yes | Yes | Yes | No |
public |
Yes | Yes | Yes | Yes |
- Accessing across packages: Only
public/protected(via inheritance) members accessible.
II. Exception Handling
Fundamentals
-
Exception: Recoverable condition (e.g.,
IOException). -
Error: Unrecoverable (e.g.,
OutOfMemoryError). -
Mechanism:
try { // risky code } catch (ExceptionType e) { // handler } finally { // always executes (cleanup) }
Throwing Exceptions
-
throw: Explicitly throw an exception object.if (age < 18) throw new ArithmeticException("Underage"); -
throws: Method declaration indicating possible exceptions.void readFile() throws IOException { ... }
Assertions
-
Purpose: Debugging/testing; check assumptions.
-
Syntax:
assert condition; // throws AssertionError if false assert condition : "message"; // with message -
Enabling/Disabling: Runtime flags
-ea(enable) or-da(disable).
Built-in Exceptions
-
ArithmeticException: e.g., division by zero. -
NullPointerException: accessing null object. -
ArrayIndexOutOfBoundsException: invalid array index. -
IOException: I/O failure.
Custom Exceptions
-
Extend
Exception(checked) orRuntimeException(unchecked).class MyException extends Exception { MyException(String msg) { super(msg); } }
Example Programs
-
Try-catch-finally:
try { int a = 10/0; } catch (ArithmeticException e) { System.out.println("Divide by zero: " + e); } finally { System.out.println("Cleanup"); } -
Throw and throws:
void validate(int age) throws MyException { if (age < 18) throw new MyException("Invalid age"); }
III. Multithreading
Introduction
-
Need: Concurrent execution, better CPU utilization.
-
Thread vs Process:
| Thread | Process |
|---|---|
| Lightweight | Heavyweight |
| Shares memory space | Separate memory space |
| Created within process | Created by OS |
Thread Creation
-
Extending
Threadclass:class MyThread extends Thread { public void run() { System.out.println("Thread running"); } } MyThread t = new MyThread(); t.start(); -
Implementing
Runnableinterface (preferred):class MyRunnable implements Runnable { public void run() { ... } } Thread t = new Thread(new MyRunnable()); t.start();
Thread Lifecycle
States (with transitions):
-
New: Thread created but not started.
-
Runnable:
start()called; ready to run. -
Running: Executing.
-
Blocked/Waiting: Waiting for resource/sleep/join.
-
Terminated:
run()completed or killed.
Thread Synchronization
-
Need: Prevent race conditions when multiple threads access shared resources.
-
synchronizedkeyword:-
Synchronized method:
synchronized void method() { ... }– locks onthis. -
Synchronized block:
synchronized(obj) { ... }– locks on specified object.
-
-
Example (bank account):
class Account { private int balance; synchronized void deposit(int amt) { balance += amt; } synchronized int getBalance() { return balance; } }
Inter-Thread Communication
-
wait(): Releases lock, waits until notified. -
notify(): Wakes one waiting thread. -
notifyAll(): Wakes all waiting threads. -
Producer-Consumer example:
synchronized void produce() { while (full) wait(); // add item notifyAll(); }
Thread Management
-
Priorities:
Thread.MIN_PRIORITYtoThread.MAX_PRIORITY; OS-dependent scheduling. -
ThreadGroup: Group threads for collective control (deprecated in Java 9+).
Example Programs
-
Three threads with intervals:
class MsgThread extends Thread { String msg; int interval; MsgThread(String m, int i) { msg=m; interval=i; } public void run() { while(true) { System.out.println(msg); Thread.sleep(interval*1000); } } } // Create threads: new MsgThread("Hello!",1), new MsgThread("Wear Mask!",2), new MsgThread("Use Sanitizer!",5)
IV. Input/Output (I/O) Streams
Stream Fundamentals
-
Byte streams: Handle raw binary data (
InputStream/OutputStream). -
Character streams: Handle text (Unicode) (
Reader/Writer). -
Hierarchy:
| Byte Streams | Character Streams |
|---|---|
InputStream |
Reader |
OutputStream |
Writer |
FileInputStream |
FileReader |
FileOutputStream |
FileWriter |
BufferedInputStream |
BufferedReader |
PrintStream |
PrintWriter |
Character Stream Classes
-
FileReader/FileWriter: Basic file read/write (character-by-character). -
BufferedReader: Efficient reading withreadLine(). -
PrintWriter: Convenientprint()/println(); auto-flush option.
File Operations
-
Reading:
BufferedReader br = new BufferedReader(new FileReader("file.txt")); String line; while ((line = br.readLine()) != null) { /* process */ } -
Writing:
PrintWriter pw = new PrintWriter(new FileWriter("output.txt")); pw.println("Hello"); -
Copying file (character streams):
BufferedReader br = new BufferedReader(new FileReader("source.txt")); PrintWriter pw = new PrintWriter(new FileWriter("dest.txt")); String line; while ((line = br.readLine()) != null) pw.println(line); br.close(); pw.close();
Standard I/O Streams
-
System.in(InputStream),System.out(PrintStream),System.err(PrintStream). -
Capturing input:
-
Scanner:Scanner sc = new Scanner(System.in); int n = sc.nextInt(); -
BufferedReader:BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine();
-
[!TIP] Use
Scannerfor simple input;BufferedReaderfor faster large input.
V. Graphical User Interface (GUI) Programming
AWT (Abstract Window Toolkit)
-
Components:
Button,Label,TextField,TextArea,Checkbox,Choice,List. -
Containers:
Frame(top-level),Panel(generic),Applet(embedded). -
Layout Managers:
-
FlowLayout: Left-to-right, wraps. -
BorderLayout: North, South, East, West, Center. -
GridLayout: Rows/columns grid. -
CardLayout: Stacked components (like cards).
-
Event Handling
-
Event Delegation Model:
-
Event Source: Component generating event (e.g., button).
-
Event Object:
ActionEvent,MouseEvent, etc. -
Event Listener: Interface (
ActionListener,MouseListener) with handler method. -
Registration:
button.addActionListener(this);
-
-
Adapter Classes: Provide empty implementations (e.g.,
MouseAdapter) to avoid overriding all methods.
Swing
-
Lightweight vs Heavyweight: Swing components (
JButton,JFrame) are lightweight (pure Java), AWT are heavyweight (native peers). -
Common Components:
JFrame,JPanel,JButton,JLabel,JTextField,JTextArea. -
Example: Sum of two numbers
JFrame f = new JFrame("Sum"); JTextField t1 = new JTextField(10), t2 = new JTextField(10), res = new JTextField(10); JButton b = new JButton("Add"); b.addActionListener(e -> { int a = Integer.parseInt(t1.getText()); int b = Integer.parseInt(t2.getText()); res.setText(String.valueOf(a+b)); }); // Add components to frame with layout, set size, setVisible(true)
Applets
-
Lifecycle:
-
init(): First call, initialize resources. -
start(): Called afterinit(), or when applet becomes visible. -
stop(): Called when applet is invisible. -
destroy(): Final cleanup, called before unloading.
-
-
HTML Tags:
<applet code="MyApplet.class" width="300" height="200"></applet>(deprecated in HTML5). -
Differences from Applications:
-
Applets run in browser, no
main(). -
Security restrictions: no file access, network access only to host.
-
-
Security: Sandbox model; unsigned applets heavily restricted.
VI. Networking
Socket Programming
-
Socket: Client endpoint. -
ServerSocket: Server endpoint, listens for connections. -
Client-Server Model:
-
Server:
ServerSocket ss = new ServerSocket(port); Socket s = ss.accept(); -
Client:
Socket s = new Socket(host, port);
-
Client-Server Communication Steps
-
Server:
-
Create
ServerSocketon port. -
Accept connection (
accept()returnsSocket). -
Get I/O streams:
InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); -
Read/write using streams.
-
Close sockets.
-
-
Client:
-
Create
Socketto server host/port. -
Get I/O streams.
-
Read/write.
-
Close.
-
Example Program (Echo)
-
Server:
ServerSocket ss = new ServerSocket(1234); Socket s = ss.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(), true); String line; while ((line = in.readLine()) != null) { out.println("Echo: " + line); } -
Client: Similar, connects to server, sends lines, prints echoes.
VII. Database Connectivity (JDBC)
JDBC Architecture
-
JDBC Drivers:
-
Type 1: JDBC-ODBC Bridge (uses ODBC driver, platform-dependent).
-
Type 2: Native API (partly Java, partly native).
-
Type 3: Network Protocol (middleware server).
-
Type 4: Pure Java (thin driver, connects directly to DB; most common).
-
-
JDBC-ODBC Bridge:
sun.jdbc.odbc.JdbcOdbcDriver(removed in Java 8).
Steps to Use JDBC
-
Load driver:
Class.forName("com.mysql.cj.jdbc.Driver"); -
Establish connection:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass"); -
Create statement:
-
Statement stmt = con.createStatement(); -
PreparedStatement pstmt = con.prepareStatement("INSERT INTO table VALUES (?, ?)"); -
CallableStatement cstmt = con.prepareCall("{call proc(?)}");
-
-
Execute query:
-
ResultSet rs = stmt.executeQuery("SELECT * FROM table");(for SELECT) -
int rows = stmt.executeUpdate("INSERT ...");(for INSERT/UPDATE/DELETE)
-
-
Process results:
while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); } -
Close connections (try-with-resources recommended):
try (Connection con = ...; Statement stmt = ...; ResultSet rs = ...) { // use resources } // auto-close
Example Programs
-
SELECT:
Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name FROM students"); while (rs.next()) System.out.println(rs.getString(1)); -
INSERT with PreparedStatement (prevents SQL injection):
PreparedStatement pstmt = con.prepareStatement("INSERT INTO students(name,age) VALUES(?,?)"); pstmt.setString(1, "John"); pstmt.setInt(2, 20); pstmt.executeUpdate();
VIII. Java Beans and Introspection
Java Beans
-
Characteristics:
-
No-arg constructor.
-
Getter/setter methods for properties (e.g.,
getName(),setName(String n)). -
Serializable (optional but common for persistence).
-
-
Use cases: Reusable components in IDEs, JSP, Swing.
Introspection
-
Purpose: Discover bean properties, events, methods at runtime (for GUI builders).
-
How it works: Uses
BeanInfointerface andPropertyDescriptorclasses.-
JVM reads bean class, analyzes getter/setter patterns.
-
Introspector.getBeanInfo(MyBean.class)returnsBeanInfo.
-
BeanInfo Interface
-
Provides explicit bean information (overrides default introspection).
-
Methods:
-
PropertyDescriptor[] getPropertyDescriptors(): Returns array of property descriptors. -
MethodDescriptor[] getMethodDescriptors(): Returns method descriptors. -
EventSetDescriptor[] getEventSetDescriptors(): Returns event descriptors.
-
-
Example:
public class MyBeanInfo extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { PropertyDescriptor pd = new PropertyDescriptor("name", MyBean.class); return new PropertyDescriptor[]{pd}; } }
Example
-
Bean:
public class PersonBean implements Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } -
Introspection:
BeanInfo info = Introspector.getBeanInfo(PersonBean.class); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { System.out.println(pd.getName()); }
IX. JNDI (Java Naming and Directory Interface)
JNDI Basics
-
Purpose: Access naming/directory services (e.g., LDAP, DNS, RMI registry).
-
InitialContext: Entry point; configured via environment properties. -
Contextinterface: Core operations (bind, lookup, etc.).
Context Operations (Syntax)
-
bind(String name, Object obj): Binds name to object.Context ctx = new InitialContext(); ctx.bind("java:comp/env/jdbc/MyDB", dataSource); -
rebind(String name, Object obj): Binds or rebinds name. -
createSubcontext(String name): Creates new subcontext.ctx.createSubcontext("java:comp/env"); -
getAttributes(String name): Returns attributes of named object.Attributes attrs = ctx.getAttributes("java:comp/env/jdbc/MyDB"); -
modifyAttributes(Attributes attrs, int modOp): Modifies attributes (e.g.,Context.ADD_ATTRIBUTE).
Syntax and Usage
-
Lookup:
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB"); -
Common in enterprise apps: JNDI used to look up DataSource, EJB, JMS queues.
X. Memory Management and Assertions
Garbage Collection
-
Automatic: JVM reclaims memory from unreachable objects.
-
System.gc()/Runtime.gc(): Suggests GC; not guaranteed. -
finalize(): Called before object is collected (deprecated in Java 9+; useCleanerortry-with-resources). -
Generational GC:
-
Young Generation: New objects; minor GC.
-
Old Generation: Long-lived objects; major GC.
-
Permanent Generation (Java 7-) / Metaspace (Java 8+): Class metadata.
-
Assertions
-
Purpose: Debugging; verify assumptions.
-
Syntax:
assert x > 0; // simple assert x > 0 : "x must be positive"; // with message -
Enabling/Disabling:
-
Runtime:
java -ea MyProgram(enable all),java -da MyProgram(disable). -
Per-class:
java -ea:com.example... MyProgram.
-
-
Guidelines: Use for internal invariants, not for argument validation (use exceptions).
XI. Problem Solving and Example Programs
Number Problems: nth Prime Number
-
Algorithm:
-
Initialize count = 0, num = 2.
-
While count < n:
-
Check if
numis prime (test divisibility from 2 to √num). -
If prime, increment count.
-
If count == n, return num.
-
Else, num++.
-
-
-
Code:
static boolean isPrime(int n) { if (n <= 1) return false; for (int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } static int nthPrime(int n) { int count = 0, num = 2; while (count < n) { if (isPrime(num)) count++; if (count == n) return num; num++; } return -1; }
GUI Applications: Swing Sum of Two Numbers
- As in Section V (Swing example).
Multithreading Applications: Three Threads
- As in Section III (example program).
File Handling: Copy File Using Character Streams
- As in Section IV (file copying example).
Client-Server Applications: Echo Program
- As in Section VI (example program).
XII. Additional Topics from Past Papers (Java-Specific)
Note: Only Java Programming past papers (Dec 2024, Nov 2022) considered; AI topics excluded.
-
Nth Prime Number: Covered in XI.
-
Swing Program (Sum of Two Numbers): Covered in V.
-
Three Threads with Intervals: Covered in III.
-
File Copy with Character Streams: Covered in IV.
-
Client-Server Communication: Covered in VI.
-
Thread Synchronization Example (Bank account): Covered in III.
-
Exception Handling with
try-catch-finally: Covered in II. -
Applet Lifecycle: Covered in V.
-
Dynamic Method Dispatch: Covered in I.
-
Abstract Class vs Interface: Covered in I.
-
Static and Final Keywords: Covered in I.
-
Constructor Types (Area of Circle): Covered in I.
-
Iteration and Jump Statements: Covered in I.
-
JDBC Steps: Covered in VII.
-
Java Beans Introspection: Covered in VIII.
-
JNDI Methods: Covered in IX.
-
Garbage Collection: Covered in X.
-
Assertions: Covered in X.
-
Throw and Throws: Covered in II.
[!TIP] Past papers emphasize: OOP concepts, multithreading (synchronization, inter-thread communication), I/O (file handling), GUI (Swing/AWT, applets), exception handling, JDBC basics, and simple problem-solving (nth prime, sum). Practice coding these thoroughly.