0% found this document useful (0 votes)
13 views141 pages

Oops With Java Notes

The document provides comprehensive notes on Object-Oriented Programming (OOP) with Java, detailing programming paradigms, characteristics of OOP, advantages, and the structure of Java programs. It highlights the evolution of Java, its importance, features, and the role of the Java Virtual Machine (JVM) in ensuring platform independence. Key concepts such as encapsulation, inheritance, polymorphism, and abstraction are explained, along with comparisons to object-based programming languages.

Uploaded by

kirpabajaj2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views141 pages

Oops With Java Notes

The document provides comprehensive notes on Object-Oriented Programming (OOP) with Java, detailing programming paradigms, characteristics of OOP, advantages, and the structure of Java programs. It highlights the evolution of Java, its importance, features, and the role of the Java Virtual Machine (JVM) in ensuring platform independence. Key concepts such as encapsulation, inheritance, polymorphism, and abstraction are explained, along with comparisons to object-based programming languages.

Uploaded by

kirpabajaj2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OOPS WITH JAVA NOTES

UNIT 1: Object-Oriented Programming (OOP) Paradigm

1. Introduction to Programming Paradigms

A programming paradigm is a style or methodology of programming. It defines how we


write code, structure logic, and solve problems in programming. Different paradigms approach
problems differently, affecting the design, implementation, and maintainability of software.

1.1 Major Programming Paradigms

1. Procedural Programming (PP)

o Focus: Procedures or routines (functions).

o Example: C, Fortran, Pascal.


o Features:

▪ Program is divided into functions.

▪ Data is separate from functions.

▪ Uses top-down design.

o Limitation: Difficult to maintain as programs grow; data and functions are not
bundled together.

2. Object-Oriented Programming (OOP)

o Focus: Objects and classes.

o Example: Java, C++, Python.


o Features:

▪ Combines data and functions (methods) into objects.

▪ Supports inheritance, encapsulation, polymorphism, and abstraction.

o Benefit: More modular, reusable, maintainable, and closer to real-world


modeling.

3. Functional Programming (FP)

o Focus: Mathematical functions.


o Example: Haskell, Lisp, Scala.
o Features:

▪ No side-effects, functions return new values without changing data.

▪ Supports recursion and higher-order functions.

o Benefit: Easier to reason about, suitable for concurrent and parallel


programming.

4. Logic Programming (LP)

o Focus: Facts and rules.


o Example: Prolog.

o Features:
▪ Based on logical reasoning.

▪ Uses queries to derive conclusions from given facts and rules.

1.2 Comparison of Programming Paradigms

Feature Procedural Object-Oriented Functional Logic

Functions
Focus Functions/Procedures Objects/Classes Logic/Rules
(stateless)

Encapsulated inside Facts &


Data Handling Separate from code Immutable
objects Rules

High (inheritance &


Reusability Limited Medium Medium
polymorphism)

Real-world
Difficult Easy Moderate Moderate
Modeling

Example
C, Pascal Java, C++, Python Haskell, Lisp Prolog
Languages

Diagrammatic Comparison of Paradigms:


Real World Problem

+---------------------------+

| |
Procedural Object-Oriented

(Functions) (Objects & Classes)

| |

Functions act on Data Objects encapsulate Data + Functions

2. Object-Oriented Programming (OOP)

Definition:
Object-Oriented Programming is a programming methodology based on the concept of
objects. It focuses on modular design, reusability, and real-world problem modeling.

In OOP, everything is represented as objects, which have attributes (data) and methods
(functions).

2.1 Characteristics of OOP Languages

OOP languages have distinct features that differentiate them from procedural or functional
languages.

1. Encapsulation

o Bundling data (attributes) and methods (functions) together into a single unit
called a class.

o Purpose: Hides internal details and protects data (Data Hiding).

o Example:
o class BankAccount {

o private int balance; // hidden data

o public void deposit(int amt) { balance += amt; }

o public int getBalance() { return balance; }


o }
2. Inheritance

o Mechanism where one class (child/subclass) acquires properties and behaviors of


another class (parent/superclass).

o Purpose: Code reuse and hierarchy representation.

o Types:

▪ Single inheritance

▪ Multiple inheritance (supported in C++, not in Java)


▪ Multilevel inheritance

▪ Hierarchical inheritance
o Diagram:

o Vehicle

o / \

o Car Bike

3. Polymorphism
o Ability of an object to take many forms.

o Types:

▪ Compile-time (Static) Polymorphism: Method overloading, Operator


overloading.

▪ Run-time (Dynamic) Polymorphism: Method overriding.

o Example:
o class Shape { void draw() { } }

o class Circle extends Shape { void draw() { [Link]("Circle"); } }

o class Square extends Shape { void draw() { [Link]("Square"); } }

4. Abstraction
o Representing only essential features while hiding complex implementation.

o Purpose: Simplifies design, hides unnecessary details.

o Example: Abstract classes, Interfaces in Java.


5. Objects
o Instances of a class.

o Have state (attributes) and behavior (methods).

o Example: BankAccount account1 = new BankAccount();

6. Classes
o Blueprints for creating objects.

o Define attributes and methods.

o Example:

o class Car {

o String color;

o void drive() { [Link]("Driving"); }

o }

7. Message Passing
o Objects communicate by sending messages (calling methods of other objects).

o Example: [Link](500);

8. Dynamic Binding

o Code to be executed for a method call is determined at runtime, especially in


overriding scenarios.

2.2 Advantages of OOP

• Easier to understand and maintain.

• Promotes reusability via inheritance.


• Models real-world scenarios naturally.

• Encapsulation ensures data security.

• Supports flexibility and scalability in large projects.

3. Object-Based Programming Languages


Definition:
Object-Based languages support objects and encapsulation but do not support inheritance
and polymorphism.

• These languages allow creation and manipulation of objects, but cannot establish
class hierarchies.

Examples:

• JavaScript (without classical inheritance), Visual Basic 6 (earlier versions).

Key Points:

• Supports: Objects, Encapsulation.

• Does not support: Inheritance, Polymorphism.

• Ideal for small-scale object-based applications.

Comparison: OOP vs Object-Based Languages

Feature Object-Oriented Object-Based

Inheritance Yes No

Polymorphism Yes No

Encapsulation Yes Yes

Abstraction Yes Limited

Examples Java, C++ JavaScript, VB6

4. Diagrammatic Overview of OOP Concepts

Class (Blueprint)

| creates
v

Object (Instance)

|
| has
v

Attributes + Methods

+----------------------------+
| Key OOP Features |

| - Encapsulation |

| - Inheritance |

| - Polymorphism |

| - Abstraction |

+----------------------------+

5. Summary
• Programming Paradigm: Style/method of programming.

• Procedural vs OOP: OOP combines data and functions in objects, unlike PP which
separates them.

• OOP Characteristics: Encapsulation, Inheritance, Polymorphism, Abstraction.

• Object-Based Languages: Support objects but lack inheritance and polymorphism.

• Advantages: Modularity, maintainability, real-world modeling, reusability.

6. FAQs for Revision

1. Q: What is the main difference between procedural and object-oriented programming?


A: Procedural programming focuses on functions, OOP focuses on objects that combine
data and behavior.

2. Q: Name the four main characteristics of OOP.


A: Encapsulation, Inheritance, Polymorphism, Abstraction.

3. Q: Can object-based languages support inheritance?


A: No, they support objects but not inheritance or polymorphism.
4. Q: Why is OOP considered more maintainable than procedural programming?
A: Because it encapsulates data and methods, allows reusability, and models real-world
entities.

Here are comprehensive notes on Java Fundamentals (as per an MCA syllabus of
Guru Gobind Singh Indraprastha University, Delhi) covering all the topics you listed —
definitions, types, detailed explanations, diagrams and examples — written so that both
beginners (even a 10-year-old) and faculty can follow. I’ve broken it into major sections,
which you can use for exam preparation. You may print or convert into PDF for your revision.

1. Brief History of Java

1.1 What is Java?


• Java is a high-level, class-based, object-oriented programming language.

• It was designed to have as few implementation dependencies as possible — “Write Once,


Run Anywhere” (WORA) — meaning compiled Java code should run on any platform
with a Java Virtual Machine (JVM).
• Java is used for a wide variety of applications: desktop, mobile (Android), enterprise
servers, embedded systems.

1.2 Why and how Java came into being


• In the early 1990s, a team at Sun Microsystems (led by James Gosling, Mike Sheridan,
Patrick Naughton) started a project called Oak (initially for embedded smart-appliances)
in 1991.

• Oak eventually became Java (in 1995) when the web was booming and Sun realised that
a portable, network-oriented, safe language would be very useful.

• Java 1.0 was released by Sun in 1995. Later Sun was acquired by Oracle Corporation.

• Over time, Java has evolved: Java2 (J2SE), Java 5 (generics, annotations), Java 8
(lambdas, streams), later versions with modularity (Java 9+), etc.

1.3 Key milestones

• 1995: Java 1.0 released.


• 1996: Java Applets, etc.
• 2004: Java 5 introduced generics, enhanced for-loop, etc.
• 2014-15: Java 8 with lambdas and streams.

• After 2017 there were faster release cycles (Java 9, 10, 11 LTS, etc.).

• Today Java is widely used in enterprise, Android, backend services.

1.4 Why study Java now?


• Java remains one of the most popular languages.

• Many enterprise systems run on Java.

• Understanding Java fundamentals gives a strong basis for programming and software
engineering.

• Java’s object-oriented architecture, portability, robustness, security features make it a


great language for teaching.

2. Structure of a Java Program

2.1 Source code to execution – overview

A simple flow:

.java (source code) → compile with javac → .class (bytecode) → run on JVM → native machine
executes

Here’s what happens:

1. Developer writes code in a .java file.

2. The Java compiler (javac) compiles it into a .class file containing Java bytecode.
3. The JVM loads the .class file, verifies it, and executes it (interprets JIT-compiles) on the
underlying operating system/hardware.
2.2 Example “Hello World” program

public class HelloWorld {

public static void main(String[] args) {

[Link]("Hello, world!");

}
Explain structure:
• public class HelloWorld → class declaration.

• { ... } → body of the class.

• public static void main(String[] args) → the entry method; every Java application starts
from main (in a simple scenario).

• [Link](...) → prints to console.

2.3 Typical parts of a Java program

• Package statement (optional): package [Link];


• Import statements (optional): import [Link].*;

• Class / Interface declarations: public class MyClass { … }


• Fields (attributes/variables) inside class.

• Methods inside class.

• Main method if it's an application: public static void main(String[] args)

• Comments: // single-line, /* multi-line */

• Statements & expressions inside methods.


2.4 Example with more elements

package mypkg;

import [Link];

public class Calculator {

// fields
private int result;

// constructor

public Calculator() {

[Link] = 0;
}
// method

public int add(int a, int b) {

return a + b;
}

public static void main(String[] args) {

Calculator calc = new Calculator();

int sum = [Link](5, 7);

[Link]("Sum is: " + sum);

}
Explain each part — package, import, class, fields, constructor, method, main etc.

2.5 Comments on good structure

• Class names start with uppercase, use CamelCase.

• Method names start with lowercase.

• Indentation, braces, readability matter.

• Each program file typically holds one public class named same as file ([Link]
→ class HelloWorld).

• Keep code modular: small methods, meaningful names.

3. Importance and Features of Java

3.1 Importance of Java

• Portability: Java bytecode runs on any platform with a compatible JVM. “Write Once,
Run Anywhere” (WORA).

• Object-Oriented: Encourages encapsulation, inheritance, polymorphism, modularity.

• Robustness: Exception handling, strong type checking, automatic memory management


(garbage collection).
• Security: Java’s runtime environment includes security features (class loader,
sandboxing) which make it suitable for networked applications.

• Performance: Although interpreted originally, modern JVMs (JIT compilation) provide


good performance.

• Rich Standard Library: Java offers extensive APIs for data structures, networking,
concurrency, UI, etc.

• Large Ecosystem: Many frameworks (Spring, Hibernate) and enterprise solutions built
on Java.

• Used in Academics: Java’s clear syntax and strict rules make it good for teaching
programming and software engineering.

3.2 Key Features of Java

Below are major features, with explanation:

Feature Description

Java syntax is simpler than C++: no explicit pointers, memory management


Simple
easier, fewer complex features (e.g., no multiple inheritance of classes).

Everything in Java is an object (except primitive types), designed around


Object-oriented
classes & objects. Promotes reuse.

Platform- Java source compiled to bytecode (.class) which runs on JVM for any
independent OS/hardware.

Java runtime environment provides a sandbox for running untrusted code


Secure
(e.g., applets), checks at compile time and runtime.

Emphasises early error detection (strong typing), garbage collection,


Robust
exception handling to reduce crashes.

Multithreaded Built-in support for threads ([Link]) for concurrent programming.

Architecture- Bytecode format is well-specified and independent of processor


neutral architecture.

Portable Size of data types is well defined, no platform-specific dependencies.

High- With JIT compilation and modern JVM optimisations, performance is quite
performance high.
Feature Description

Java has built-in networking libraries ([Link]) making it easy to write


Distributed
distributed applications.

Dynamic Java can dynamically load classes, link at runtime, support reflection, etc.

3.3 Why these features matter (for you as a student)

• Being simple and object-oriented makes Java good to learn and apply for complex
applications.

• Portability ensures that your code will run regardless of the underlying OS if you follow
standards.

• Security and robustness are important in today’s networked world — for safe
programming.

• Multithreading, distributed computing are key skills in MCA/industry.

• The rich standard library means you can build complex applications without rewriting
basic components.

4. Introduction to JVM and its Architecture (including set of instructions)

4.1 What is the JVM?

• Java Virtual Machine (JVM) is a software implementation of a “virtual machine” that


executes Java bytecode. According to the spec: “The Java Virtual Machine is an abstract
machine that provides a runtime environment in which Java bytecode can be executed.”
(Oracle Documentation)
• In simple terms: you compile Java source code into bytecode (.class files). The JVM
loads, verifies, interprets or compiles (JIT) this bytecode and executes it, interacting with
the underlying hardware/OS.

• Because each platform (Windows, Linux, Mac) has a JVM implementation, Java
becomes platform-independent: you compile once, run anywhere there’s a JVM.

4.2 Why is JVM important?


• Platform independence: through JVM, Java avoids being tied to a specific OS/processor.

• Memory and resource management: JVM manages memory (heap, stack) for Java
programs, with garbage collection.
• Security: JVM acts to load and verify code, enforcing safe execution (sandbox).
• Performance: modern JVMs include Just-In-Time (JIT) compilation and optimisations.

• Isolation: Java programs run inside JVM, separated from native system, providing a layer
of safety.

4.3 JVM Architecture – major components

Here is a high-level diagram:


Subsystems and areas

• Class Loader Subsystem: Responsible for loading class (.class) files into the JVM. Uses
a delegation model. (Java Code Geeks)

• Runtime Data Areas: Memory areas managed by JVM at runtime. These include:

o Method Area: storage for class structures (field & method data, constant pool).
(TutorialsPoint)

o Heap: storage for objects/instances.

o Java Stacks: each thread has its own stack, stores frames for method invocations.
o PC (Program Counter) Registers: each thread has a PC register pointing to current
instruction.

o Native Method Stacks: support execution of native (non-Java) methods.


• Execution Engine: Executes the bytecode. May use an interpreter, JIT compiler, garbage
collector. (Java Code Geeks)
• Native Method Interface & Libraries: For Java to call native code (C/C++ libraries)
when needed.
Flow of execution

1. Load class file →

2. Linking (verification, preparation, resolution) →

3. Initialization →

4. Execution engine executes methods on runtime data areas.


5. Garbage collection reclaims unused objects.
(TutorialsPoint)

Class Loader Delegation

Three primary class loaders:

• Bootstrap ClassLoader (loads core Java classes)


• Extension ClassLoader (loads extension libraries)

• Application/System ClassLoader (loads user classes)


They work in a delegation model (parent first) so classes are loaded in a hierarchy.
4.4 JVM Instruction Set (Bytecode)

• JVM uses bytecode instructions (single-byte opcodes plus operands) which the
execution engine executes. The specification lists dozens of instructions (load, store,
arithmetic, object creation, method invocation, control flow, exception handling). (Oracle
Documentation)

• Examples of instructions:

o iload_0 – load int from local variable 0

o invokevirtual – call an instance method

o if_icmpge – compare two ints and branch if greater or equal

o new – create a new object instance

o return – return from method

• The benefit: The same .class file can be executed on any JVM implementation: the
bytecode is standardised.

4.5 JVM Working in Simple Steps


1. Write .java source code.

2. Compile to .class (bytecode) using javac.

3. Launch JVM (via java command).

4. Class Loader loads the class.

5. Bytecode verifier checks code safety.

6. Preparation: allocate memory for static variables, etc.

7. Initialization: execute static initializers.


8. Execution Engine interprets/JIT-compiles the bytecode, using runtime data areas.

9. Garbage collector reclaims unused objects, runtime continues or finishes.

10. On program termination, the JVM exits.

4.6 Summary in simple terms for a 10-year-old

Imagine you wrote a story in English. Then you translate it into a special language (bytecode)
that can be read by any computer that has a “translator” (JVM). The translator loads your story,
checks it for bad words, then uses its own magic engine to perform your story’s instructions. All
machines can act the same because they all understand this special language.
5. Overview of JVM Programming

In this section we talk about what it means to “program for the JVM” or “programming at the
JVM level” (a brief introduction, since deep bytecode programming goes beyond basic courses).

5.1 JVM-level programming: what is it?

• Normally you write Java source code. Programming “for the JVM” means you think in
terms of bytecode instructions, class files, class loaders, runtime data areas.

• For example, frameworks or tools may generate or transform bytecode, manipulate class
files at load time, use instrumentation to monitor performance, or define custom class
loaders.
• This is advanced, but the basics (understanding how class loading, linking, execution
work) give you more power to understand how Java works under the hood.

5.2 Class file format (the .class file)

Since the JVM runs bytecode in the .class files, understanding their structure helps:
General layout (based on The Java® Virtual Machine Specification)

From the spec: “A class file consists of a single ClassFile structure.” (Oracle Documentation)
Key parts (in order) include:

• magic (u4): 0xCAFEBABE identifying the file as a Java class file. (Oracle
Documentation)

• minor_version, major_version (u2 each): indicate the version of class file format. (Oracle
Documentation)

• constant_pool_count and constant_pool: pool of constants (strings, numbers,


class/method references) used in the class. (Oracle Documentation)

• access_flags: flags like public, final, interface etc. (Oracle Documentation)


• this_class, super_class: indices in constant pool referring to class and its superclass.
(Oracle Documentation)

• interfaces_count, interfaces[]: list of interfaces this class implements. (Oracle


Documentation)

• fields_count, fields[]: description of fields (variables) declared in class. (Oracle


Documentation)

• methods_count, methods[]: description of methods declared in class (including code,


parameters etc). (Oracle Documentation)

• attributes_count, attributes[]: extra information (source file name, annotations, etc).


(Oracle Documentation)

Why this is important

• When you compile your Java source code, you produce this .class file structure. The JVM
loads it and understands how to execute methods, access fields etc by reading this
structure.
• Tools like bytecode manipulators, instrumentation agents, decompilers must understand
this structure.
5.3 Instrumentation of a Class File / Bytecode Engineering Libraries

What is instrumentation?

• Instrumentation in Java is “the addition of byte-codes to methods for the purpose of


gathering data to be utilized by tools.” (from the API docs) (Oracle Documentation)
• In simpler terms: you add extra instructions to an already compiled class (bytecode) to do
additional work (e.g., logging, performance monitoring, security checks) without
changing original source code.

Bytecode Engineering Libraries

• Libraries such as ASM, Javassist, and Apache BCEL allow developers to read, modify
and generate .class files (bytecode) programmatically. (Medium)

• For example BCEL: “a library for manipulating Java bytecode… allows to create,
analyse, and manipulate the files .class Java.” (Wikipedia)

• Use cases: profiling tools, coverage tools, AOP (aspect-oriented programming), code
obfuscation.

How instrumentation works (in brief)

• A Java Agent is a special JAR file that is loaded by the JVM at startup (via -javaagent) or
attached later.

• The agent gets an Instrumentation instance via premain(String agentArgs,


Instrumentation inst) or agentmain(…).

• The agent registers a ClassFileTransformer which intercepts class loading (or re-
definition) and can transform the byte array of the class before it is defined by the JVM.
(Medium)

• Example pseudo-code:
public class MyAgent {

public static void premain(String args, Instrumentation inst) {

[Link](new ClassFileTransformer() {

public byte[] transform(ClassLoader loader,

String className,

Class<?> classBeingRedefined,

ProtectionDomain protectionDomain,
byte[] classfileBuffer) {

// modify classfileBuffer (bytecode) as needed

return modifiedByteCode;
}
});

Why this matters


• Gives advanced control: you can add monitoring, instrumentation, diagnostics, or modify
behaviour at runtime without source changes.

• Helps understanding of how the JVM loads, links, and executes classes — making you a
deeper Java programmer.

5.4 Overview of Class Loaders & Sandbox Model of Security


Class Loaders Overview

• Every Java class is loaded by a ClassLoader. The Class Loader Subsystem handles:
loading, linking (verification, preparation, resolution), and initialization of classes. (Java
Code Geeks)

• Loading: given class name, find the corresponding .class file (or resource) and load it
into memory.

• Linking:
o Verification: ensure the bytecode is well-formed, safe.

o Preparation: allocate memory for static variables and set default values.

o Resolution: convert symbolic references (like method names in constant pool) into
direct references.
(TutorialsPoint)
• Initialization: assign actual values to static variables, execute static initializers in the
class.

• The delegation model ensures that bootstrap loader gets first chance to load a class;
prevents duplication and security issues.

Sandbox Model of Security


• Java was designed for networked/distributed applications (e.g., applets) where code from
untrusted sources might run.

• The sandbox model: untrusted code runs in a restricted environment (sandbox) where it
cannot access native OS functions, cannot read/write arbitrary files, cannot crash the
system.
• Key elements:

o Class Loader separates trusted and untrusted code.

o Bytecode Verifier prevents code from performing illegal operations (e.g., jumping
outside method, corrupting stack).

o Security Manager (in older Java) checked runtime permissions (file I/O, network
access).

o The runtime confines untrusted code, whereas trusted code (in libraries) runs
normally.

• Because of these mechanisms, Java is considered secure for running code from remote
sources.
5.5 Diagram summarising class loading & security
5.6 Summary: Overview of JVM programming

• Understand that Java source → bytecode → JVM execution.

• Knowing class file format, bytecode, class loader, instrumentation and security makes
you a more advanced Java developer.

• Even if your regular programming is at source level, awareness of how the JVM works is
a strong advantage (for performance tuning, debugging, using frameworks).

• Topics like instrumentation, class loaders, sandbox appear in advanced Java/enterprise


topics and can be a distinguishing factor in your MCA exams.

6. Basic Language Constructs of Java — Keywords, Constants, Variables, Operators,


Looping & Decision-Making Constructs

In this section, we go through the core programming constructs of Java, with definitions, types
where applicable, and explanations. This forms the backbone of Java programming for your
MCA syllabus.
6.1 Keywords

• Keywords are reserved words in Java; you cannot use them as identifiers (variable names,
method names, class names).
• Java has about ~50 keywords (this may vary slightly with version). Some common
keywords include: class, public, static, void, if, else, switch, while, for, new, try, catch,
finally, extends, implements, interface, package, import, etc.

• Purpose: they form the syntax of the Java language.

6.2 Constants

• A constant is a fixed value that cannot be changed by the program once it is defined.

• In Java, you typically declare constants using final keyword (and often static). For
example:

• public static final int MAX_VALUE = 100;

Types of constants

• Literal constants: numbers (123), characters ('A'), strings ("Hello"), boolean (true/false),
null.

• Final constants: variables declared final so their value cannot change.

6.3 Variables
• A variable is a name given to a memory location. It holds a data value of a particular type
and can change (unless declared final).
• Syntax for declaration:

• type variableName;

• type variableName = initialValue;

Types of variables (in Java)

• Primitive variables: hold basic data types (see below).


• Reference variables: hold references (addresses) to objects (instances of classes).

• Classification by scope / storage:

o Instance variables: defined in class, outside methods; each object has its own
copy.

o Class variables (static variables): defined with static modifier; one copy shared
among all objects of class.

o Local variables: defined inside methods, constructors or blocks; only accessible


within that method/block.
o Parameters: variables passed into methods.
Primitive data types

Built-in Java primitive types:

Type Description Size Example value

byte 8-bit signed integer 8 bits -128 to 127

short 16-bit signed integer 16 bits -32,768 to 32,767

int 32-bit signed integer 32 bits typical integer

long 64-bit signed integer 64 bits large integer values

float 32-bit floating-point 32 bits approx decimals

double 64-bit floating-point 64 bits more precision decimals

char 16-bit Unicode character 16 bits e.g., 'A', '₹'

boolean true or false not precisely defined bits true, false

(Note: size in bits as per Java spec)

Example of variable usage

int age = 20;

final double PI = 3.14159;


String name = "Ravi";

boolean isValid = true;

6.4 Operators

Operators are symbols that perform operations on operands (variables/values). Java supports
many operators.

Types of operators in Java

Category Description

Arithmetic operators +, -, *, /, % (modulus)

Unary operators +, -, ++, --, ! (logical NOT)

Assignment operators =, +=, -=, *=, /=, %=


Category Description

Relational (comparison) ops ==, !=, >, <, >=, <=

Logical operators && (AND), `

Bitwise operators &, `

Conditional operator (ternary) ?: – e.g., result = (a > b) ? a : b;

** instanceof operator** Checks whether object is an instance of a class/interface.

String concatenation operator + used to join strings.

Example of operators
int a = 10, b = 3;

int sum = a + b; // 13

int diff = a - b; // 7

int prod = a * b; // 30

int mod = a % b; // 1

a++; // a becomes 11

boolean check = (a > b) && (b < 5); // true


String msg = "Sum is: " + sum; // "Sum is: 13"

int max = (a > b) ? a : b; // ternary operator

6.5 Decision-Making Constructs

Decision-making constructs let the program choose which path to take based on conditions.

if statement

if (condition) {

// block if condition is true

} else {
// block if condition is false

}
if-else if ladder
if (condition1) {

// code1

} else if (condition2) {

// code2
} else {

// code3

switch statement

switch (expression) {

case value1:

// code

break;
case value2:

// code

break;

default:

// code if no case matches

Important: break is required to prevent “fall-through” unless you intentionally want multiple
cases to execute.

6.6 Looping Constructs


Loops allow repetition of a block of code until a condition is met.

for loop

for (initialisation; condition; update) {

// body of loop

}
Example:
for (int i = 0; i < 5; i++) {

[Link](i);

Enhanced for loop (Java 5+)


Also called “for-each” loop — helpful for arrays/collections.

int[] arr = {1,2,3,4};

for (int num : arr) {

[Link](num);

while loop

while (condition) {

// body
// update usually inside

do-while loop

do {

// body

} while (condition);

This loop executes the body first and checks the condition after.
6.7 Combining decision and loops — examples

Example: Print even numbers from 1 to 20.

for (int i = 1; i <= 20; i++) {

if (i % 2 == 0) {

[Link](i);

}
Example: Menu driven application using switch and loop.
Scanner sc = new Scanner([Link]);

int choice;

do {

[Link]("1. Add\n2. Subtract\n3. Exit");


choice = [Link]();

switch(choice) {

case 1:

[Link]("Add selected");

break;

case 2:

[Link]("Subtract selected");

break;
case 3:

[Link]("Exiting...");

break;

default:

[Link]("Invalid choice");

} while (choice != 3);


6.8 Best practices in using these constructs

• Always use braces {} even if one statement inside if or for — improves readability and
avoids errors.

• Avoid deeply nested loops/ifs — break into methods.

• Choose appropriate loop construct: for for known iteration count, while when condition is
pre-checked, do-while when body must execute at least once.

• Use meaningful variable names, avoid magic numbers (hard coded literal values).

• For switch, ensure break or intentional fall-through is clear.


Implementation of OOPs Concepts in Java

1. Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of


objects, which can contain data and code.
In Java, everything revolves around classes and objects.

Key Principles of OOP:

1. Objects and Classes

2. Encapsulation

3. Abstraction

4. Inheritance

5. Polymorphism

6. Dynamic Binding

7. Message Passing

2. Objects and Classes

Definition of a Class

A class is a blueprint or template for creating objects.


It defines the properties (data members) and behaviors (methods) that its objects will have.

class Student {

String name; // data member


int age; // data member

void display() { // method

[Link]("Name: " + name + ", Age: " + age);

}
}
Definition of an Object

An object is an instance of a class.


It represents a real-world entity such as a car, student, or employee.

Student s1 = new Student(); // creating object

[Link] = "Riya";

[Link] = 22;
[Link]();

Diagram:

Class: Student

+---------------+

| name : String |

| age : int |

+---------------+
| display() |

+---------------+

↓ Object Instantiation

+---------------+

| [Link]=Riya |

| [Link]=22 |
+---------------+

3. Encapsulation

Definition

Encapsulation means wrapping data and methods that operate on that data into a single unit
(class).
It also involves restricting direct access to data using access modifiers like private, public, and
protected.
Example:

class Account {

private double balance; // private data

public void deposit(double amount) {

balance += amount;

public double getBalance() {

return balance;

}
}

Here, balance is hidden and can only be accessed through methods → Data Hiding.

Benefits:

• Protects data integrity

• Increases security

• Easy maintenance

4. Data Abstraction

Definition

Abstraction means showing only essential features and hiding unnecessary details.
It focuses on what an object does rather than how it does it.

Ways to achieve Abstraction in Java:

1. Abstract Classes
2. Interfaces

Example:

abstract class Vehicle {


abstract void start(); // abstract method

class Car extends Vehicle {


void start() {

[Link]("Car starts with a key.");

Here, Vehicle provides a general idea, and Car defines specific details.

5. Inheritance

Definition

Inheritance allows one class to acquire the properties and methods of another class.

• The existing class is called Parent/Super Class.

• The new class is called Child/Sub Class.

Syntax:

class Parent { ... }

class Child extends Parent { ... }

Types of Inheritance in Java:

Type Example Description

Single Inheritance A→B One class inherits from another

Multilevel Inheritance A → B → C Chain of inheritance

Hierarchical Multiple classes inherit from one


A → B and A → C
Inheritance parent

Not directly supported in


Hybrid Inheritance Achieved through interfaces
Java
Example:

class Animal {

void eat() {
[Link]("Eating...");

class Dog extends Animal {

void bark() {

[Link]("Barking...");

}
}

Diagram:

Animal

Dog

6. Polymorphism

Definition

Polymorphism means one name, many forms.


It allows a single function, method, or operator to behave differently in different situations.

Types of Polymorphism:

1. Compile-time (Static Binding) – achieved through Method Overloading

2. Run-time (Dynamic Binding) – achieved through Method Overriding

(a) Method Overloading

Two or more methods with the same name but different parameters.
class MathOperation {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

(b) Method Overriding

When a subclass provides a specific implementation of a method already defined in the parent
class.
class Animal {

void sound() {

[Link]("Animal makes sound");

class Dog extends Animal {


void sound() {

[Link]("Dog barks");

7. Dynamic Binding

Definition
Dynamic Binding (Late Binding) means the method call is resolved at runtime, not at compile-
time.
It occurs during method overriding.

Animal obj = new Dog();

[Link](); // Output: Dog barks

Here, the compiler doesn’t know which method will run — it is decided during execution.

8. Message Passing

Definition

Message Passing means communication between objects by calling methods.

For example:

[Link]("Hello", student2);

This concept is similar to how objects “talk” to each other using method calls in Java.

9. Default Parameter Values in Java

Unlike C++, Java doesn’t support default parameter values.


Instead, it uses method overloading to achieve the same effect.

Example:

void greet() {

[Link]("Hello!");

void greet(String name) {

[Link]("Hello " + name);

Here, calling greet() or greet("Riya") works differently.


10. Using Reference Variables with Functions

Reference variables store the address of an object, not the actual data.
When you pass an object to a function, Java passes the reference.

class Box {

int length;

class Demo {

void change(Box b) {

[Link] = 20;

public static void main(String[] args) {


Box obj = new Box();

[Link] = 10;

Demo d = new Demo();

[Link](obj);

[Link]([Link]); // Output: 20

}
}

So, changes made inside the method affect the original object.

11. Arrays in Java

An array is a collection of similar data items stored at contiguous memory locations.

Syntax:

int[] arr = new int[5]; // Declaration + Memory allocation


One-Dimensional Array:

int[] num = {10, 20, 30};

Two-Dimensional Array:

int[][] matrix = {

{1, 2, 3},

{4, 5, 6}

};

Array Diagram:

1D Array: [10][20][30]

2D Array:

[1][2][3]

[4][5][6]

12. String in Java

Definition

A String is a sequence of characters enclosed in double quotes " ".

Creating a String:

String s1 = "Hello";

String s2 = new String("World");

String Methods:

Method Description Example

length() returns length [Link]()

charAt(i) returns character at index [Link](2)

concat() joins two strings [Link](s2)


Method Description Example

equals() compares strings [Link](s2)

substring() extracts part [Link](2,5)

toUpperCase() converts to uppercase [Link]()

13. StringBuffer Class

Used for mutable strings (can be changed after creation).


StringBuffer sb = new StringBuffer("Hello");
[Link](" World");

[Link](sb); // Output: Hello World

Common Methods:

• append()

• insert()
• delete()

• reverse()

14. Wrapper Classes

Definition

Wrapper classes convert primitive data types into objects.

Primitive Type Wrapper Class

int Integer

float Float

char Character

boolean Boolean

Example:
int a = 10;

Integer obj = [Link](a); // boxing

int b = [Link](); // unboxing

15. super Keyword

Definition

super is used to refer to immediate parent class.

Uses:

1. Access parent class variables.


2. Call parent class methods.

3. Invoke parent constructor.

class Parent {

void display() { [Link]("Parent"); }

class Child extends Parent {


void display() {

[Link]();

[Link]("Child");

16. Multilevel Hierarchy

This is multilevel inheritance, where one class inherits another which in turn inherits another.

class A { void showA(){} }


class B extends A { void showB(){} }

class C extends B { void showC(){} }


Diagram:

A→B→C

17. Abstract and Final Classes

Abstract Class

A class that cannot be instantiated and may contain abstract methods.

abstract class Shape {

abstract void draw();

Final Class

A class that cannot be inherited.

final class Vehicle { }

18. Object Class

All classes in Java implicitly inherit from the Object class.

Common Methods:

• toString()

• equals()

• hashCode()

• getClass()

• clone()

19. Packages

A package is a namespace that organizes related classes and interfaces.

Types:

1. Built-in packages → [Link], [Link], [Link]


2. User-defined packages

Creating a package:

package mypackage;
public class A {

public void show() {

[Link]("Hello");

Using a package:

import mypackage.A;

20. Interfaces

Definition

An interface is a blueprint of a class with only abstract methods and constants.

interface Animal {
void eat();

class Dog implements Animal {

public void eat() {

[Link]("Dog eats bone");

}
}

Extending Interfaces:

interface A { void show(); }


interface B extends A { void display(); }
Access Protection:

• public → accessible everywhere

• protected → accessible in same package and subclass


• private → within same class

• default → within same package only

Summary Table

Concept Description Achieved by

Encapsulation Hiding data Classes, access modifiers

Abstraction Showing essential details Abstract classes, interfaces

Inheritance Reuse code extends, implements

Polymorphism One name, many forms Overloading, overriding

Dynamic Binding Method call resolved at runtime Overriding

Message Passing Communication between objects Method calls

Part 2: Arrays, Strings, Wrapper Classes, Packages, and Interfaces in Java

1. ARRAYS IN JAVA

Definition:

An array is a collection of similar data types stored in contiguous memory locations under a
single name.
It allows storing multiple values of the same type efficiently.

Characteristics:

• Fixed size (cannot change once created)


• Elements are indexed (starting from 0)
• Elements are of same data type

• Stored in continuous memory blocks

Declaration and Initialization

Syntax:

dataType[] arrayName; // Declaration

arrayName = new dataType[size]; // Memory allocation

Example:

int[] marks = new int[5]; // Declare array of size 5

marks[0] = 90; // Assign values

marks[1] = 85;
Combined Declaration:

int[] marks = {90, 85, 80, 95, 88};

Accessing Array Elements:

[Link](marks[0]); // Access first element

Diagram:

Index: 0 1 2 3 4

Marks: [90] [85] [80] [95] [88]

Types of Arrays:

(a) One-Dimensional Array

Stores a list of values in a single row.

int[] arr = {1, 2, 3, 4};


(b) Two-Dimensional Array (Matrix)

Stores values in rows and columns.


int[][] matrix = {

{1, 2, 3},

{4, 5, 6}

};
Diagram:

Row 0 → [1] [2] [3]

Row 1 → [4] [5] [6]

Access using → matrix[row][column]

Array Length Property:

int size = [Link];


[Link]("Size = " + size);

Traversing Arrays:

for(int i = 0; i < [Link]; i++) {

[Link](arr[i]);

Enhanced For Loop:

for(int value : arr) {

[Link](value);

Array of Objects:

Arrays can also store objects.


Student[] students = new Student[3];

students[0] = new Student("Riya", 22);


Exam Tip:

Remember the difference between 1D and 2D arrays.


Always mention array index starts from 0.
Practice basic programs — sum of array, largest number, matrix addition.

2. STRINGS IN JAVA

Definition:

A String is a sequence of characters enclosed within double quotes " ".


Java provides a String class in [Link] package.

Example:

String s1 = "Hello World";

Ways to Create Strings:

1. Using String Literals:

2. String s1 = "Hello";

3. String s2 = "Hello"; // Reuses from String pool

4. Using new Keyword:


5. String s3 = new String("Hello");

Memory Concept:

String Pool (Heap Memory)

• When you create strings using literals, they are stored in a string constant pool to save
memory.

• "Hello" is created only once and reused.


Common String Methods:

Method Description Example

length() returns string length [Link]()

charAt(int index) returns character at index [Link](2)

substring(int begin, int end) extracts substring [Link](0,5)

equals(String str) compares content [Link](s2)

compareTo(String s) lexicographically compares [Link](s2)

concat(String s) joins strings [Link](s2)

toLowerCase() converts to lowercase [Link]()

toUpperCase() converts to uppercase [Link]()

trim() removes leading and trailing spaces [Link]()

Example:

String str = "Java Programming";

[Link]([Link](5)); // Output: Programming

[Link]([Link](2)); // Output: v

String Comparison:

String a = "Hello";

String b = "Hello";
String c = new String("Hello");

[Link](a == b); // true (same pool reference)

[Link](a == c); // false (different object)


[Link]([Link](c)); // true (same content)
Difference: String vs StringBuffer

Feature String StringBuffer

Mutability Immutable Mutable

Storage String Pool Heap memory

Thread-safe Yes Yes

Usage Fixed text When frequent modifications needed

StringBuffer Example:

StringBuffer sb = new StringBuffer("Hello");

[Link](" Java");

[Link](sb); // Output: Hello Java

StringBuffer Methods:

Method Description

append() Adds text at end

insert(pos, str) Inserts at position

delete(start, end) Removes text

reverse() Reverses string

StringBuilder (Optional):

Similar to StringBuffer but not thread-safe, hence faster.

Exam Tip:
String = immutable; StringBuffer = mutable.
== checks reference; .equals() checks content.
Revise common methods (length(), substring(), compareTo()).

3. WRAPPER CLASSES

Definition:

Wrapper classes are object representations of primitive data types.


They “wrap” primitive values into objects so they can be used in collections or OOP contexts.

Primitive Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Example:

int a = 10; // primitive

Integer obj = [Link](a); // Boxing

int b = [Link](); // Unboxing

Auto-Boxing & Unboxing:

Java automatically converts between primitive and wrapper types.


Integer num = 5; // Autoboxing

int x = num; // Auto-unboxing

Common Wrapper Methods:

[Link]("123"); // Converts string to int

[Link](45.6); // Converts double to string

[Link]('A'); // Checks if letter

Exam Tip:

Remember primitive-to-wrapper mapping.


Explain Boxing & Unboxing with example.
Wrapper classes belong to [Link] package.

4. PACKAGES IN JAVA

Definition:

A package is a group of related classes, interfaces, and sub-packages.


It helps organize code and avoid name conflicts.

Types of Packages:

1. Built-in Packages (Predefined)

o [Link] → core classes

o [Link] → utilities (ArrayList, HashMap)

o [Link] → input/output

o [Link] → database connectivity

2. User-defined Packages
o Created by developers for modular programming.
Creating a Package:

package mypackage;

public class Demo {

public void show() {

[Link]("Hello from mypackage!");

Using a Package:

import [Link];

public class Test {

public static void main(String[] args) {

Demo d = new Demo();

[Link]();
}

Access Protection in Packages:

Modifier Same Class Same Package Subclass (diff pkg) Other Packages

public

protected

default (no modifier)


Modifier Same Class Same Package Subclass (diff pkg) Other Packages

private

Advantages of Packages:

• Code reusability

• Namespace management
• Better organization

• Easier maintenance

5. INTERFACES IN JAVA

Definition:

An interface is a collection of abstract methods and constants.


It defines what a class should do, not how.

Syntax:

interface Vehicle {

void start(); // abstract method (public + abstract by default)

Implementing an Interface:

class Car implements Vehicle {

public void start() {

[Link]("Car starts with a key");

}
}
Extending an Interface:

interface A {
void display();

interface B extends A {

void show();

Multiple Inheritance using Interfaces:

Java doesn’t allow multiple inheritance through classes, but allows through interfaces.

interface A { void methodA(); }

interface B { void methodB(); }

class C implements A, B {

public void methodA() { [Link]("A method"); }

public void methodB() { [Link]("B method"); }


}

Default & Static Methods in Interfaces (Java 8+):

interface Calculator {

default void show() { [Link]("Default method"); }

static void info() { [Link]("Static method"); }


}

Marker Interface:

Interface with no methods; used to signal metadata to JVM (e.g., Serializable).


Diagram:

Interface: Vehicle

Class: Car (implements Vehicle)

Exam Tip:

Interface = 100% abstraction.


Methods in interfaces are public and abstract by default.
Remember difference between abstract class and interface.
Practice multiple interface implementation syntax.

Summary Table

Concept Key Point Example Keyword

Array Fixed collection of similar type int[] arr

String Immutable text data "Hello"

StringBuffer Mutable string append()

Wrapper Class Object representation of primitives Integer

Package Collection of classes package, import

Interface Blueprint of class implements

DIAGRAM SUMMARY

+---------------------+

| Object-Oriented Java|

+---------------------+
/ | \
Classes Arrays Strings

Wrapper Classes

\
Packages

Interfaces

Quick Revision Points

Arrays → Fixed size, same data type, use [Link]


Strings → Immutable, stored in String Pool
StringBuffer → Mutable, use append()
Wrapper Classes → Used for object-type conversion
Packages → Group related classes
Interfaces → 100% abstraction, used for multiple inheritance
UNIT-2

1. Exception Handling

1.1 What is an Exception?

• Definition: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions (i.e., the usual sequential execution). (Oracle
Documentation)

• Explanation: Imagine you’re reading a book, line by line. Suddenly a wind blows and a
page tears out — you cannot continue the usual reading. Similarly, in a program, if
something unexpected (e.g., dividing by zero, file not found) happens, that’s an
exception.

• In Java, an exception is represented by an object of a class (derived from Throwable) that


captures information about the error: its type, message, program state, etc. (ProTech)
• Why handle exceptions? Because if you don’t, your program may abruptly terminate and
you lose control. Exception handling gives you a mechanism to catch and recover or at
least manage such events. (InfoWorld)

Diagram: Exception hierarchy


• At the top: [Link] → [Link] → two main branches: Error and
Exception. (GeeksforGeeks)

• Error represents serious problems the application usually cannot handle (e.g.,
OutOfMemoryError, StackOverflowError). (GeeksforGeeks)

• Exception represents conditions that a reasonable application might catch. It is


subdivided into checked exceptions and unchecked exceptions.

1.2 Types of Exceptions

We can categorise exceptions in several ways.


1.2.1 Based on definition (built-in vs custom)

• Built-in exceptions (predefined exceptions): These are exception classes provided by


Java libraries (e.g., IOException, NullPointerException, ArithmeticException). (Baeldung
on Kotlin)
• Custom exceptions (user-defined exceptions): When you want to represent a special
error situation specific to your application you can create your own exception class (by
extending Exception or RuntimeException).

1.2.2 Based on compile-time vs run-time: Checked vs Unchecked

• Checked exceptions: These are exceptions that are checked by the compiler at compile-
time. If a method can throw them, you must either handle them (with try‐catch) or declare
them with throws. Examples: IOException, ClassNotFoundException. (GeeksforGeeks)
• Unchecked exceptions: These are exceptions that occur at run-time, not required to be
declared or caught. Usually subclasses of RuntimeException. Examples:
NullPointerException, ArithmeticException. (TutorialsPoint)

• Errors: Not exceptions for which you usually write code to handle them—they represent
problems in the runtime environment.

1.3 Fundamentals of Exception Handling – Key Keywords

In Java, exception-handling uses several keywords: try, catch, finally, throw, and throws.
(O'Reilly Media)
Let’s go through each in a simple way.
try

• The block of code that might throw an exception is placed inside a try block.

• If no exception occurs, everything inside try executes, then optionally the finally block
executes (if present).

• If an exception occurs inside try, Java looks for a matching catch block to handle it.

catch

• After the try, you can have one or more catch blocks, each catching a particular type of
exception (or its superclass).

• Example: catch (ArithmeticException e) { … }

• The catch block executes when an exception of matching type is thrown in the try block.

finally

• This is an optional block that always executes after try (and any catch blocks), regardless
of whether an exception occurred or not. (GeeksforGeeks)
• Commonly used to clean up resources (close files, database connections, sockets) even if
an exception occurred.

throw

• Used by programmer to explicitly throw an exception: e.g., throw new


MyException("Bad state");

• This means “create this exception object and hand it to the runtime system”.
(GeeksforGeeks)

throws
• Used in method signature to declare that this method may throw certain exceptions and
does not handle them internally.

• Example: public void readFile() throws IOException { … }

• The caller must handle or further declare them.

1.4 Flow / Control of Exception Handling

Here’s a step-by-step view of how exception handling works:

1. A try block begins.


2. Code inside try executes.

o If no exception → execute all statements, then skip all catch blocks, then finally
(if present).

o If an exception is thrown (by the code or via throw), normal execution is broken,
any remaining statements in try are skipped, control moves to the first catch block
that matches the thrown exception type (or its superclass).

3. The matching catch executes. If no catch matches, the exception propagates up the call-
stack to the caller method.

4. After catch, finally executes (if present).


5. If exception was not handled in this method, it propagates further; if handled and no
further throw, method ends normally or abnormal (depending on logic).

1.5 Caught vs Uncaught Exceptions


• Caught exceptions: Those exceptions that are handled by a catch block in the method
where they occur (or somewhere up the call stack). They do not cause terminating the
program if handled properly.
• Uncaught exceptions: Those that are not handled (no matching catch), so they propagate
to the JVM default handler, which typically prints a stack trace and terminates the
program.

• It is good practice to anticipate the exceptions your code may throw, catch the ones you
can recover from, and declare (via throws) the ones you can’t handle, or convert them
into custom exceptions.

1.6 Built-in Exceptions (Some Common Ones)

Here are a few frequently used/seen built-in exceptions in Java:


• ArithmeticException (e.g., divide by zero)
• NullPointerException (accessing a null reference)

• ArrayIndexOutOfBoundsException (array index beyond bounds)

• IOException / FileNotFoundException (file I/O errors)

• ClassNotFoundException, SQLException, etc.


These are part of the standard Java libraries; they help you handle many common error
conditions without writing new exception types from scratch.

1.7 Custom Exceptions (User-defined Exceptions)

• Why? Sometimes built-in exceptions don’t clearly represent a specific error scenario in
your business logic (e.g., InsufficientBalanceException in a banking application).

• How to define? You create a new class, typically extending Exception (checked) or
RuntimeException (unchecked).

• public class InsufficientBalanceException extends Exception {

• public InsufficientBalanceException(String message) {

• super(message);
• }

• }

• Then, in your method you can throw new InsufficientBalanceException("Balance too


low") and declare throws InsufficientBalanceException.

• Benefits: It improves readability, makes error handling more precise, enforces semantics
in your code.

1.8 Example Code Snippet

public void processFile(String filename) throws IOException {

try {

FileReader fr = new FileReader(filename);

// ... process file ...

} catch (FileNotFoundException fnfe) {


[Link]("File not found: " + filename);

} finally {
[Link]("Finished attempt to process file.");
}

In this example:

• new FileReader(filename) may throw FileNotFoundException (a checked exception)


• We catch it and handle it with a message.

• finally block executes regardless.

• The method declares throws IOException to indicate it may throw other IO exceptions.

1.9 Good Practices & Important Points

• Don’t catch overly broad exceptions (e.g., catch(Exception e)) unless you really intend
to handle all types; it may hide bugs.

• Use meaningful error messages when throwing custom exceptions.

• Clean up resources in finally (or better: use try-with-resources in newer Java versions).

• Don’t use exceptions for regular control flow — exceptions should be for
“exceptional” cases.

• Document your methods with throws properly (for checked exceptions).

• Avoid empty catch blocks — swallowing exceptions silently can hide problems.

2. Multithreaded Programming

2.1 What is Multithreading?

• Definition: Multithreading is a programming feature that allows a single program


(process) to execute multiple threads (units of execution) concurrently (or seemingly so)
within the same memory space. (TutorialsPoint)

• Explanation: Think of a restaurant where many chefs are cooking different dishes
simultaneously — the main program is the restaurant, threads are chefs. They share the
same kitchen (memory) but perform independent tasks. This helps improve
responsiveness, CPU / resource utilisation.

• Because threads share memory, multithreading brings benefits (parallelism, efficiency)


but also challenges (synchronisation, race conditions).

Diagram: Multithreading overview


2.2 Benefits of Multithreading

• Better CPU utilization: While one thread waits (e.g., for I/O), other threads can run.

• Improved performance in multi-core systems.


• Enhanced responsiveness (e.g., GUI applications: one thread handles UI, others handle
computation/IO).

• Simpler modelling of concurrent tasks.


2.3 Challenges in Multithreading

• Thread interference: When two threads try to modify shared data simultaneously,
leading to inconsistent results.

• Memory consistency errors: Changes made by one thread may not be visible to another
thread unless properly synchronised.
• Deadlocks, livelocks, starvation: Badly designed synchronization can lead to one or
more threads being blocked forever.
• Understanding concurrency control is essential to avoid subtle bugs.
2.4 Basics of the Java Thread Model
Thread class and Runnable interface

• In Java you can create threads in two common ways:

1. Extending the Thread class:

2. class MyThread extends Thread {


3. public void run() {

4. // code

5. }

6. }

7. MyThread t = new MyThread();

8. [Link](); // starts new thread, calls run()

(W3Schools)

9. Implementing the Runnable interface:


10. class MyTask implements Runnable {

11. public void run() {

12. // code

13. }

14. }

15. Thread t = new Thread(new MyTask());

16. [Link]();
This approach is more flexible (because your class can extend some other class besides Thread).
(W3Schools)
Thread lifecycle / states

A thread goes through several states in its lifecycle:

• New: Thread object created, but not started yet.

• Runnable (Ready to Run / Running): Thread has been started (start()) and is eligible to
run (or is actually running).

• Blocked / Waiting / Timed Waiting: Thread is waiting for some condition (lock, I/O,
wait, sleep).
• Terminated (Dead): Thread has finished execution or been stopped. (TutorialsPoint)

Thread priorities

• Each thread has a priority (from Thread.MIN_PRIORITY (1) to


Thread.MAX_PRIORITY (10), default Thread.NORM_PRIORITY (5)). (TutorialsPoint)

• Higher-priority threads are given preference by thread scheduler but there is no


guarantee of execution order across priorities (platform dependent).

• Use with caution — don’t rely on priority to enforce correct logic.

2.5 Happens-Before Ordering & the Java Memory Model (JMM)

One critical concept in multithreading is happens-before ordering (a formal mechanism from


the Java Memory Model) which governs memory visibility and ordering of actions between
threads. (GeeksforGeeks)

What does “happens-before” mean?

• If action A happens-before action B, then:

1. The effects (writes) of A are guaranteed to be visible to B.


2. A appears to occur before B in some ordering that respects visibility/ordering
constraints. (GeeksforGeeks)
• It is not necessarily actual physical ordering (i.e., in real time), but a guarantee that
correct visibility happens. (Shipilev)

Key rules for happens-before (as per JLS 17.4.5) (Oracle Documentation)
• If two actions are in the same thread, and action X comes before action Y in program
order, then X happens-before Y.
• A call to [Link]() on thread T happens-before any actions in the started thread T.

• All actions in a thread happen-before that thread terminates; thread termination happens-
before another thread join() returning.
• If action X synchronizes-with action Y (e.g., release of lock, acquire of lock) then X
happens-before Y.
• The happens-before relation is transitive: if A hb B and B hb C then A hb C.

Why this matters

• Without these guarantees, one thread may not “see” the updates made by another thread,
leading to inconsistent or stale values. (Stack Overflow)
• Correct use of synchronized, volatile, thread start/join ensure predictable behaviour in
concurrent programs.

2.6 Synchronization, Messaging, Thread Priorities, Thread Control

Let’s cover these components in detail:

Synchronization

• When multiple threads share mutable data (fields, objects), to avoid race conditions and
data corruption we use synchronization mechanisms.

• synchronized keyword: When a method or block is marked synchronized, a lock


(monitor) is acquired for that object or class; only one thread at a time can execute inside
that block for that object.
• Example:

• synchronized(this) {

• // critical section

• }
• Benefit: prevents two threads modifying shared data at the same time.

• But over-synchronization may lead to performance issues or deadlock.

Inter-Thread Communication (Messaging)

Often threads must coordinate (one waits, another signals). Java provides built-in methods via
Object class: wait(), notify(), notifyAll(). (GeeksforGeeks)

• wait(): causes current thread to give up the object’s monitor (lock) and go to waiting
state until some other thread calls notify() or notifyAll() on the same object.

• notify(): wakes up one waiting thread on that object’s monitor.

• notifyAll(): wakes up all waiting threads on that object’s monitor.


These must be called within synchronized code (i.e., when the thread holds the monitor
of the object).

Example: Producer-Consumer problem (brief)

• Shared resource: a queue with limited capacity.

• Producer thread adds items; Consumer thread removes items.

• When queue is full, producer waits; when queue is empty, consumer waits.
• Use wait()/notify() inside synchronized blocks to coordinate. (GeeksforGeeks)
Thread Priorities (again)

We have already touched on this. For completeness:

• Methods: [Link](int), [Link](), Thread.MAX_PRIORITY, etc.


• Note: Priority scheduling depends on JVM/OS; should not rely solely on priority for
correctness.

Suspending, Resuming, Stopping Threads


• Historically, Java had methods like suspend(), resume(), stop() in Thread class, but they
are deprecated because they are unsafe (deadlocks, inconsistent state).
• Modern practice: Use interruption (interrupt()), flags, or concurrency utilities to manage
thread termination.

• Example: Setting a volatile boolean running = false and checking inside run() loop to stop
gracefully.

2.7 Putting It All Together: Thread Model Summary


• Threads are created (via Thread class or Runnable interface) and started with start() →
enters Runnable/Running state.
• Threads may enter blocked/waiting states (sleep, wait, join, I/O) and then come back to
runnable.
• Threads share memory; to avoid data issues we enforce happens-before ordering (via
synchronization, volatile, start/join) and mutual exclusion (synchronised).

• Threads communicate using wait/notify or higher-level concurrency utilities


([Link]) for more complex designs.

• Thread priorities and lifecycle methods help control scheduling and execution flow, but
do not guarantee strict ordering.
2.8 Example Code Snippet – Thread Creation & Synchronisation

class Counter {
private int count = 0;

public synchronized void increment() {


count++;

public int getCount() {

return count;
}

class MyRunnable implements Runnable {

private Counter counter;

MyRunnable(Counter c) { [Link] = c; }

public void run() {

for(int i=0; i<1000; i++) {


[Link]();

public class Main {

public static void main(String[] args) throws InterruptedException {


Counter c = new Counter();

Thread t1 = new Thread(new MyRunnable(c));

Thread t2 = new Thread(new MyRunnable(c));

[Link]();

[Link]();

[Link]();

[Link]();
[Link]("Final count = " + [Link]());
}

• Two threads increment the same counter 1000 times each → resulting in 2000 if
synchronization correct.

• synchronized keyword ensures mutual exclusion for increment() so no data corruption.

• join() ensures main thread waits until both threads finish (establishes happens-before
relation).

2.9 Suspended, Resumed, Stopping Threads – Safe Approach

Instead of deprecated suspend(), resume(), stop(), modern pattern:


class MyTask implements Runnable {

private volatile boolean running = true;

public void run() {

while(running) {

// do work

}
[Link]("Thread stopping.");

public void stop() {


running = false;

Thread t = new Thread(new MyTask());

[Link]();

// … later
((MyTask)[Link]()).stop();
[Link]();

• volatile running ensures visibility between threads (happens-before).

• No abrupt stop; thread finishes loop and terminates gracefully.

2.10 Good Practices for Multithreading


• Avoid sharing mutable data whenever possible (prefer immutable objects or thread-local
data).

• Always use proper synchronization (locks, synchronized, volatile, or higher-level


concurrency constructs).

• Avoid deadlocks: acquire locks in consistent order, avoid nested locks whenever possible.
• Use join() or concurrency utilities (ExecutorService, Future, CountDownLatch) instead
of deprecated thread control methods.

• Document thread behaviours, clarify which threads access which data.


• Test concurrency scenarios (race conditions often hide until under load).

• Consider using high-level constructs in [Link] (thread pools, concurrent


collections) for production code.

3. Summary Table

Topic Key Concepts Why it matters

Exception definition, types (checked/unchecked), Ensures errors are handled


Exception
built-in vs custom, keywords (try, catch, finally, gracefully, program
Handling
throw, throws), flow, good practices remains robust

Enables concurrent
Thread creation (Thread class, Runnable),
execution, better CPU
lifecycle, thread priorities, synchronization, inter-
Multithreading utilisation, but requires
thread communication (wait(), notify()), happens-
care for safety and
before ordering, safe thread control
correctness

1. The Collection Framework

(The Collection Interface, Collection Architecture in Java, Collection Classes, Traversing


Collections, Working with Maps & Sets)
1.1 What is a Collection?

• A collection is simply a group of objects treated as a single unit. For example, a box of
toys is like a collection of toy-objects. In Java, we often want a way to hold many objects
(like storing student names, book records) rather than one by one.

• The Java Collections Framework (JCF) gives us ready-made data structures and
algorithms so we don’t have to build them from scratch. (GeeksforGeeks)

• According to Oracle: “A collections framework is a unified architecture for representing


and manipulating collections, enabling collections to be manipulated independently of
implementation details.” (Oracle Documentation)
• In simpler terms: instead of having many separate containers each with its own methods,
we have a standard set of interfaces, plus many classes that implement them, plus
algorithms that work on them — all consistent and reusable.

1.2 Why do we need the Collection Framework?

Key reasons:
• Arrays in Java have fixed size; collections can grow and shrink dynamically.
(GeeksforGeeks)
• Without framework: every developer would build their own data structures; with
framework: reuse.

• Efficiency: optimized, tested implementations. (Oracle Documentation)


• Consistency: all collections behave similarly (add / remove / size / iterate) even if
underlying structure differs.
• Flexibility: easier to switch one implementation for another (e.g., ArrayList to
LinkedList) if interface remains the same.
• Interoperability: APIs can use generic collection interfaces and classes, reducing
coupling. (Oracle Documentation)

1.3 Core Interfaces & Hierarchy


1.3.1 Root interfaces

• [Link]<E>: the very top. It allows “for-each” looping and returns an


Iterator<E>. (Programiz)
• [Link]<E>: extends Iterable; it is the root for many collection types (except
Map). It defines basic operations like add, remove, size, contains. (Oracle
Documentation)
• [Link]<K, V>: this is not a subinterface of Collection. It represents key-value
pairs. Although not a “Collection” in strict sense, it is part of the overall framework.
(W3Schools)

1.3.2 Sub-interfaces of Collection

• List<E> — an ordered collection (elements have positions), duplicates allowed.

• Set<E> — no duplicate elements allowed. Order may or may not matter depending on
implementation.

• Queue<E> — typically for holding elements before processing (e.g., "first in, first out").

• Deque<E> — double-ended queue: you can add/remove from both ends.

• SortedSet<E>, NavigableSet<E> — sets with ordering / navigation capabilities.

• For Map: SortedMap<K,V>, NavigableMap<K,V>.

1.3.3 Visualising the hierarchy


This diagram helps you see how interfaces and classes relate: Collection → List, Set, Queue, etc.
and Map stands separately.

1.4 Collection Architecture in Java

Let’s break down the architecture into three major components: interfaces, implementations,
and algorithms.

• Interfaces: define what operations you can do (e.g., add, remove, iterate) without
specifying how things are done.

• Implementation (Classes): concrete classes that implement the interfaces, e.g.,


ArrayList, LinkedList, HashSet, TreeMap. They decide the data structure behind the
scenes (array, linked list, tree, hash table). (GeeksforGeeks)

• Algorithms: operations that work across collections (like sort, binary search, shuffle).
They are usually static methods in [Link] class. (DigitalOcean)

Basic flow: You declare a variable of interface type (e.g., List<String> myList = new
ArrayList<>();). You program to the interface (List), use its methods. Underneath, ArrayList
provides the behaviour. If later you decide LinkedList is better, you can change the
implementation without changing the rest of your code (as long as you keep using List methods).

1.5 The Collection Interface (detailed)

Definition: public interface Collection<E> extends Iterable<E>


Represents a group of objects (elements). Comes under [Link].

Important methods:
• boolean add(E e) — insert element e.
• boolean remove(Object o) — remove one occurrence of o.

• boolean contains(Object o) — checks if element exists.

• int size() — number of elements.

• void clear() — remove all elements.

• boolean isEmpty() — check if no elements.

• Iterator<E> iterator() — get an iterator to traverse the elements.

Key points:
• Collection doesn’t define ordering or uniqueness (that is left to subinterfaces).
• Collection supports generic types (<E>).

• All subinterfaces (List, Set, Queue) inherit from Collection, so they get these basic
operations plus their own special operations.

• The Collection interface does not allow primitive types directly — only objects (so use
wrapper classes).

1.6 Collection Classes (Implementations)

Let’s discuss major implementations under List, Set, and Map with their characteristics
(advantages, when to use).

1.6.1 List Implementations

• ArrayList<E>: backed by dynamic array. Good for random access (get by index is fast).
But adding/removing in middle may be slower because shift is required.

• LinkedList<E>: uses doubly linked nodes. Good for insertions/removals in the middle;
slower for random access.

• Vector<E> (legacy): synchronized (thread-safe) version of ArrayList; not used much in


new code.

• Stack<E> (legacy): extends Vector; represents LIFO (last-in, first-out) stack.

• CopyOnWriteArrayList, etc (for concurrency) — advanced topic.

When you choose List: order matters, duplicates allowed, you need position or index operations.

1.6.2 Set Implementations


• HashSet<E>: backed by a hash table (actually a HashMap internally). No ordering
guarantee (depending on implementation). No duplicates allowed.
• LinkedHashSet<E>: like HashSet but maintains insertion order (or access order) of
elements.

• TreeSet<E>: implements SortedSet; elements sorted according to natural ordering or


comparator. Backed by a tree (usually a Red-Black tree).

• EnumSet<E>: special set for enum types (efficient).


When you choose Set: you need uniqueness (no duplicates), maybe ordering not important (or
want sorted order).

1.6.3 Map Implementations (Key-Value pairs)


Although Map is not a subclass of Collection, it is part of the framework and widely used.
• HashMap<K,V>: hash-table based implementation; keys are unique. Order unspecified.

• LinkedHashMap<K,V>: maintains insertion order (or access order).

• TreeMap<K,V>: sorted map based on keys; implements SortedMap.

• Hashtable<K,V> (legacy): synchronized; older version of HashMap.


• ConcurrentHashMap, etc (for concurrency).

When to choose Map: you want to associate keys with values (e.g., studentID →
studentObject), efficient lookup by key, uniqueness of keys.
1.6.4 Summary Table

Category Interface Common Implementations Key Feature

Ordered collection,
List List<E> ArrayList, LinkedList, Vector
duplicates allowed

HashSet, LinkedHashSet, Unique elements, no


Set Set<E>
TreeSet duplicates

Queue<E>, LinkedList, ArrayDeque,


Queue/Deque FIFO or special order
Deque<E> PriorityQueue

HashMap, LinkedHashMap,
Map Map<K,V> Key-value pairs, unique keys
TreeMap

1.7 Traversing Collections

Traversal means visiting each element in a collection, usually to perform some action (print,
compute sum, modify, etc.).

Common ways to traverse collections:

1. Iterator

o For any Collection (List, Set) you can obtain an Iterator<E> it =


[Link]();

o Then use while ([Link]()) { E element = [Link](); ... }


o Iterator also has remove() to remove the last element returned.

2. Enhanced for-loop (for-each)

o Since Collection<E> extends Iterable<E>, you can write for (E e : collection) {


… }. Simpler and cleaner.
3. ListIterator (for List)

o Supports forward and backward traversal, modifying during iteration, getting


index etc.

4. Stream API (Java 8 onward)

o [Link]().forEach(e -> … ). Though more advanced, still traversal.

5. For Map: Since Map is not a Collection, you cannot directly use the above. You can
traverse keys, values or entries:

o for (K key : [Link]()) { V value = [Link](key); … }

o for ([Link]<K,V> entry : [Link]()) { … }


Tips for exam: mention each method, note that enhanced-for works only if the class implements
Iterable, note performance when removing during traversal (use iterator’s remove(), not for-
each).

1.8 Working with Sets & Maps

1.8.1 Sets
• Definition: A Set<E> is a collection that does not allow duplicate elements. That means
[Link](e2) cannot hold for two distinct elements in the set.
• Since duplicates are not allowed, equality (equals()) and hashCode() methods of elements
become important (especially for HashSet).

• Ordering depends on implementation:


o HashSet: no guarantee of order.

o LinkedHashSet: maintains insertion (or access) order.

o TreeSet: sorted order by natural ordering or comparator.

• Common operations: add(), remove(), contains(), size(), iterator().

• When to use Set: when you need to maintain a collection of unique items – e.g., unique
student IDs, unique words in a text.

1.8.2 Maps

• Definition: A Map<K, V> associates keys to values. Keys must be unique; each key
maps to one value (though values may be duplicated).

• Key operations:
o put(K key, V value) — adds or updates mapping.
o get(K key) — retrieves value associated with key.

o remove(K key) — removes mapping.

o containsKey(K key), containsValue(V value).

o keySet(), values(), entrySet().


• Common implementations:

o HashMap — fastest general-purpose, no ordering guarantee.

o LinkedHashMap — maintains insertion/access order.

o TreeMap — sorted key order.

• Example use: mapping studentID → student record, userName → user settings, word →
frequency.

• Notes: since Map is not a Collection, operations differ (e.g., you can’t do [Link](...)).

1.9 Important Exam Points / Summary

• Understand the difference between interface and implementation.

• Know which interface is at root (Collection) and which are sub-interfaces.


• Know the difference between List / Set / Map.

• Know common classes and when to use which.

• Know traversal methods (Iterator, for-each, ListIterator, Stream).

• Be aware of performance trade-offs (e.g., ArrayList vs LinkedList, HashMap vs


TreeMap).

• Understand equals() and hashCode() in context of Sets and Maps.


• Be able to draw/recognise the hierarchy diagram for the Collection Framework.

• Real-world analogy: think of List as a row of chairs (ordered), Set as a group of unique
students (no duplicates), Map as a dictionary (key→value).

• Additional: mention that all of these reside in [Link] package (mostly).

• Algorithms: [Link](), [Link](), etc.

1.10 Sample Code Snippet (for clarity)


import [Link].*;
public class Example {

public static void main(String[] args) {

// List example

List<String> languages = new ArrayList<>();


[Link]("Java");

[Link]("Python");

[Link]("C++");

for (String lang : languages) {

[Link](lang);

// Set example
Set<Integer> numbers = new HashSet<>();

[Link](10);

[Link](20);

[Link](20); // duplicate – will not be stored twice

[Link]([Link]()); // prints 2

// Map example
Map<String, Integer> ages = new HashMap<>();

[Link]("Alice", 23);

[Link]("Bob", 30);

int aliceAge = [Link]("Alice");

[Link]("Alice is " + aliceAge);

}
2. Networking Fundamentals

(Networking classes & interfaces, using [Link] package, TCP/IP, Datagram (UDP)
programming)

2.1 What is Networking (in Java context)

• Networking refers to the concept of connecting two or more computing devices


(computers, servers) so they can exchange data or share resources. (GeeksforGeeks)

• In Java, you can write programs that communicate over a network (Internet, LAN) using
classes in the [Link] package. This enables building client-server applications, chat
apps, multiplayer games, etc.

2.2 Basic Network Protocols: TCP/IP and UDP


2.2.1 TCP (Transmission Control Protocol)

• Connection-oriented: before data is sent, a connection is established between client and


server.

• Guarantees reliable, ordered delivery of data. If packets are lost, they are retransmitted;
data arrives in correct order. (Oracle Documentation)

• Common uses: web browsing (HTTP), file transfer (FTP), email, applications where data
integrity matters.

2.2.2 UDP (User Datagram Protocol)

• Connectionless: data is sent without establishing a dedicated connection.

• No guarantee of delivery, order or duplication control. If a packet is lost, it’s lost.


(GeeksforGeeks)

• Faster overhead (less protocol overhead) than TCP. Suitable for streaming audio/video,
real‐time gaming, where speed is more important than absolute reliability.

2.2.3 TCP/IP Stack & Basics

• The “IP” part is Internet Protocol (IPv4 or IPv6) which deals with addressing (e.g.,
[Link], [Link]). Java has classes for IP addressing (e.g., InetAddress).
(Oracle Documentation)

• The TCP and UDP protocols run on top of IP (so you often call it TCP/IP).

• Important network concepts: port numbers (to identify applications), sockets (endpoints),
client/server model, packets/streams, datagrams.
2.3 Java Networking Classes & Interfaces (in [Link])

Key classes/interfaces:

• InetAddress / Inet4Address / Inet6Address: represent IP addresses. (Oracle


Documentation)

• Socket: represents a client-side socket (TCP). (Oracle Documentation)

• ServerSocket: listens for incoming TCP connection requests (server side). (Oracle
Documentation)

• DatagramSocket, DatagramPacket: for UDP communication. (GeeksforGeeks)

• MulticastSocket: for UDP multicast (sending to a group).


• URL, URLConnection, HttpURLConnection: to connect to remote resources (HTTP,
FTP, etc.). (Oracle Documentation)

• SocketAddress, InetSocketAddress: represent socket endpoints (IP + port).


• Some interfaces: NetworkInterface, etc.

Package: [Link]

All of the above classes/interfaces are in [Link] (and some in related packages). Java
documentation emphasises that: “Through the classes in [Link], Java programs can use TCP or
UDP to communicate over the Internet.” (Oracle Documentation)

2.4 Client-Server Model with TCP in Java

Steps:

1. Server side:

o Create ServerSocket server = new ServerSocket(portNumber);


o Wait for connection: Socket clientSocket = [Link]();

o Once accepted, get input/output streams: InputStream in =


[Link]();, OutputStream out =
[Link]();

o Read/write data.

o Close connection.

2. Client side:
o Create Socket socket = new Socket(hostName, portNumber);
o Get input/output streams from the socket.

o Use read/write.

o Close connection.

3. Communication: Once connected, both ends can send/receive data (in Java often via
streams).

Key points

• The connection is reliable, data arrives in order.


• Suitable for request/response style communication.

• You must handle exceptions (IOExceptions) and ensure sockets/streams are closed.
• Example snippet (simplified):

// Server

ServerSocket server = new ServerSocket(5000);

Socket s = [Link]();

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));


PrintWriter out = new PrintWriter([Link](), true);

String line = [Link]();

[Link]("Received: " + line);

[Link]();

[Link]();

// Client
Socket s = new Socket("localhost", 5000);

PrintWriter out = new PrintWriter([Link](), true);

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

[Link]("Hello server!");

String response = [Link]();


[Link](response);
[Link]();

This shows the basic flow.

2.5 Datagram (UDP) Programming in Java

Key ideas
• You use DatagramSocket to send/receive DatagramPackets. The packet contains a byte
array and destination address & port.

• There is no connection set-up; you just send packets.


• Example: to send a packet:

DatagramSocket socket = new DatagramSocket();


byte[] buf = "Hello".getBytes();

InetAddress address = [Link]("localhost");

DatagramPacket packet = new DatagramPacket(buf, [Link], address, 5000);

[Link](packet);

[Link]();
• To receive:

DatagramSocket socket = new DatagramSocket(5000);

byte[] buf = new byte[1024];

DatagramPacket packet = new DatagramPacket(buf, [Link]);

[Link](packet);

String received = new String([Link](), 0, [Link]());

[Link](received);
[Link]();

• UDP is useful when speed is critical and occasional packet loss is acceptable (e.g., live
streaming). (GeeksforGeeks)
• Important: order is not guaranteed; packets may arrive out‐of‐order or be lost.

2.6 Using TCP/IP in Java with [Link]

• To use TCP/IP programming you make use of Socket and ServerSocket.


• IP addressing: you often use [Link](host) to resolve hostname or
address.

• Ports: range from 0–65535 (privileged ports <1024). Client chooses ephemeral port;
server listens on a known port.

• Streams: Once socket connected, data is sent via InputStream/OutputStream or wrappers


(Reader, Writer).

• Clean-up: always close sockets and streams to avoid resource leak.

2.7 Important Networking Terms & Concepts

• Socket: one endpoint of a two-way communication link (client side or server side).
(Oracle Documentation)
• Port number: identifies a specific process/application on machine.

• Host: computer in network (identified by IP address).

• Client: program which initiates connection.

• Server: program which waits for clients.


• Datagram: a packet sent via UDP.

• Stream: continuous flow of data (used by TCP).

• Connectionless vs Connection-oriented: UDP vs TCP.

• Reliable vs Unreliable: TCP ensures reliability; UDP does not.

• Order guarantee: TCP yes; UDP no.

• Overhead: TCP more overhead (due to reliability, handshaking), UDP less.

2.8 Why learn Java Networking?


• Enables you to build distributed applications (client-server) which is a major part of real-
world systems.

• Many enterprise systems, web services, gaming, chat, streaming rely on networking.
• Understanding TCP/IP & UDP is fundamental for modern software.

• The [Link] API makes the task easier: high-level abstractions for sockets, datagrams,
URLs. (TutorialsPoint)
UNIT 3

1. Anonymous Classes and Inner Classes in Java

1.1 Core Concept: Nested Classes & Inner Classes

Definition:
• A nested class in Java is a class defined within another class. (Oracle Documentation)

• An inner class is a non-static nested class: i.e., a class defined inside another class,
without the static modifier. (Oracle Documentation)
• Why use nested/inner classes? They help in logically grouping classes that are used only
in one place, enhancing encapsulation, readability and maintainability. (W3Schools)
• Inner classes can access the members (including private members) of their enclosing
class (in the non-static case) because they are tied to an enclosing instance. (Oracle
Documentation)

• Static nested classes behave more like normal top-level classes but are scoped inside the
outer class, and they cannot directly access instance members of the outer class.
(W3Schools)

High‐level diagram:
1.2 Types of Nested/Inner Classes

We classify nested classes into two major categories, and further into sub‐types.

Category Definition / Notes

A nested class declared with static modifier. It does not need an instance of
Static Nested
the outer class to be created. It cannot directly access non‐static members of
Class
the outer class. (W3Schools)

Inner Classes These classes require an instance of the outer class. They can access all
(non-static members (including private) of the outer class. Within this broad group there
nested) are further sub‐types. (Oracle Documentation)

Inner class sub‐types:

1. Member inner class (or simply “inner class”): defined at member level within outer
class, not static.

2. Local inner class: defined within a method (or a block) of the outer class. Its scope is the
method/block. (W3Schools)

3. Anonymous inner class: special case of local inner class without a name, defined and
instantiated in one go. (GeeksforGeeks)

Here is a simplified diagram summarising:


1.3 Anonymous Classes

Definition:
An anonymous class is an inner class without a name. It is declared and instantiated in a single
expression. It is useful when you need a one-time class for immediate use. (Oracle
Documentation)

Key characteristics:

• No name.

• Defined and instantiated at the point of creation (using new).

• Can either extend a class or implement an interface in the same expression.


(TutorialsPoint)

• Cannot declare any constructors (because there is no class name). (Baeldung on Kotlin)

• Scope is limited: the anonymous class is usable only at the point where it is defined.
(DigitalOcean)

Types of Anonymous Inner Classes: (as per one classification) (GeeksforGeeks)


1. Anonymous inner class that extends a class.

2. Anonymous inner class that implements an interface.

3. Anonymous inner class used as a method / constructor argument.

Syntax Example:

// Example Type 1: extends a class

Car c2 = new Car() {


@Override
public void engineType() {

[Link]("V2 Engine");

};
[Link]();

// Example Type 2: implements an interface

Software s = new Software() {

@Override

public void develop() {

[Link]("Software Developed in Java");

}
};

[Link]();

(TutorialsPoint)

When to use:

• When you need an instance of a class just once, and you do not want to create a separate
named class.

• Good for short event handlers (especially in GUI programming) or simple


override/implementation on the fly.
• Note: from Java 8 onward you might often use lambdas (for functional interfaces) in
place of some anonymous classes, but understanding them is still vital in the context of
GUI and older APIs.

Pros & Cons (for a 10-year-old simplified):

• Pros: You can write less code because you don’t need a separate named class. It’s “right
there” where you use it.

• Cons: If it becomes large or reused, code becomes messy or harder to read/debug. If you
need reuse, a named class is better. (Stack Overflow)
1.4 Implementation of Nested/Inner Classes
Member Inner Class Example:

class Outer {

private int outerData = 10;

class Inner {
void show() {

[Link]("outerData = " + outerData);

void test() {

Inner in = new Inner();

[Link]();

}
public static void main(String[] args) {

Outer o = new Outer();

[Link]();

• The Inner class is defined inside Outer.

• Inner can access outerData.


• To instantiate: Outer o = new Outer(); [Link] in = [Link] Inner(); (though inside
Outer, new Inner() is fine).
• Good for grouping logic that belongs only to Outer.

Static Nested Class Example:

class Outer {

static class StaticNested {

void display() {
[Link]("In static nested class");
}

public static void main(String[] args) {

[Link] sn = new [Link]();


[Link]();

• Because the nested class is static, you don’t need an Outer instance.

• It cannot directly refer to non-static members of Outer.

Local Inner Class Example:

class Outer {

void method() {
final int localVar = 100; // or effectively final in Java 8+

class LocalInner {

void print() {

[Link]("localVar = " + localVar);

LocalInner li = new LocalInner();


[Link]();

• LocalInner is defined inside method method().

• Its scope is inside that method.

Anonymous Inner Class Example:

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked");

});

• Here, we create an object of an anonymous class implementing ActionListener.


• The class has no name; immediately used.

1.5 Why & When to Use Inner / Anonymous Classes

Reasons / Advantages:

• Encapsulation: inner classes allow keeping classes that belong together in one place.

• Readability: logic that is tightly coupled with outer class can be placed inside.

• Access: inner classes (non‐static) have easy access to outer class members (including
private).

• Convenience: anonymous classes simplify single‐use implementations (often for event


handling).

When to avoid / consider alternatives:

• If the inner class is large or used by many other classes → make it a top‐level class.

• Overuse of anonymous classes can make code difficult to read/debug.


• From Java 8+ for interface implementations with single abstract method, lambdas may be
clearer.

Summary / Tip for exam:


• Understand and remember the classification: static nested vs non‐static inner; inner has
member, local, anonymous.
• Know the benefits of inner classes and differences vs static nested.

• Know syntax for creating objects of inner classes.

• Know anonymous classes: definition, types, syntax, use‐cases.

2. Event Handling in Java

This covers GUI‐event handling concepts: mechanisms, the delegation model, event classes,
listener interfaces, adapter classes, inner classes for handlers, working with
windows/graphics/text/controls/layouts/menus/images/animation/sound/video etc.
2.1 What is Event Handling?

Definition:
Event handling is the mechanism by which a program responds to events — actions triggered
usually by the user (clicks, key presses), or by other components. For example: pressing a button,
entering text, selecting menu item, closing window. (GeeksforGeeks)

In GUI programming with Java’s AWT/Swing, event handling connects user interactions with
code that executes.
2.2 Event Handling Mechanisms, and the Delegation Event Model

Mechanisms:

• Early Java versions used the inheritance model — components inherited from classes and
overridden event handling methods. This approach had limitations. (O'Reilly Media)

• Modern Java (since JDK 1.1) uses the Delegation Event Model. (O'Reilly Media)

Delegation Event Model – Definition:


In this model:

• The component (event source) generates an event.

• The component delegates the handling of the event to one or more listener objects.

• The listener objects register themselves with the source. When the event occurs, the
source notifies all registered listeners via callback methods. ([Link])

Key participants:

1. Event source: The object on which event occurs (e.g., Button, TextField, Window).
([Link])

2. Event object: An object that encapsulates information about the event (which
component, what type, when, etc.). Eg. ActionEvent, MouseEvent. (O'Reilly Media)

3. Event listener: An object implementing a listener interface, which contains one or more
methods that the source will call when the event occurs. The listener registers itself with
the source by calling e.g. addActionListener(…). (GeeksforGeeks)

Steps / Workflow:

1. Create a GUI component (source).

2. Create a listener (object implementing appropriate interface).

3. Register the listener with the source ([Link]…Listener(listener)).


4. At runtime, when the user performs an action (click, keypress, etc.), the source fires an
event.

5. The event object is created and passed to the listener’s callback method.

6. The listener code executes to handle the event.

Diagram of delegation model:


Why delegation model is good:

• Separation of concerns: UI component generates event, handler logic is separate.


• Flexibility: multiple listeners may register with one source.

• Efficiency: only registered listeners are notified.

• Maintainability: code organised simpler. (Stack Overflow)

2.3 Event Classes & Listener Interfaces

Event Classes:

• Base class: [Link]. (O'Reilly Media)


• Subclasses (in [Link] and [Link]):

o ActionEvent – e.g., button clicked.


o MouseEvent, KeyEvent, WindowEvent, ItemEvent, etc. (O'Reilly Media)
• Event object typically holds: reference to source, timestamp, and event‐specific data (e.g.,
which key pressed). ([Link])

Listener Interfaces:

• A listener is defined by an interface such as:

o ActionListener (with method actionPerformed(ActionEvent e))

o MouseListener, KeyListener, WindowListener, ItemListener, etc.

• When you implement the interface, you provide the logic inside that method.
• Then register the listener with the component: e.g.
[Link](myListener).
2.4 Adapter Classes & Inner Classes for Handlers

Adapter classes:

• Many listener interfaces have multiple methods (e.g., MouseListener has mouseClicked,
mousePressed, mouseReleased, etc.).

• If you want to implement only some of them, you can extend an adapter class (like
MouseAdapter) that implements the interface with empty methods. Then you override
only the methods you need.
• This simplifies your code and reduces boilerplate.

Using inner/anonymous classes for handlers:

• In GUI programming, event‐handler classes are generally short and closely tied to the
GUI component. So you often define them as inner classes (member or anonymous)
inside your GUI class.
• Example of anonymous inner class (common for button click):

• [Link](new ActionListener(){

• public void actionPerformed(ActionEvent e){

• // handle button click

• }

• });

• Using inner/anonymous classes keeps the handler code close to where it is used, which is
often clearer.
2.5 Working with Windows, Graphics, Text, AWT Controls
Windows/Frames:

• A major top‐level window is created using Frame (in AWT) or JFrame (in Swing).

• You handle events like window closing (via WindowListener or WindowAdapter).

• Example: [Link](new WindowAdapter(){ public void


windowClosing(WindowEvent e){ [Link](0); } });

Graphics & Text:

• Use Canvas, Panel, or override paint(Graphics g) to draw shapes/text.


• The Graphics object lets you draw lines, rectangles, strings, images.

AWT Controls (widgets):


• Buttons (Button), Labels (Label), TextField (TextField), TextArea (TextArea), Choice
(Choice), List (List), Checkbox, Scrollbar, etc.

• You attach listeners: e.g., [Link], [Link],


[Link], etc.

• Example:

• Button btn = new Button("Click Me");

• [Link](new ActionListener(){

• public void actionPerformed(ActionEvent e){

• [Link]("Button clicked");

• }
• });

2.6 Layout Managers, Menus

Layout Managers:

• A layout manager controls how components are placed inside containers (like Frame,
Panel).

• Common managers in AWT/Swing:

o FlowLayout – components placed left‐to‐right, then wrap.

o BorderLayout – five regions: North, South, East, West, Center.


o GridLayout – grid of equal sized cells.
o CardLayout, GridBagLayout (advanced)

• Example:

• Frame f = new Frame("Example");

• [Link](new BorderLayout());
• [Link](button1, [Link]);

• [Link](button2, [Link]);

Menus:

• A menu bar (MenuBar) contains menus (Menu), which contain menu items (MenuItem).

• Menu items generate ActionEvents when clicked.

• Example:

• MenuBar mb = new MenuBar();

• Menu file = new Menu("File");


• MenuItem exit = new MenuItem("Exit");

• [Link](exit);

• [Link](file);

• [Link](mb);

• [Link](new ActionListener(){

• public void actionPerformed(ActionEvent e){

• [Link](0);
• }

• });

2.7 Handling Images, Animation, Sound, Video

Images:

• Use [Link]().getImage(...) or ImageIcon (in Swing) to load an image.

• Draw image in paint() via [Link](image, x, y, this).

• Handle media loading asynchronously often.


Animation:
• Typically achieved by repeatedly repainting a component (e.g., inside a loop or using
Timer) and changing the position/state of drawn objects (images/shapes) each time.

• For example, a ball moving across screen: in paint(), draw ball at x‐position; then
increment x, call repaint() with some delay.

Sound / Video:

• Java supports playing audio and video via additional APIs (e.g., [Link],
JavaFX media, or third‐party libs).

• In AWT/Swing context you may use AudioClip, Applet methods (older model), or Clip
from [Link].

• Example:
• AudioClip clip = [Link](getClass().getResource("[Link]"));

• [Link]();

2.8 Summary Tips for Exam

• Be able to list and explain the Delegation Event Model (source → event object →
listener).

• Know how to register listeners and which methods/interfaces correspond to which events.
• Know adapter classes and why they help.

• Be familiar with major GUI component types and layout managers.

• Understand how images, animation, sound integrate into GUI event handling.

• Write short example code to illustrate event handling for button click, window closing,
key press etc.

3. Swing (Java Foundation Classes – JFC)

3.1 Introduction to JFC & Swing

Definition / Overview:

• The Java Foundation Classes (JFC) is a set of APIs for building graphical user
interfaces (GUIs) and adding rich client capabilities to Java applications.

• Swing is the GUI toolkit part of JFC (along with AWT, accessibility, drag-and-drop, etc.).
(Wikipedia)
• Swing was developed to provide a more sophisticated, richer, platform-independent set of
GUI components than the older AWT toolkit. (Wikipedia)

3.2 Features of Swing

• Lightweight components: Swing components (e.g., JButton, JLabel, JTable) are mostly
written in pure Java (no heavy native peer components) → more flexible. (Wikipedia)

• Pluggable Look & Feel: you can change the appearance of Swing components to match
different OS, or custom themes.

• Rich set of components: powerful widgets like trees (JTree), tables (JTable), lists (JList),
sliders, spinners, tabbed panes, etc.

• More control over rendering: you can use paintComponent() etc. to customise.
• MVC architecture: underlying model‐view separation (though somewhat hidden in
Swing) helps in separating data from presentation.

• Double buffering and better rendering for smoother UI.

• Support for accessibility, drag-and-drop, key bindings, etc.

3.3 Comparison with AWT

Feature AWT Swing

Component Heavyweight (native OS


Lightweight (all Java, fewer native peers)
implementation peers)

Uses OS look & feel Pluggable Look & Feel; can mimic OS or
Look & Feel
directly; less flexible custom look

Basic (Button, Label, Richer (JButton, JLabel, JTextField, JTable,


Component set
TextField, List, etc.) JTree, etc.)

High: override paintComponent, custom


Rendering control Limited
rendering

Works with Delegation Uses same model, with enhancements (Swing


Event handling
Model components fire same events)

Threading Requires UI updates in Event Dispatch


Similar but less strict
considerations Thread (EDT) for safety
Exam tip: Be able to say why Swing is preferred over AWT (for new GUI apps): richer
component set, better look & feel control, lighter weight, Java-only implementation → more
portable.

3.4 Advanced Controls in Swing

Some advanced Swing controls and concepts you should know:

• JTable – table component for showing tabular data with rows/columns, selectable cells,
editing support.

• JTree – hierarchical data display (nodes, expand/collapse).

• JTabbedPane – switch among different “pages” in the same window.

• JSplitPane – divide area into resizable panes.

• JInternalFrame – internal frames (for MDI applications) inside JDesktopPane.

• Custom rendering: You can customise how items are drawn by overriding cell renderers,
using ListCellRenderer, TableCellRenderer.

• Use of SwingWorker, background threads for long tasks, and careful use of Event
Dispatch Thread (EDT) to avoid freezing UI.

• Use of icons/images in buttons or labels: new ImageIcon("path"), [Link](ic).


• Event handling: Swing uses the same delegation model as AWT, but with Swing-specific
listener interfaces and event classes.

3.5 Swing Example Snippet


import [Link].*;

import [Link].*;

import [Link].*;

public class MySwingApp {

public static void main(String[] args) {

// Ensure GUI is created on the Event Dispatch Thread


[Link](() -> {

JFrame frame = new JFrame("My Swing App");


[Link](JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Click Me");

[Link](new ActionListener(){

public void actionPerformed(ActionEvent e) {

[Link](frame, "Button clicked");


}

});

[Link]().add(btn, [Link]);

[Link](300,200);

[Link](true);

});

}
• JFrame is top container.

• JButton is a Swing button.

• addActionListener adds a handler via anonymous class.

• [Link] ensures UI is created in EDT (good practice).

• JOptionPane shows a modal dialog.

3.6 Summary Tips for Exam

• Define JFC and Swing, list features.


• Contrast Swing vs AWT.

• Be able to name and describe some advanced controls.

• Understand event handling in Swing (same model but more robust).

• Know best practice: UI updates on Event Dispatch Thread.

• For deeper depth: mention how custom rendering, table/tree, internal frames work.

4. Summary of All Topics (for revision)


• Nested/Inner Classes: definition, types (static nested, member inner, local inner,
anonymous inner), benefits and use-cases, syntax/examples.

• Anonymous Classes: no name, one‐time use, types (extends class, implements interface,
method/constructor argument), when to use, syntax.

• Event Handling in Java: What is event handling; difference between old model and
Delegation Event Model; key participants (source, event object, listener); steps; event
classes and listener interfaces; adapter & inner/anonymous classes for handling; AWT
controls, windows, graphics/text, layout managers, menus, image/animation/sound/video.

• Swing and JFC: Introduction, features, comparison with AWT, advanced controls,
example code, good practices.

5. Diagrams & Visual Aids


Here are some additional diagrams to help you visualise key points:

Delegation Event Model Diagram

Swing vs AWT Architecture Diagram


6. Additional Notes & Tips for Exam
• Write small code examples in the exam to illustrate inner classes and event handling:
showing the creation of an anonymous class for a button click is often expected.

• For diagrams, you can draw a simple flow: User action → event source → event object
→ registered listener → handler method executes.

• Understand access privileges: inner classes can access outer class’s private members;
static nested cannot.

• Remember layout managers by name and briefly what they do (FlowLayout,


BorderLayout, GridLayout).
• For Swing vs AWT: emphasise lightweight vs heavyweight, rich component set,
pluggable Look & Feel.
• Keep in mind thread safety: in Swing, updates to GUI should happen on the Event
Dispatch Thread (EDT).

• Do not ignore image/sound/animation: you may get questions like “how would you
animate a graphic in Java GUI?”. Answer: repeatedly update state + call repaint(); use a
Timer or thread; handle images via drawImage, handle audio via Clip etc.

• Adapters are especially useful to remember: for example, if you implement


MouseListener, you must override all methods; instead you can extend MouseAdapter
and override only what you need.

• Always mention that registration of listener is essential: [Link](…).


Without registration, listener won’t receive events.

• Regarding anonymous inner classes, emphasise: no class name, defined/instantiated in


same place, good for one‐time use, extends a class or implements an interface.

• For inner classes: mention member inner, local inner, anonymous inner. Also mention that
inner classes increase coupling but may improve encapsulation when used appropriately.
UNIT-4

1. JDBC (Java Database Connectivity)

1.1 Introduction to DBMS & RDBMS

DBMS (Database Management System)


• Definition: A DBMS is a software system that enables creation, management, and use of
databases. It provides functionalities such as storing, retrieving, updating, and managing
data.

• Key ideas:

o It allows multiple users or applications to access the data safely and reliably.
o It enforces integrity, security, concurrency control, backup & recovery.

• Example use-case: A university keeps student records, courses, marks in a DBMS.

RDBMS (Relational Database Management System)

• Definition: An RDBMS is a type of DBMS in which data is stored in tables (relations),


rows (tuples), and columns (attributes). Relationships are defined between tables.

• Key features:

o Tables, primary keys, foreign keys.

o SQL (Structured Query Language) to query and manipulate data.

o ACID properties: Atomicity, Consistency, Isolation, Durability.

• Why “relational”? Data is represented in relations and the system uses relational algebra
beneath.

• Example: MySQL, Oracle, PostgreSQL are RDBMS.


Why we need RDBMS for Java applications: When you create a Java program that needs to
store and query data (for example, a student management system), you use an RDBMS to keep
the data and an interface (API) to connect to it (that’s where JDBC comes in).

1.2 What is JDBC? (Java Database Connectivity)


• Definition: Java Database Connectivity (JDBC) is a Java API (Application Programming
Interface) that lets Java programs connect to a relational database, send SQL queries,
retrieve results and update data. (GeeksforGeeks)
• It is part of the Java platform (in [Link] and [Link] packages) and works with many
databases, provided there is a suitable driver. (Wikipedia)

• Purpose: Allow Java applications (desktop, web, mobile backend) to interact with
databases in a database-independent way.

1.3 JDBC API – Key Interfaces & Classes

Here are some of the main components of JDBC, explained simply:

• DriverManager: This class loads and manages the database drivers. It is the starting
point for getting a database connection.

• Driver: Interface implemented by database vendors. Represents a specific database


driver (e.g., for MySQL).

• Connection: Interface that represents a connection (session) with a specific database.


Through it you send SQL statements and control transactions.

• Statement: Interface to send SQL statements (often static SQL) to the database.

• PreparedStatement: A sub‐interface of Statement that allows you to create SQL


statements with parameters (placeholders) which can be executed multiple times.

• CallableStatement: Another sub‐interface of Statement, used to call database stored


procedures.

• ResultSet: Interface representing the result of executing a SQL query (e.g., a SELECT).
It allows you to move through rows of data and get column values.

• SQLException: Exception thrown when there is a database access error or other errors.

• DataSource (in [Link]): An alternative to DriverManager; it provides connection-


pooling, distributed transactions, etc.

These are explained in the official tutorial. (Oracle Documentation)

1.4 JDBC Application Architecture


Diagram (text format):

+---------------------+

| Java Application |
+---------------------+
|

+---------------------+

| JDBC API |
| ([Link] / [Link])|

+---------------------+

+---------------------+

| JDBC Driver(s) |

| (vendor specific) |

+---------------------+
|

+---------------------+

| Database Server |

| (RDBMS) |

+---------------------+

Explanation:
1. The Java application uses JDBC API to request a connection, execute SQL, fetch results.

2. The JDBC driver (provided by the database vendor) translates those calls into database-
specific operations (network protocol, native library, etc.).

3. The database server executes the SQL and returns results.

4. The JDBC driver wraps the results back into ResultSet objects returned to the application.

Why this architecture matters: It decouples your Java code from the database vendor — you
can switch from one RDBMS to another (in many cases) by just changing driver/URL with
minimal code changes.
1.5 Obtaining a Connection

The basic steps to establish a connection:

1. Load/Register the JDBC driver. Example:

2. [Link]("[Link]");
(With newer JDBC versions, automatic driver loading may happen so you might skip this)

3. Use [Link](...) method to get a Connection object. Example:

4. Connection conn = [Link](

5. "jdbc:mysql://localhost:3306/mydb", "username", "password");

6. Once you have the Connection, you can create Statement, PreparedStatement, etc.

7. At the end, close the connection (ideally in a finally block or use Java 7+ try‐with‐
resources).

8. [Link]();

Important details:

• The URL pattern varies by database vendor.


• Many applications use DataSource instead of DriverManager for better features
(pooling).
• Always handle SQLException.

1.6 JDBC Models: Two-Tier and Three-Tier Models

When building applications, the architecture of how the client (UI), application logic, and
database server are arranged is important. Two common models:

Two-Tier Model

• Architecture: Client ↔ Database

• The client application directly connects to the database and executes queries.

• Advantages: Simple, fewer layers, fast for small systems.

• Disadvantages: Hard to scale, business logic in client, tight coupling, less secure.
• Diagram (text):
• [Client Application] <---> [Database Server]
Three-Tier Model

• Architecture: Client (Presentation) ↔ Application Server (Business Logic) ↔


Database Server

• The client interacts with an application layer (for example a Java server or web server)
which in turn connects to the database via JDBC.

• Advantages: Better modularity, easier to maintain, business logic separated, improved


security, can scale.

• Disadvantages: More complexity, cost.

• Diagram (text):

• [Client UI] <---> [Application Server] <---> [Database Server]

• |

• \--(using JDBC)--> [Database]


Which model for MCA? For most enterprise Java applications you will use the three-tier
model.

1.7 ResultSet, PreparedStatement, CallableStatement

ResultSet

• Definition: ResultSet is the JDBC interface used to hold the results of a query (usually a
SELECT). You can iterate over rows and get column values.

• Types / modes (depending on driver support):

o TYPE_FORWARD_ONLY: rows can be traversed only forward.


o TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE: you can move
backward, jump to specific rows.

o CONCUR_READ_ONLY, CONCUR_UPDATABLE: read only or can update.

• Usage:

• Statement stmt = [Link]();


• ResultSet rs = [Link]("SELECT * FROM Students");

• while ([Link]()) {
• int id = [Link]("id");
• String name = [Link]("name");

• // process

• }

• [Link]();
• [Link]();

• Note: Always close ResultSet, Statement, Connection.

PreparedStatement

• Definition: A PreparedStatement is a SQL statement which is pre‐compiled on the


database. It allows parameter placeholders (?) and can be executed multiple times with
different values.

• Why use it?

o Better performance when executing similar SQL repeatedly.

o Helps prevent SQL injection (external user inputs are bound as parameters).

o Cleaner code.

• Example:

• String sql = "INSERT INTO Students (name, age) VALUES (?, ?)";
• PreparedStatement ps = [Link](sql);

• [Link](1, "Alice");

• [Link](2, 20);

• [Link]();
• [Link](1, "Bob");

• [Link](2, 22);

• [Link]();

• [Link]();
CallableStatement

• Definition: A CallableStatement is used to call stored procedures (in the database) from
Java. Stored Procedures are pre‐defined SQL modules in the database.
• Usage:
• CallableStatement cs = [Link]("{call GetStudentById(?, ?)}");

• [Link](1, 101); // input parameter

• [Link](2, [Link]); // output parameter

• [Link]();
• String studentName = [Link](2);

• [Link]();

• When to use: When business logic resides inside the database (heavy logic, reused across
applications) and you want to call it from Java.

1.8 Summary of JDBC Section

• We learned what DBMS and RDBMS are.

• We defined JDBC and saw its architecture.

• We saw how to obtain a connection.

• We discussed two-tier vs three-tier models.


• We studied key JDBC interfaces: ResultSet, PreparedStatement, CallableStatement.

• Important for exam: know definitions, diagrams, usage, pros/cons.

2. Input/Output Programming (in Java)

2.1 Basics of I/O in Java

• Definition: I/O (Input/Output) programming refers to reading data from input sources
(keyboard, file, network) and writing data to output destinations (console, file, network).

• In Java, I/O is handled via streams—a stream is a sequence of data (either bytes or
characters) that flows from a source to a destination. (Rice University)

• Streams provide a uniform way to handle different data sources/destinations (files,


memory, network, console).

• Two main categories: Byte streams and Character streams.

2.2 Streams, Byte and Character Streams, Predefined Streams


What is a Stream?

• A stream is an abstraction for reading or writing data. Think of reading water from a pipe
(input stream) or writing water into a pipe (output stream).

• In Java:

o InputStream / OutputStream classes for byte streams.

o Reader / Writer classes for character streams.

o They are located in [Link] package (and newer [Link] packages). (Oracle
Documentation)

Byte Streams
• Definition: Streams that handle raw binary data (8-bit bytes). Suitable for non-text data
(images, audio, video, executable files). (GeeksforGeeks)

• Base classes: InputStream, OutputStream.


• Common classes: FileInputStream, FileOutputStream, BufferedInputStream,
DataInputStream etc. (@knowledgehut)
• Example code (copying bytes):

• FileInputStream in = new FileInputStream("[Link]");

• FileOutputStream out = new FileOutputStream("[Link]");

• int b;

• while ((b = [Link]()) != -1) {

• [Link](b);

• }
• [Link]();

• [Link]();

• ``` :contentReference[oaicite:10]{index=10}

• When to use: When dealing with binary data (images, videos, etc.) or raw streams where
encoding isn’t relevant.

Character Streams

• Definition: Streams that handle character data (16-bit Unicode characters). Suitable for
text files, where you need to respect character encoding. (Oracle Documentation)
• Base classes: Reader, Writer.

• Common classes: FileReader, FileWriter, BufferedReader, BufferedWriter,


InputStreamReader, OutputStreamWriter. (GeeksforGeeks)

• Example code (reading text):

• FileReader reader = new FileReader("[Link]");

• FileWriter writer = new FileWriter("[Link]");

• int c;
• while ((c = [Link]()) != -1) {

• [Link](c);
• }

• [Link]();

• [Link]();

• ``` :contentReference[oaicite:13]{index=13}

• Why character streams wrap byte streams: Internally a text file is bytes; the character
stream handles conversion between bytes and characters using encoding. (Stack
Overflow)

• When to use: For text processing (reading/writing .txt files, reading lines, etc.).

Predefined Streams

In Java, the JVM provides three standard streams which are always available:
• [Link] — Standard input stream (keyboard) (byte stream: InputStream)

• [Link] — Standard output stream (console) (print to screen)

• [Link] — Standard error output stream (console for error messages)


You can wrap them in higher-level Streams/Writers (e.g., BufferedReader(new
InputStreamReader([Link])) for reading keyboard input as characters).

2.3 Reading and Writing from Console and Files

Reading/Writing from Console

• Reading: Using Scanner, BufferedReader, InputStreamReader. For example:


• BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
• [Link]("Enter your name: ");

• String name = [Link]();

• Writing: Using [Link](), PrintWriter, etc.

• [Link]("Hello, " + name);


Reading/Writing Files

• Writing bytes to file:

• FileOutputStream fos = new FileOutputStream("[Link]");

• [Link](byteArray);

• [Link]();

• Reading bytes from file:

• FileInputStream fis = new FileInputStream("[Link]");

• int b;
• while ((b = [Link]()) != -1) {

• // process byte

• }

• [Link]();

• Writing characters to file:

• FileWriter fw = new FileWriter("[Link]");

• [Link]("Hello World");
• [Link]();

• Reading characters from file:

• FileReader fr = new FileReader("[Link]");

• int c;

• while ((c = [Link]()) != -1) {

• char ch = (char)c;

• // process
• }
• [Link]();

• Using buffered streams for performance:

• BufferedReader br = new BufferedReader(new FileReader("[Link]"));

• String line;
• while ((line = [Link]()) != null) {

• [Link](line);

• }

• [Link]();

Buffering reduces the number of system calls and improves performance. (GeeksforGeeks)

Important considerations

• Always close streams (in finally block or try-with-resources) to free resources and avoid
leaks.

• Consider character encoding when reading/writing text (use InputStreamReader /


OutputStreamWriter with encoding). (Oracle Documentation)

• Use correct stream type depending on data (binary vs text).

• Handle exceptions (IOException, FileNotFoundException).

2.4 Summary of I/O Section

• Learned what I/O means in Java (reading/writing data).

• Defined streams, byte streams vs character streams, and their use‐cases.


• Covered predefined console streams.

• Showed how to read/write from console and files, including best practices (buffering,
closing streams).

• For exam: know definitions, class hierarchies (InputStream/OutputStream vs


Reader/Writer), difference diagrams, example code snippets.

3. Diagrams & Comparative Tables


3.1 JDBC Architecture Diagram
Java Application

JDBC API

|
JDBC Drivers

Relational Database (RDBMS)

3.2 Two-Tier vs Three-Tier

Model Architecture Advantages Disadvantages

Poor modularity, security &


Two-Tier Client ↔ Database Simple, direct
scaling issues

Three- Client ↔ App Server ↔ Modular, scalable, More complex, more


Tier Database secure infrastructure

3.3 Byte vs Character Streams Comparison

Feature Byte Streams Character Streams

Data unit Bytes (8 bits) Characters (16 bits, Unicode)

Base classes InputStream, OutputStream Reader, Writer

Text data (files, keyboard


Use-case Binary data (images, audio)
input)

Class names usually end …Stream …Reader, …Writer

FileInputStream,
Example classes FileReader, BufferedWriter
BufferedInputStream

3.4 JDBC Workflow (textual)

1. Load driver (optional).

2. Get Connection via DriverManager or DataSource.

3. Create Statement / PreparedStatement / CallableStatement.


4. Execute SQL (e.g., executeQuery() or executeUpdate()).
5. If query, receive ResultSet. Iterate rows, fetch data.

6. Process data in Java.

7. Close ResultSet, Statement, Connection.

5. Summary

• The first part (JDBC) equips you with how Java connects to a database, the architecture,
what two- and three-tier models look like, and how statements like ResultSet,
PreparedStatement and CallableStatement are used.

• The second part (I/O Programming) gives you how Java handles input and output, the
difference between byte streams and character streams, how to read/write from console
and files, and the classes involved.

• Both topics are very important for a database‐driven Java application (for an MCA
course) and are foundational.

Java 8 Concepts

Java 8 introduced many new features to make coding more concise, readable, and efficient. The
main features include Default and Functional Interfaces, Lambda Expressions, Stream API
and Pipelines, Try-With-Resources, and memory optimizations.

1. Default and Functional Interfaces

1.1 Interface in Java


• An interface in Java is a blueprint of a class, having abstract methods.

• Before Java 8: All methods in interfaces were abstract.

• Java 8 added default and static methods.

1.2 Default Interface Methods

• A default method is a method in an interface that has a body.

• Syntax:
interface MyInterface {
default void display() {

[Link]("This is a default method.");

}
Key Points

• Allows adding new methods in existing interfaces without breaking implementing


classes.
• Cannot override Object class methods like toString().

• Can be overridden in implementing classes.

1.3 Functional Interface

• A Functional Interface is an interface with exactly one abstract method.

• Can have default or static methods, but only one abstract method.

• Example:
@FunctionalInterface

interface Calculator {

int add(int a, int b);

Common Functional Interfaces in Java 8

Interface Description

Runnable Represents a task that can run in a thread.

Callable<V> Returns a value and can throw exception.

Comparator<T> Compares two objects.

Function<T, R> Accepts one argument and produces a result.

Predicate<T> Evaluates a condition and returns boolean.

Consumer<T> Performs an action on input.


2. Lambda Expressions

2.1 Definition

• Lambda expression is a short block of code which takes parameters and returns a
value.

• Used primarily for functional interfaces.

2.2 Syntax
(parameters) -> expression

(parameters) -> { statements; }


Examples

// Example 1: No parameter

() -> [Link]("Hello Lambda");

// Example 2: One parameter


x -> x * x;

// Example 3: Two parameters

(a, b) -> a + b;

2.3 Benefits

• Concise and less boilerplate code.

• Enables functional programming.


• Makes collection processing easier.

3. Java Stream API and Pipelines

3.1 Definition

• Stream API allows processing of collections in a functional style.


• Stream is a sequence of elements supporting aggregate operations.
3.2 Key Concepts

1. Source: Collection, array, or I/O channel.

2. Intermediate Operations: Transform stream into another stream (e.g., filter, map).
3. Terminal Operations: Produce result or side-effect (e.g., collect, forEach).

3.3 Stream Pipeline

• A pipeline is a sequence of stream operations.

• Structure:

Source → Intermediate Operations → Terminal Operation

• Example:

List<Integer> numbers = [Link](1,2,3,4,5);


[Link]()

.filter(n -> n % 2 == 0) // Intermediate

.map(n -> n * n) // Intermediate

.forEach([Link]::println); // Terminal

Common Intermediate Operations

Operation Description

filter() Filters elements by a condition

map() Transforms elements

sorted() Sorts elements

distinct() Removes duplicates

Common Terminal Operations

Operation Description

forEach() Iterates elements


Operation Description

collect() Converts stream to collection

reduce() Aggregates elements

count() Counts elements

4. Try-With-Resources

4.1 Definition

• Automatic resource management in Java 8.


• Any resource that implements AutoCloseable can be used.

4.2 Syntax

try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {

[Link]([Link]());

} catch(IOException e) {

[Link]();

}
4.3 Benefits

• Automatically closes resources.

• Avoids memory leaks.

• Cleaner code than traditional try-catch-finally.

5. Java 8 Memory Optimization

5.1 Key Areas

1. PermGen removed: Replaced by Metaspace (dynamically resizable).


2. Lambda Expressions:

o Use invokedynamic for runtime binding.


o Avoid unnecessary anonymous classes.
3. Streams:

o Lazy evaluation reduces memory footprint.

4. Try-With-Resources:

o Ensures timely closure of resources.

RMI (Remote Method Invocation)

RMI is a Java API that allows an object running in one JVM to invoke methods of an object in
another JVM.

1. Introduction

• RMI enables distributed computing in Java.

• Allows communication between remote Java programs.

• Works over TCP/IP.

Key Features
• Remote method calls.

• Type safety (compile-time checking).

• Object serialization.

2. Steps in Creating a Remote Object

1. Define Remote Interface

o Must extend [Link].


o Declare remote methods with throws RemoteException.

import [Link].*;

public interface Hello extends Remote {

String sayHello() throws RemoteException;

}
2. Implement Remote Interface
import [Link];

public class HelloImpl extends UnicastRemoteObject implements Hello {

public HelloImpl() throws RemoteException { super(); }

public String sayHello() { return "Hello, RMI!"; }


}

3. Compile the Classes

javac *.java

4. Generate Stub & Skeleton

• Stub: Proxy object on client-side.

• Skeleton: Server-side dispatcher (before Java 5, now optional).

rmic HelloImpl

5. Start RMI Registry


rmiregistry

6. Bind Remote Object

[Link]("HelloServer", new HelloImpl());

7. Client Lookup

Hello obj = (Hello) [Link]("rmi://localhost/HelloServer");

[Link]([Link]());

3. RMI Architecture

Diagram:

+--------------------+ +--------------------+

| Client JVM | | Server JVM |

| | | |

| Lookup & Call |<-----> | Remote Object Impl |

| | | |
+--------------------+ +--------------------+
^ ^

| |

| RMI Registry |

+------------------------------+
Components

1. Client: Calls remote methods.

2. Server: Implements remote methods.

3. Remote Interface: Defines methods.

4. Stub: Client-side proxy.

5. Skeleton (Optional): Server-side dispatcher.

6. RMI Registry: Stores references to remote objects.

4. RMI Packages

• [Link]: Core RMI classes (Remote, RemoteException, Naming).

• [Link]: Server-side utilities (UnicastRemoteObject, RemoteServer).

• [Link]: For RMI registry operations (LocateRegistry).

5. Summary of RMI Steps

1. Create remote interface.


2. Implement remote object.

3. Compile and generate stub.

4. Start RMI registry.

5. Bind object to registry.

6. Client looks up object and invokes method.

Important Points

• RMI uses object serialization.


• Supports remote exceptions.

• Uses dynamic class loading.

You might also like