0% found this document useful (0 votes)
10 views102 pages

Matrix Operations and Collections Guide

Uploaded by

ujjawal pandey
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)
10 views102 pages

Matrix Operations and Collections Guide

Uploaded by

ujjawal pandey
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

for(int k = 0; k < 3; k++) {

mul[i][j] += a[i][k] * b[k][j];


}
}
}

// Display Addition
[Link]("Matrix Addition:");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
[Link](sum[i][j] + " ");
}
[Link]();
}

// Display Multiplication
[Link]("\nMatrix Multiplication:");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
[Link](mul[i][j] + " ");
}
[Link]();
}
}

**Sample Output:**

Matrix Addition:
10 10 10
10 10 10
10 10 10

Matrix Multiplication:
30 24 18
84 69 54
138 114 90
### 5. Collections Framework

**Need:**
1. Store and manipulate group of objects
2. Dynamic size (unlike arrays)
3. Ready-made data structures
4. Algorithms for searching, sorting
5. Better performance and flexibility

**Collections Framework Hierarchy:**

Collection (Interface)

┌───────┼───────┐
↓ ↓ ↓

List Set Queue


↓ ↓ ↓
ArrayList HashSet PriorityQueue
LinkedList TreeSet LinkedList
Vector

Stack

**Map Interface (Separate):**

Map (Interface)

┌───┼───┐
HashMap TreeMap LinkedHashMap
**Key Interfaces:**

**1. Collection Interface:**


- Root interface
- Basic operations: add, remove, size, clear

**2. List Interface:**


- Ordered collection
- Allows duplicates
- Index-based access
- Classes: ArrayList, LinkedList, Vector, Stack

**3. Set Interface:**


- No duplicates
- Unordered (HashSet) or sorted (TreeSet)
- Classes: HashSet, LinkedHashSet, TreeSet

**4. Queue Interface:**


- FIFO (First In First Out)
- Classes: PriorityQueue, LinkedList

**5. Map Interface:**


- Key-value pairs
- No duplicate keys
- Classes: HashMap, TreeMap, LinkedHashMap

### 6. Collection and List Interface Methods

**Collection Interface Methods:**


```java
// 1. add(E e) - Add element
[Link]("Java");

// 2. remove(Object o) - Remove element


[Link]("Java");

// 3. size() - Return size


int size = [Link]();

// 4. isEmpty() - Check if empty


boolean empty = [Link]();
// 5. contains(Object o) - Check if contains
boolean has = [Link]("Java");

// 6. clear() - Remove all elements


[Link]();

// 7. iterator() - Return iterator


Iterator it = [Link]();

// 8. toArray() - Convert to array


Object[] arr = [Link]();

// 9. addAll(Collection c) - Add all elements


[Link](anotherCollection);

// 10. removeAll(Collection c) - Remove all


[Link](anotherCollection);

List Interface Methods:

java
// 1. add(int index, E element) - Add at index
[Link](0, "First");

// 2. get(int index) - Get element at index


String s = [Link](0);

// 3. set(int index, E element) - Replace element


[Link](0, "Updated");

// 4. remove(int index) - Remove at index


[Link](0);

// 5. indexOf(Object o) - Find first index


int index = [Link]("Java");

// 6. lastIndexOf(Object o) - Find last index


int lastIndex = [Link]("Java");

// 7. subList(int from, int to) - Get sublist


List sublist = [Link](0, 3);

// 8. sort(Comparator c) - Sort list


[Link]([Link]());

// 9. listIterator() - Get list iterator


ListIterator lit = [Link]();

// 10. addAll(int index, Collection c) - Add all at index


[Link](0, anotherList);

7. ArrayList, Vector, and Stack


ArrayList Example:

java
import [Link];

class ArrayListDemo {
public static void main(String[] args) {
// Create ArrayList
ArrayList<String> list = new ArrayList<>();

// Add elements
[Link]("Java");
[Link]("Python");
[Link]("C++");

// Display
[Link]("ArrayList: " + list);

// Get element
[Link]("Element at 1: " + [Link](1));

// Remove element
[Link](1);
[Link]("After removal: " + list);

// Size
[Link]("Size: " + [Link]());

// Iterate
for(String s : list) {
[Link](s);
}
}
}

Output:

ArrayList: [Java, Python, C++]


Element at 1: Python
After removal: [Java, C++]
Size: 2
Java
C++

Vector Example:
java

import [Link];

class VectorDemo {
public static void main(String[] args) {
Vector<Integer> v = new Vector<>();

// Add elements
[Link](10);
[Link](20);
[Link](30);

[Link]("Vector: " + v);

// Add at specific position


[Link](1, 15);
[Link]("After insertion: " + v);

// Remove element
[Link](2);
[Link]("After removal: " + v);

// Capacity
[Link]("Capacity: " + [Link]());
[Link]("Size: " + [Link]());
}
}

Output:

Vector: [10, 20, 30]


After insertion: [10, 15, 20, 30]
After removal: [10, 15, 30]
Capacity: 10
Size: 3

Stack Example:

java
import [Link];

class StackDemo {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();

// Push elements
[Link]("First");
[Link]("Second");
[Link]("Third");

[Link]("Stack: " + stack);

// Peek - view top element


[Link]("Top: " + [Link]());

// Pop - remove top element


[Link]("Popped: " + [Link]());
[Link]("After pop: " + stack);

// Check if empty
[Link]("Is empty: " + [Link]());

// Search element (position from top)


[Link]("Position of 'First': " + [Link]("First"));
}
}

Output:

Stack: [First, Second, Third]


Top: Third
Popped: Third
After pop: [First, Second]
Is empty: false
Position of 'First': 2

8. List Operations Program

java
import [Link];
import [Link];

class ListOperations {
public static void main(String[] args) {
// Create List
List<String> letters = new ArrayList<>();

// Add letters
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link]("E");

[Link]("Original List: " + letters);


[Link]("Size: " + [Link]());

// Add more letters


[Link]("F");
[Link]("G");
[Link]("\nAfter adding: " + letters);
[Link]("Size: " + [Link]());

// Remove specific letter


[Link]("C");
[Link]("\nAfter removing 'C': " + letters);
[Link]("Size: " + [Link]());

// Remove by index
[Link](0);
[Link]("\nAfter removing first element: " + letters);
[Link]("Size: " + [Link]());

// Check if contains
[Link]("\nContains 'B': " + [Link]("B"));
[Link]("Contains 'Z': " + [Link]("Z"));

// Get element at index


[Link]("\nElement at index 2: " + [Link](2));

// Clear all
[Link]();
[Link]("\nAfter clearing: " + letters);
[Link]("Size: " + [Link]());
[Link]("Is empty: " + [Link]());
}
}

Sample Output:

Original List: [A, B, C, D, E]


Size: 5

After adding: [A, B, C, D, E, F, G]


Size: 7

After removing 'C': [A, B, D, E, F, G]


Size: 6

After removing first element: [B, D, E, F, G]


Size: 5

Contains 'B': true


Contains 'Z': false

Element at index 2: E

After clearing: []
Size: 0
Is empty: true

9. Streams in Java
Definition: Stream is a sequence of data. Java provides streams to perform I/O operations.

Types of Streams:

Stream Hierarchy:
Stream
↙ ↘
InputStream OutputStream
↓ ↓
FileInputStream FileOutputStream
BufferedInputStream BufferedOutputStream
DataInputStream DataOutputStream
ObjectInputStream ObjectOutputStream

1. Byte Streams:

Handle binary data (images, audio, video)

InputStream and OutputStream classes

8-bit bytes

2. Character Streams:

Handle text data


Reader and Writer classes

16-bit Unicode characters

Byte Stream Example:

java
import [Link].*;

class ByteStreamDemo {
public static void main(String[] args) {
try {
// Write to file
FileOutputStream fout = new FileOutputStream("[Link]");
String s = "Hello Java";
byte[] b = [Link]();
[Link](b);
[Link]();
[Link]("Written successfully");

// Read from file


FileInputStream fin = new FileInputStream("[Link]");
int i;
while((i = [Link]()) != -1) {
[Link]((char)i);
}
[Link]();
} catch(Exception e) {
[Link](e);
}
}
}

Character Stream Example:

java
import [Link].*;

class CharacterStreamDemo {
public static void main(String[] args) {
try {
// Write to file
FileWriter fw = new FileWriter("[Link]");
[Link]("Learning Java Streams");
[Link]();
[Link]("Written successfully");

// Read from file


FileReader fr = new FileReader("[Link]");
int i;
while((i = [Link]()) != -1) {
[Link]((char)i);
}
[Link]();
} catch(Exception e) {
[Link](e);
}
}
}

Buffered Stream Example:

java
import [Link].*;

class BufferedStreamDemo {
public static void main(String[] args) {
try {
// Buffered Writer
FileWriter fw = new FileWriter("[Link]");
BufferedWriter bw = new BufferedWriter(fw);

[Link]("Java Programming");
[Link]();
[Link]("Buffered Streams");
[Link]();
[Link]("Written with buffer");

// Buffered Reader
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);

String line;
while((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch(Exception e) {
[Link](e);
}
}
}

Stream Diagram:

Application

Stream

File/Network/Memory

Flow:
Input Stream: Source → Stream → Program
Output Stream: Program → Stream → Destination
Advantages:

1. Efficient data handling

2. Automatic buffering
3. Support for different data types

4. Error handling

UNIT 5: JDBC and Database

1. Need for Database Applications with JDBC


Need for Database:

1. Store large amount of data permanently

2. Efficient data retrieval


3. Data security and integrity

4. Concurrent access
5. Data consistency

JDBC (Java Database Connectivity):

API for connecting Java application with database

Provides methods to query and update database

Database independent

JDBC Layout/Architecture:

Java Application

JDBC API

JDBC Driver Manager

JDBC Driver

Database

Components:

1. JDBC API - Provides interfaces and classes


2. Driver Manager - Manages database drivers
3. JDBC Driver - Implements JDBC interfaces for specific database

4. Connection - Session with database

5. Statement - Execute SQL queries

6. ResultSet - Store query results

Advantages:

Database independent code


Easy to use

Automatic type conversion

Performance optimization
Transaction management

2. Steps to Connect MS-Access Database


Steps:

Step 1: Import JDBC packages

java

import [Link].*;

Step 2: Load JDBC Driver

java

[Link]("[Link]");

Step 3: Establish Connection

java

Connection con = [Link](


"jdbc:odbc:StudentDSN", "", ""
);

Step 4: Create Statement

java
Statement stmt = [Link]();

Step 5: Execute Query

java

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

Step 6: Process Results

java

while([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}

Step 7: Close Connection

java

[Link]();

Complete Example:

java
import [Link].*;

class JDBCDemo {
public static void main(String[] args) {
try {
// Step 1 & 2: Load Driver
[Link]("[Link]");
[Link]("Driver loaded");

// Step 3: Create Connection


Connection con = [Link](
"jdbc:odbc:StudentDSN", "", ""
);
[Link]("Connected to database");

// Step 4: Create Statement


Statement stmt = [Link]();

// Step 5: Execute Query


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

// Step 6: Process Results


[Link]("ID\tName\tAge");
while([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link](id + "\t" + name + "\t" + age);
}

// Step 7: Close Connection


[Link]();
[Link]();
[Link]();
[Link]("Connection closed");

} catch(Exception e) {
[Link](e);
}
}
}

Output:

Driver loaded
Connected to database
ID Name Age
1 John 20
2 Alice 22
3 Bob 21
Connection closed

Insert Data Example:

java

String query = "INSERT INTO Student VALUES(4, 'David', 23)";


int rows = [Link](query);
[Link](rows + " row inserted");

Update Data Example:

java

String query = "UPDATE Student SET age=24 WHERE id=4";


int rows = [Link](query);
[Link](rows + " row updated");

Delete Data Example:

java

String query = "DELETE FROM Student WHERE id=4";


int rows = [Link](query);
[Link](rows + " row deleted");

3. Four Types of JDBC Drivers


JDBC Driver Architecture:
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native-API Driver
Type 3: Network Protocol Driver
Type 4: Thin Driver (Pure Java)

Type 1: JDBC-ODBC Bridge Driver

Java App → JDBC → ODBC Bridge → ODBC Driver → Database

Advantages:

Easy to use
Can connect to any database with ODBC driver
No need for database-specific driver

Disadvantages:

Slow performance (multiple layers)

ODBC driver required


Platform dependent

Not suitable for production

Diagram:

┌─────────────┐
│ Java App │
└──────┬──────┘

┌──────────────┐
│ JDBC-ODBC │
│ Bridge │
└──────┬───────┘

┌──────────────┐
│ ODBC Driver │
└──────┬───────┘

┌──────────────┐
│ Database │
└──────────────┘
Type 2: Native-API Driver

Java App → JDBC → Native Database Library → Database

Advantages:

Faster than Type 1


Better performance

Disadvantages:

Platform dependent
Native library required on client

Database specific

Diagram:

┌─────────────┐
│ Java App │
└──────┬──────┘

┌──────────────┐
│ JDBC Driver │
└──────┬───────┘

┌──────────────┐
│Native Library│
└──────┬───────┘

┌──────────────┐
│ Database │
└──────────────┘

Type 3: Network Protocol Driver

Java App → JDBC → Middleware Server → Database

Advantages:

Platform independent
No client-side library needed
Can access multiple databases

Good for internet applications

Disadvantages:

Requires middleware server


Slower due to network layers

Maintenance overhead

Diagram:

┌─────────────┐
│ Java App │
└──────┬──────┘

┌──────────────┐
│ JDBC Driver │
└──────┬───────┘
↓ (Network)
┌──────────────┐
│ Middleware │
│ Server │
└──────┬───────┘

┌──────────────┐
│ Database │
└──────────────┘

Type 4: Thin Driver (Pure Java)

Java App → JDBC → Database (Direct)

Advantages:

Pure Java (Platform independent)


Best performance

No additional libraries needed


Suitable for internet/intranet
Disadvantages:

Database specific

Different driver for each database

Diagram:

┌─────────────┐
│ Java App │
└──────┬──────┘

┌──────────────┐
│Pure Java │
│JDBC Driver │
└──────┬───────┘
↓ (Direct)
┌──────────────┐
│ Database │
└──────────────┘

Comparison Table:

Feature Type 1 Type 2 Type 3 Type 4

Platform Independent No No Yes Yes

Performance Slow Medium Medium Fast

Client Library Yes Yes No No

Best For Testing Limited use Internet Production


 

4. JPA Architecture
JPA (Java Persistence API):

Specification for ORM (Object Relational Mapping)


Maps Java objects to database tables
Simplifies database operations

Part of Java EE

JPA Architecture Diagram:


┌──────────────────────────────────┐
│ Java Application │
└────────────┬─────────────────────┘

┌──────────────────────────────────┐
│ JPA API │
│ (EntityManager, Query, etc.) │
└────────────┬─────────────────────┘

┌──────────────────────────────────┐
│ JPA Provider/Implementation │
│ (Hibernate, EclipseLink, etc.) │
└────────────┬─────────────────────┘

┌──────────────────────────────────┐
│ JDBC Driver │
└────────────┬─────────────────────┘

┌──────────────────────────────────┐
│ Database │
└──────────────────────────────────┘

JPA Components:

1. Entity:

Java class mapped to database table


Annotated with @Entity

java

@Entity
public class Student {
@Id
private int id;
private String name;
private int age;
}

2. EntityManager:

Interface to interact with persistence context


CRUD operations

java

EntityManager em = [Link]();
[Link](student); // Insert
[Link]([Link], 1); // Select
[Link](student); // Delete

3. Persistence Unit:

Configuration for database connection


Defined in [Link]

4. EntityManagerFactory:

Creates EntityManager instances


One per application

5. Query:

Execute JPQL queries

java

Query query = [Link]("SELECT s FROM Student s");


List<Student> students = [Link]();

JPA Annotations:

java

@Entity - Mark class as entity


@Table - Specify table name
@Id - Primary key
@GeneratedValue - Auto-generate primary key
@Column - Map to column
@OneToOne - One-to-one relationship
@OneToMany - One-to-many relationship
@ManyToOne - Many-to-one relationship
@ManyToMany - Many-to-many relationship

Example:
java

import [Link].*;

@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = [Link])
@Column(name = "student_id")
private int id;

@Column(name = "student_name", length = 50)


private String name;

@Column(name = "student_age")
private int age;

// Getters and Setters


}

// Using JPA
EntityManagerFactory emf = [Link]("myPU");
EntityManager em = [Link]();

// Insert
[Link]().begin();
Student s = new Student();
[Link]("John");
[Link](20);
[Link](s);
[Link]().commit();

// Find
Student found = [Link]([Link], 1);

Advantages:

Database independent
Reduces boilerplate code

Automatic table generation

Caching support
Lazy loading

5. Object-Relational Mapping (ORM)


Definition: ORM is a technique to map object-oriented programming objects to relational database tables.

Need for ORM:

1. Eliminates Boilerplate Code


No need to write SQL queries manually
Automatic CRUD operations

2. Database Independence
Switch databases without changing code
Same code works with MySQL, Oracle, etc.

3. Object-Oriented Approach
Work with objects instead of tables
Natural for Java developers

4. Productivity
Faster development

Less code maintenance

5. Type Safety
Compile-time checking
Reduces runtime errors

ORM Concept:

Java Object Model Relational Database


───────────────── ──────────────────
Student Student Table
├── id ├── id (PK)
├── name <─ORM─> ├── name
└── age └── age

Without ORM:

java
// Manual JDBC Code
String sql = "INSERT INTO Student VALUES(?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link]();

With ORM (JPA/Hibernate):

java

// Simple ORM Code


[Link](student);

ORM Mapping:

1. Class to Table:

java

@Entity
@Table(name = "students")
public class Student { }

2. Field to Column:

java

@Column(name = "student_name")
private String name;

3. Object to Row:

Student object {id=1, name="John", age=20}


↓ (ORM)
Table row: | 1 | John | 20 |

Popular ORM Frameworks:

1. Hibernate - Most popular


2. JPA - Standard specification
3. EclipseLink - Reference implementation
4. MyBatis - Lightweight

ORM Features:

1. Lazy Loading:

java

@OneToMany(fetch = [Link])
private List<Course> courses;

2. Caching:

First-level cache (Session)

Second-level cache (Application)

3. Relationship Mapping:

java

@OneToMany
@ManyToOne
@OneToOne
@ManyToMany

4. Query Language:

java

// JPQL (Java Persistence Query Language)


"SELECT s FROM Student s WHERE [Link] > 20"

Advantages:

Less code, more productivity

Database portability
Automatic schema generation

Transaction management

Caching

Disadvantages:
Learning curve
Performance overhead for complex queries

Less control over SQL

6. CRUD Operations
CRUD stands for: Create, Read, Update, Delete

Definition: Basic operations performed on database records.

1. CREATE (Insert)

Purpose: Add new records to database

SQL:

sql

INSERT INTO Student VALUES(1, 'John', 20);

JDBC:

java

String sql = "INSERT INTO Student VALUES(?, ?, ?)";


PreparedStatement ps = [Link](sql);
[Link](1, 1);
[Link](2, "John");
[Link](3, 20);
int rows = [Link]();
[Link](rows + " row inserted");

JPA:

java

Student s = new Student();


[Link](1);
[Link]("John");
[Link](20);
[Link](s);

2. READ (Select)
Purpose: Retrieve records from database

SQL:

sql

SELECT * FROM Student;


SELECT * FROM Student WHERE id = 1;

JDBC:

java

String sql = "SELECT * FROM Student";


Statement stmt = [Link]();
ResultSet rs = [Link](sql);
while([Link]()) {
[Link]([Link]("id") + " " +
[Link]("name") + " " +
[Link]("age"));
}

JPA:

java

// Find by ID
Student s = [Link]([Link], 1);

// Find all
Query query = [Link]("SELECT s FROM Student s");
List<Student> students = [Link]();

3. UPDATE (Modify)

Purpose: Modify existing records

SQL:

sql

UPDATE Student SET age = 21 WHERE id = 1;

JDBC:
java

String sql = "UPDATE Student SET age = ? WHERE id = ?";


PreparedStatement ps = [Link](sql);
[Link](1, 21);
[Link](2, 1);
int rows = [Link]();
[Link](rows + " row updated");

JPA:

java

Student s = [Link]([Link], 1);


[Link](21);
[Link](s);

4. DELETE (Remove)

Purpose: Remove records from database

SQL:

sql

DELETE FROM Student WHERE id = 1;

JDBC:

java

String sql = "DELETE FROM Student WHERE id = ?";


PreparedStatement ps = [Link](sql);
[Link](1, 1);
int rows = [Link]();
[Link](rows + " row deleted");

JPA:

java

Student s = [Link]([Link], 1);


[Link](s);
Complete CRUD Example:

java
import [Link].*;

class CRUDOperations {
static Connection con;

// Connect to database
static void connect() throws Exception {
[Link]("[Link]");
con = [Link](
"jdbc:mysql://localhost:3306/college", "root", "password"
);
}

// CREATE
static void insertStudent(int id, String name, int age) throws Exception {
String sql = "INSERT INTO Student VALUES(?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, id);
[Link](2, name);
[Link](3, age);
[Link]();
[Link]("Student inserted");
}

// READ
static void displayStudents() throws Exception {
String sql = "SELECT * FROM Student";
Statement stmt = [Link]();
ResultSet rs = [Link](sql);
[Link]("ID\tName\tAge");
while([Link]()) {
[Link]([Link](1) + "\t" +
[Link](2) + "\t" +
[Link](3));
}
}

// UPDATE
static void updateStudent(int id, int newAge) throws Exception {
String sql = "UPDATE Student SET age = ? WHERE id = ?";
PreparedStatement ps = [Link](sql);
[Link](1, newAge);
[Link](2, id);
[Link]();
[Link]("Student updated");
}

// DELETE
static void deleteStudent(int id) throws Exception {
String sql = "DELETE FROM Student WHERE id = ?";
PreparedStatement ps = [Link](sql);
[Link](1, id);
[Link]();
[Link]("Student deleted");
}

public static void main(String[] args) {


try {
connect();

// CREATE
insertStudent(1, "John", 20);
insertStudent(2, "Alice", 22);

// READ
displayStudents();

// UPDATE
updateStudent(1, 21);
displayStudents();

// DELETE
deleteStudent(2);
displayStudents();

[Link]();
} catch(Exception e) {
[Link](e);
}
}
}

CRUD in Web Applications:

Create: Registration form


Read: Display user list
Update: Edit profile
Delete: Remove account

Best Practices:

1. Use PreparedStatement (prevents SQL injection)

2. Close connections properly


3. Handle exceptions
4. Use transactions for multiple operations

5. Validate input data

EXAM TIPS:

How to Write Answers:


1. For Definition Questions:

Write definition first


Explain with diagram if needed
Give example

Write advantages/need

2. For Program Questions:

Write complete program with imports

Add comments for clarity

Show sample output


Explain logic if needed

3. For Diagram Questions:

Draw neat diagrams with arrows


Label all components

Write explanation below

4. For Comparison Questions:

Use table format

Minimum 5-6 points


Give examples for each

5. For Explain Questions:

Write in points or paragraphs


Give examples

Draw diagrams if helpful

Important Topics (High Weightage):


Unit 1:

Platform Independence

JVM, JRE, JDK

Data types and operators

Flow control programs

Unit 2:

Inheritance (all types)

Constructor
Interface vs Abstract class

Method Overriding (Polymorphism)


this and super keywords

Encapsulation

Unit 3:

Exception handling (try-catch-finally)

Exception hierarchy
Thread life cycle

Thread creation methods


Synchronization

Unit 4:

String methods
Array operations (matrix)

Collections (ArrayList, Vector, Stack)


List operations
Streams

Unit 5:

JDBC steps

JDBC drivers (all 4 types)


JPA Architecture
ORM concept

CRUD operations

Last Minute Checklist:


✓ Practice all diagrams (JVM, Exception hierarchy, Thread lifecycle, JPA)
✓ Remember syntax for class, interface, inheritance
✓ Know 4 types of JDBC drivers with advantages/disadvantages
✓ Practice 2-3 complete programs from each unit
✓ Remember important method names (String, Collections, Thread)
✓ Understand concepts: Polymorphism, Encapsulation, Exception, Synchronization

ALL THE BEST FOR YOUR EXAM! 🎯📚


Remember:

Write neat and clean

Underline important points


Draw diagrams wherever possible
Manage time properly

Attempt all questions# Programming in Java - Exam Preparation Guide

UNIT 1: Java Fundamentals

1. Java Buzzwords and Four Editions


Java Buzzwords:

1. Simple - Easy to learn, removed complex features like pointers


2. Object-Oriented - Everything is an object (except primitives)
3. Platform Independent - Write Once, Run Anywhere (WORA)
4. Secure - No explicit pointers, bytecode verification
5. Robust - Strong memory management, exception handling

6. Multithreaded - Built-in support for concurrent programming


7. Architecture Neutral - Bytecode works on any platform

8. Portable - No implementation-dependent features

Four Editions:

1. Java SE (Standard Edition) - Core Java, basic applications


Example: Desktop applications, console programs

2. Java EE (Enterprise Edition) - Large-scale enterprise applications


Example: Web applications, distributed systems

3. Java ME (Micro Edition) - Mobile and embedded devices


Example: Mobile apps, IoT devices

4. Java FX - Rich internet applications with GUI


Example: Desktop applications with modern UI

2. Platform Independence
Explanation: Java achieves platform independence through bytecode and JVM.

Diagram:

Java Source Code (.java)



Java Compiler (javac)

Bytecode (.class)

┌─────────────────────┐
│ JVM │
├─────────────────────┤
│ Windows | Linux | Mac│
└─────────────────────┘

Process:

1. Java code is compiled into bytecode (platform-independent)

2. JVM interprets bytecode for specific platform


3. Same bytecode runs on any OS with JVM

4. "Write Once, Run Anywhere" principle

3. JVM, JRE, and JDK


JVM (Java Virtual Machine):

Executes Java bytecode

Provides runtime environment


Platform-dependent implementation

JRE (Java Runtime Environment):

JVM + Library Classes + Supporting files


Required to run Java programs

JRE = JVM + Libraries

JDK (Java Development Kit):

JRE + Development Tools (compiler, debugger)

Required to develop Java programs


JDK = JRE + Development Tools

Relationship: JDK ⊃ JRE ⊃ JVM

4. Difference between C, C++, and Java


| Feature | C | C++ | Java |
|}

### 26. Java Reflection

**Definition:** Reflection is a feature that allows inspection and modification of classes, interfaces, fields, and methods at
runtime.

**Java Reflection Diagram:**


Java Reflection API

┌──────────────────┐
│ [Link] │
└──────────────────┘
↓ ↓ ↓
┌────┐ ┌────┐ ┌────┐
│Field│ │Method│ │Constructor│
└────┘ └────┘ └────┘
**Uses:**
1. Get class information at runtime
2. Inspect methods, fields, constructors
3. Invoke methods dynamically
4. Create objects dynamically
5. Used in frameworks (Spring, Hibernate)

**Example:**
```java
import [Link].*;

class Student {
private int id;
private String name;

public Student() { }

public Student(int id, String name) {


[Link] = id;
[Link] = name;
}

public void display() {


[Link]("ID: " + id + ", Name: " + name);
}
}

class ReflectionDemo {
public static void main(String[] args) {
try {
// Get class object
Class c = [Link]("Student");

// Get class name


[Link]("Class Name: " + [Link]());

// Get all methods


Method[] methods = [Link]();
[Link]("\nMethods:");
for(Method m : methods) {
[Link]([Link]());
}
// Get all fields
Field[] fields = [Link]();
[Link]("\nFields:");
for(Field f : fields) {
[Link]([Link]());
}

// Get constructors
Constructor[] constructors = [Link]();
[Link]("\nConstructors: " + [Link]);

// Create object using reflection


Object obj = [Link]();

} catch(Exception e) {
[Link](e);
}
}
}

27. Java Singleton Class


Definition: Singleton class allows only one instance of the class to be created throughout the application.

Need:

1. Control access to shared resources


2. Save memory (only one instance)

3. Global access point


4. Database connections, logging, caching

Implementation:

Method 1: Eager Initialization

java
class Singleton {
// Create instance at class loading
private static Singleton instance = new Singleton();

// Private constructor
private Singleton() { }

// Public method to get instance


public static Singleton getInstance() {
return instance;
}

public void showMessage() {


[Link]("Singleton Instance");
}
}

class Main {
public static void main(String[] args) {
// Get the only object available
Singleton obj1 = [Link]();
Singleton obj2 = [Link]();

[Link]();

// Both refer to same instance


[Link](obj1 == obj2); // true
}
}

Method 2: Lazy Initialization

java
class Singleton {
private static Singleton instance;

private Singleton() { }

public static Singleton getInstance() {


// Create instance only when needed
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}

Method 3: Thread-Safe Singleton

java

class Singleton {
private static Singleton instance;

private Singleton() { }

public static synchronized Singleton getInstance() {


if(instance == null) {
instance = new Singleton();
}
return instance;
}
}

Key Points:

Private constructor prevents external instantiation

Static method provides global access


Static variable holds the single instance

Used in: Logger, Database connection, Configuration

---------|---|-----|------|
| Type | Procedural | Object-Oriented | Pure OOP |
| Platform | Dependent | Dependent | Independent |
| Pointers | Yes | Yes | No |
| Memory | Manual | Manual | Automatic (GC) |
| Inheritance | No | Yes | Yes (no multiple) |
| Compilation | Machine code | Machine code | Bytecode |

Java Data Types:

1. Primitive Types:
byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

float (32-bit), double (64-bit)


char (16-bit), boolean (true/false)

2. Reference Types:
Classes, Interfaces, Arrays

5. Java Operators
1. Arithmetic: +, -, *, /, %

2. Relational: ==, !=, >, <, >=, <=


3. Logical: && (AND), || (OR), ! (NOT)

4. Assignment: =, +=, -=, *=, /=


5. Unary: ++, --, +, -

6. Bitwise: &, |, ^, ~, <<, >>


7. Ternary: condition ? value1 : value2

6. Area Calculation Program

java
import [Link];

class AreaCalculator {
void circle(double r) {
[Link]("Circle Area: " + (3.14 * r * r));
}

void square(double s) {
[Link]("Square Area: " + (s * s));
}

void rectangle(double l, double b) {


[Link]("Rectangle Area: " + (l * b));
}

void triangle(double b, double h) {


[Link]("Triangle Area: " + (0.5 * b * h));
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
AreaCalculator ac = new AreaCalculator();

[Link]("[Link] [Link] [Link] [Link]");


int ch = [Link]();

switch(ch) {
case 1:
[Link]("Enter radius: ");
[Link]([Link]());
break;
case 2:
[Link]("Enter side: ");
[Link]([Link]());
break;
case 3:
[Link]("Enter length and breadth: ");
[Link]([Link](), [Link]());
break;
case 4:
[Link]("Enter base and height: ");
[Link]([Link](), [Link]());
break;
default:
[Link]("Invalid choice");
}
}
}

7. Palindrome Check Program

java

import [Link];

class Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
int num = [Link]();
int original = num, rev = 0;

while(num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num = num / 10;
}

if(original == rev)
[Link](original + " is Palindrome");
else
[Link](original + " is not Palindrome");
}
}

9. Prime Number Check

java
import [Link];

class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
int n = [Link]();
boolean isPrime = true;

if(n <= 1) {
isPrime = false;
} else {
for(int i = 2; i <= n/2; i++) {
if(n % i == 0) {
isPrime = false;
break;
}
}
}

if(isPrime)
[Link](n + " is Prime");
else
[Link](n + " is not Prime");
}
}

10. Flow Control Statements


Three Types:

1. Selection Statements:
if, if-else, if-else-if, switch-case

Used for decision making

2. Iteration Statements:
for, while, do-while

Used for loops

3. Jump Statements:
break, continue, return
Used to transfer control
8. Types of Java Expressions
Definition: Expression is a combination of variables, operators, and method calls that evaluates to a single
value.

Types:

1. Arithmetic Expressions:

java

int a = 10, b = 5;
int sum = a + b; // 15
int product = a * b; // 50

2. Relational Expressions:

java

int x = 10, y = 20;


boolean result = x < y; // true
boolean equal = x == y; // false

3. Logical Expressions:

java

boolean a = true, b = false;


boolean and = a && b; // false
boolean or = a || b; // true
boolean not = !a; // false

4. Assignment Expressions:

java

int x = 10; // Simple assignment


x += 5; // x = x + 5 (Compound assignment)

5. Conditional/Ternary Expressions:

java
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20

6. Bitwise Expressions:

java

int a = 5, b = 3;
int and = a & b; // Bitwise AND
int or = a | b; // Bitwise OR
int xor = a ^ b; // Bitwise XOR

7. Increment/Decrement Expressions:

java

int x = 10;
int y = ++x; // Pre-increment: y=11, x=11
int z = x++; // Post-increment: z=11, x=12

12. Flow Control Programs


a) Leap Year:

java

if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))


[Link]("Leap Year");
else
[Link]("Not Leap Year");

b) Odd or Even:

java

if(num % 2 == 0)
[Link]("Even");
else
[Link]("Odd");

c) Fibonacci Series:

java
int a = 0, b = 1, c;
[Link](a + " " + b);
for(int i = 2; i < count; i++) {
c = a + b;
[Link](" " + c);
a = b;
b = c;
}

d) Factorial:

java

int fact = 1;
for(int i = 1; i <= n; i++)
fact *= i;
[Link]("Factorial: " + fact);

13. Square Root Without sqrt Method

java
import [Link];

class SquareRoot {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
double num = [Link]();

// Using Newton's Method (Babylonian Method)


double guess = num / 2;
double temp;

while(true) {
temp = (guess + num / guess) / 2;
if([Link](guess - temp) < 0.0001)
break;
guess = temp;
}

[Link]("Square root of " + num + " = " + guess);


}
}

Alternative Method:

java

double sqrt = 1;
for(int i = 0; i < 10; i++) {
sqrt = (sqrt + num / sqrt) / 2;
}
[Link]("Square root: " + sqrt);

UNIT 2: OOP Concepts

1. Multilevel Inheritance - Bank Details

java
import [Link];

class Account {
int accno;
String name;

void getAccountDetails() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Account No: ");
accno = [Link]();
[Link]("Enter Name: ");
name = [Link]();
}
}

class Person extends Account {


int age;
String gender;

void getPersonDetails() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Age: ");
age = [Link]();
[Link]("Enter Gender: ");
gender = [Link]();
}
}

class Bank extends Person {


String acctype;
double balance;

void getBalance() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Account Type: ");
acctype = [Link]();
[Link]("Enter Balance: ");
balance = [Link]();
}

void deposit(double amt) {


balance += amt;
[Link]("Deposited: " + amt);
}

void withdraw(double amt) {


if(balance >= amt) {
balance -= amt;
[Link]("Withdrawn: " + amt);
} else {
[Link]("Insufficient Balance");
}
}

void annualInterest() {
double interest = balance * 0.05;
balance += interest;
[Link]("Interest Added: " + interest);
}

void display() {
[Link]("\n--- Bank Details ---");
[Link]("Account No: " + accno);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Gender: " + gender);
[Link]("Account Type: " + acctype);
[Link]("Balance: " + balance);
}
}

2. Three Ways to Initialize Object


1. By Reference Variable:

java

Student s1 = new Student();


[Link] = 101;
[Link] = "John";

2. By Method:

java
class Student {
int id;
String name;

void setData(int i, String n) {


id = i;
name = n;
}
}
// Usage: [Link](101, "John");

3. By Constructor:

java

class Student {
int id;
String name;

Student(int i, String n) {
id = i;
name = n;
}
}
// Usage: Student s1 = new Student(101, "John");

3. Constructors
Definition: Special method to initialize objects, same name as class, no return type.

Types:

1. Default Constructor:

java

class Student {
Student() {
[Link]("Object created");
}
}

2. Parameterized Constructor:
java

class Student {
int id;
String name;

Student(int i, String n) {
id = i;
name = n;
}
}

3. Copy Constructor:

java

Student(Student s) {
id = [Link];
name = [Link];
}

Constructor vs Method:

Constructor Method

Same as class name Any name

No return type Has return type

Called automatically Called explicitly

Initialize object Perform operations


 

6. Fibonacci Using Recursion

java
class Fibonacci {
int fib(int n) {
if(n <= 1)
return n;
return fib(n-1) + fib(n-2);
}

public static void main(String[] args) {


Fibonacci f = new Fibonacci();
[Link]("Fibonacci Series: ");
for(int i = 0; i < 10; i++)
[Link]([Link](i) + " ");
}
}

7. Student Class with Multiple Objects

java
import [Link];

class Student {
String name;
int rollno, age, sub1, sub2;
String gender;

void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Roll No: ");
rollno = [Link]();
[Link]("Enter Age: ");
age = [Link]();
[Link]("Enter Gender: ");
gender = [Link]();
[Link]("Enter Marks (Sub1 Sub2): ");
sub1 = [Link]();
sub2 = [Link]();
}

void calculate() {
int total = sub1 + sub2;
double percentage = (total / 2.0);
String grade;

if(percentage >= 90) grade = "A+";


else if(percentage >= 80) grade = "A";
else if(percentage >= 70) grade = "B";
else if(percentage >= 60) grade = "C";
else grade = "Fail";

display(total, percentage, grade);


}

void display(int total, double per, String grade) {


[Link]("\n--- Student Details ---");
[Link]("Name: " + name);
[Link]("Roll No: " + rollno);
[Link]("Total: " + total);
[Link]("Percentage: " + per);
[Link]("Grade: " + grade);
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();

Student[] s = new Student[n];

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


s[i] = new Student();
[Link]("\nStudent " + (i+1));
s[i].input();
s[i].calculate();
}
}
}

8. Calculator Using Interface

java
interface Arithmetic {
void add(int a, int b);
void sub(int a, int b);
void mul(int a, int b);
void div(int a, int b);
void mod(int a, int b);
}

class Operation implements Arithmetic {


public void add(int a, int b) {
[Link]("Addition: " + (a + b));
}

public void sub(int a, int b) {


[Link]("Subtraction: " + (a - b));
}

public void mul(int a, int b) {


[Link]("Multiplication: " + (a * b));
}

public void div(int a, int b) {


if(b != 0)
[Link]("Division: " + (a / b));
else
[Link]("Cannot divide by zero");
}

public void mod(int a, int b) {


[Link]("Modulus: " + (a % b));
}
}

class Main {
public static void main(String[] args) {
Operation op = new Operation();
[Link](10, 5);
[Link](10, 5);
[Link](10, 5);
[Link](10, 5);
[Link](10, 5);
}
}

9. Employee Details Using Encapsulation

java
import [Link];

class Employee {
private int empId;
private String name;
private double salary, pf, hra, totalSalary;

public void setData() {


Scanner sc = new Scanner([Link]);
[Link]("Enter Employee ID: ");
empId = [Link]();
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Salary: ");
salary = [Link]();
}

public void calculate() {


pf = salary * 0.12; // 12% PF
hra = salary * 0.18; // 18% HRA
totalSalary = salary + hra - pf;
}

public void display() {


[Link]("\nEmployee ID: " + empId);
[Link]("Name: " + name);
[Link]("Basic Salary: " + salary);
[Link]("PF: " + pf);
[Link]("HRA: " + hra);
[Link]("Total Salary: " + totalSalary);
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of employees: ");
int n = [Link]();

Employee[] emp = new Employee[n];

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


emp[i] = new Employee();
[Link]("\nEmployee " + (i+1) + " Details:");
emp[i].setData();
emp[i].calculate();
emp[i].display();
}
}
}

10. Stack Operations Using Classes

java
import [Link];

class Stack {
int[] stack;
int top;
int size;

Stack(int s) {
size = s;
stack = new int[size];
top = -1;
}

void push(int value) {


if(top == size - 1) {
[Link]("Stack Overflow");
} else {
stack[++top] = value;
[Link](value + " pushed");
}
}

void pop() {
if(top == -1) {
[Link]("Stack Underflow");
} else {
[Link](stack[top--] + " popped");
}
}

void peek() {
if(top == -1) {
[Link]("Stack is empty");
} else {
[Link]("Top element: " + stack[top]);
}
}

void display() {
if(top == -1) {
[Link]("Stack is empty");
} else {
[Link]("Stack: ");
for(int i = 0; i <= top; i++) {
[Link](stack[i] + " ");
}
[Link]();
}
}
}

class Main {
public static void main(String[] args) {
Stack s = new Stack(10);
[Link](10);
[Link](20);
[Link](30);
[Link]();
[Link]();
[Link]();
[Link]();
}
}

11. Calculator Using Classes and Switch

java
import [Link];

class Calculator {
void add(double a, double b) {
[Link]("Addition: " + (a + b));
}

void subtract(double a, double b) {


[Link]("Subtraction: " + (a - b));
}

void multiply(double a, double b) {


[Link]("Multiplication: " + (a * b));
}

void divide(double a, double b) {


if(b != 0)
[Link]("Division: " + (a / b));
else
[Link]("Cannot divide by zero");
}

void modulus(double a, double b) {


[Link]("Modulus: " + (a % b));
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Calculator calc = new Calculator();

[Link]("Calculator Menu:");
[Link]("1. Addition");
[Link]("2. Subtraction");
[Link]("3. Multiplication");
[Link]("4. Division");
[Link]("5. Modulus");
[Link]("Enter choice: ");
int ch = [Link]();

[Link]("Enter two numbers: ");


double a = [Link]();
double b = [Link]();

switch(ch) {
case 1:
[Link](a, b);
break;
case 2:
[Link](a, b);
break;
case 3:
[Link](a, b);
break;
case 4:
[Link](a, b);
break;
case 5:
[Link](a, b);
break;
default:
[Link]("Invalid choice");
}
}
}

12. 'this' Keyword


Need: To refer to current object, resolve naming conflicts.

Uses:

1. Refer to instance variables


2. Invoke current class method

3. Pass current object as parameter


4. Invoke current class constructor

java
class Student {
int id;
String name;

Student(int id, String name) {


[Link] = id; // this refers to instance variable
[Link] = name;
}

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

13. 'final' Keyword


1. Final Variable: Becomes constant

java

final int MAX = 100;


// MAX = 200; // Error: cannot change

2. Final Method: Cannot be overridden

java

class Parent {
final void display() {
[Link]("Final method");
}
}

3. Final Class: Cannot be inherited

java

final class MyClass {


// class content
}
// class Sub extends MyClass { } // Error
14. Types of Inheritance
1. Single Inheritance:

A

B

java

class A { }
class B extends A { }

2. Multilevel Inheritance:

A

B

C

java

class A { }
class B extends A { }
class C extends B { }

3. Hierarchical Inheritance:

A
↙ ↘
B C

java

class A { }
class B extends A { }
class C extends A { }

4. Multiple Inheritance (Through Interface):


java

interface A { }
interface B { }
class C implements A, B { }

Note: Java doesn't support multiple inheritance through classes to avoid ambiguity.

15. Library Management Using Interface

java
import [Link];

interface LibraryOperations {
void getDetails();
void calculateFine();
void display();
}

class Library implements LibraryOperations {


String bookName, bookTitle, accType, issueDate, returnDate;
int days;
double balance, fine;

public void getDetails() {


Scanner sc = new Scanner([Link]);
[Link]("Enter Book Name: ");
bookName = [Link]();
[Link]("Enter Book Title: ");
bookTitle = [Link]();
[Link]("Enter Account Type: ");
accType = [Link]();
[Link]("Enter Issue Date: ");
issueDate = [Link]();
[Link]("Enter Return Date: ");
returnDate = [Link]();
[Link]("Enter Days Late: ");
days = [Link]();
[Link]("Enter Balance: ");
balance = [Link]();
}

public void calculateFine() {


if(days > 7) {
fine = (days - 7) * 5; // Rs. 5 per day after 7 days
balance -= fine;
} else {
fine = 0;
}
}

public void display() {


[Link]("\n--- Library Details ---");
[Link]("Book Name: " + bookName);
[Link]("Book Title: " + bookTitle);
[Link]("Account Type: " + accType);
[Link]("Issue Date: " + issueDate);
[Link]("Return Date: " + returnDate);
[Link]("Days Late: " + days);
[Link]("Fine Amount: " + fine);
[Link]("Balance: " + balance);
}
}

class Main {
public static void main(String[] args) {
Library lib = new Library();
[Link]();
[Link]();
[Link]();
}
}

Simple Interest Using Interface:

java
interface Interest {
void calculate();
}

class SimpleInterest implements Interest {


double principal, rate, time, si;

SimpleInterest(double p, double r, double t) {


principal = p;
rate = r;
time = t;
}

public void calculate() {


si = (principal * rate * time) / 100;
[Link]("Simple Interest: " + si);
[Link]("Total Amount: " + (principal + si));
}
}

class Main {
public static void main(String[] args) {
SimpleInterest s = new SimpleInterest(10000, 5, 2);
[Link]();
}
}

16. Arithmetic Operations Using Inheritance

java
class Calculator {
int a, b;

Calculator(int x, int y) {
a = x;
b = y;
}

void add() {
[Link]("Addition: " + (a + b));
}

void sub() {
[Link]("Subtraction: " + (a - b));
}
}

class AdvancedCalculator extends Calculator {


AdvancedCalculator(int x, int y) {
super(x, y);
}

void mul() {
[Link]("Multiplication: " + (a * b));
}

void div() {
if(b != 0)
[Link]("Division: " + (a / b));
else
[Link]("Cannot divide by zero");
}

void mod() {
[Link]("Modulus: " + (a % b));
}
}

class Main {
public static void main(String[] args) {
AdvancedCalculator calc = new AdvancedCalculator(20, 5);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Output:

Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4
Modulus: 0

17. Abstract and Nested Classes


Abstract Classes:

Definition: Class declared with 'abstract' keyword, cannot be instantiated, may contain abstract methods.

Features:

Can have abstract and non-abstract methods

Can have constructors and static methods


Can have final methods
Used to achieve abstraction

java
abstract class Shape {
abstract void draw(); // Abstract method

void display() { // Concrete method


[Link]("This is a shape");
}
}

class Circle extends Shape {


void draw() {
[Link]("Drawing Circle");
}
}

class Main {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
[Link]();
}
}

Nested Classes:

Definition: Class defined within another class.

Types:

1. Static Nested Class:

java
class Outer {
static int x = 10;

static class Inner {


void display() {
[Link]("x = " + x);
}
}
}

class Main {
public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}

2. Non-Static Nested Class (Inner Class):

java

class Outer {
int x = 10;

class Inner {
void display() {
[Link]("x = " + x);
}
}
}

class Main {
public static void main(String[] args) {
Outer out = new Outer();
[Link] in = [Link] Inner();
[Link]();
}
}

3. Local Inner Class:

java
class Outer {
void display() {
class Inner {
void show() {
[Link]("Local Inner Class");
}
}
Inner i = new Inner();
[Link]();
}
}

4. Anonymous Inner Class:

java

abstract class Animal {


abstract void sound();
}

class Main {
public static void main(String[] args) {
Animal a = new Animal() {
void sound() {
[Link]("Animal sound");
}
};
[Link]();
}
}

18. Arithmetic Operations Using Multi-level Inheritance

java
class Level1 {
int a, b;

Level1(int x, int y) {
a = x;
b = y;
}

void add() {
[Link]("Addition: " + (a + b));
}

void sub() {
[Link]("Subtraction: " + (a - b));
}
}

class Level2 extends Level1 {


Level2(int x, int y) {
super(x, y);
}

void mul() {
[Link]("Multiplication: " + (a * b));
}
}

class Level3 extends Level2 {


Level3(int x, int y) {
super(x, y);
}

void div() {
if(b != 0)
[Link]("Division: " + (a / b));
else
[Link]("Cannot divide by zero");
}

void mod() {
[Link]("Modulus: " + (a % b));
}
}
class Main {
public static void main(String[] args) {
Level3 obj = new Level3(20, 4);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Output:

Addition: 24
Subtraction: 16
Multiplication: 80
Division: 5
Modulus: 0

19. Stack Operations Using Interface

java
import [Link];

interface StackOperations {
void push(int value);
void pop();
void display();
}

class Stack implements StackOperations {


int[] stack;
int top;
int size;

Stack(int size) {
[Link] = size;
stack = new int[size];
top = -1;
}

public void push(int value) {


if(top == size - 1) {
[Link]("Stack Overflow");
} else {
stack[++top] = value;
[Link](value + " pushed to stack");
}
}

public void pop() {


if(top == -1) {
[Link]("Stack Underflow");
} else {
[Link](stack[top--] + " popped from stack");
}
}

public void display() {


if(top == -1) {
[Link]("Stack is empty");
} else {
[Link]("Stack elements: ");
for(int i = 0; i <= top; i++) {
[Link](stack[i] + " ");
}
[Link]();
}
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Stack s = new Stack(10);

[Link]("Enter 10 values:");
for(int i = 0; i < 10; i++) {
int value = [Link]();
[Link](value);
}

[Link]();

[Link]("\nPopping 2 elements:");
[Link]();
[Link]();

[Link]();
}
}

Sample Output:

Enter 10 values:
10 20 30 40 50 60 70 80 90 100
10 pushed to stack
20 pushed to stack
...
Stack elements: 10 20 30 40 50 60 70 80 90 100

Popping 2 elements:
100 popped from stack
90 popped from stack
Stack elements: 10 20 30 40 50 60 70 80
20. 'super' Keyword
Three Uses:

1. Access Parent Class Variable:

java

class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
[Link](super.x); // 10
[Link](x); // 20
}
}

2. Call Parent Class Method:

java

class Parent {
void display() {
[Link]("Parent");
}
}
class Child extends Parent {
void display() {
[Link](); // calls parent method
[Link]("Child");
}
}

3. Call Parent Class Constructor:

java
class Parent {
Parent() {
[Link]("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super(); // calls parent constructor
[Link]("Child Constructor");
}
}

22. Runtime Polymorphism


Concept: Method overriding with dynamic method dispatch. Method called is determined at runtime based on
object type.

java
class Shape {
void area() {
[Link]("Shape area");
}
}

class Rectangle extends Shape {


double l, b;

Rectangle(double l, double b) {
this.l = l;
this.b = b;
}

void area() {
[Link]("Rectangle Area: " + (l * b));
}
}

class Triangle extends Shape {


double b, h;

Triangle(double b, double h) {
this.b = b;
this.h = h;
}

void area() {
[Link]("Triangle Area: " + (0.5 * b * h));
}
}

class Main {
public static void main(String[] args) {
Shape s;
s = new Rectangle(5, 4);
[Link](); // Runtime polymorphism

s = new Triangle(6, 3);


[Link](); // Runtime polymorphism
}
}
}
### 23. Bank Interest Calculation Using Method Overriding
```java
class Bank {
double getRateOfInterest() {
return 0;
}
}

class SBI extends Bank {


double getRateOfInterest() {
return 7.5;
}
}

class ICICI extends Bank {


double getRateOfInterest() {
return 8.2;
}
}

class HDFC extends Bank {


double getRateOfInterest() {
return 8.5;
}
}

class Main {
public static void main(String[] args) {
double principal = 10000;
int time = 2;

Bank b;

b = new SBI();
double interest1 = (principal * [Link]() * time) / 100;
[Link]("SBI Interest: " + interest1);

b = new ICICI();
double interest2 = (principal * [Link]() * time) / 100;
[Link]("ICICI Interest: " + interest2);

b = new HDFC();
double interest3 = (principal * [Link]() * time) / 100;
[Link]("HDFC Interest: " + interest3);
}
}

Output:

SBI Interest: 1500.0


ICICI Interest: 1640.0
HDFC Interest: 1700.0

24. Abstract Class vs Interface


Abstract Class Interface

Can have abstract and non-abstract methods All methods abstract (before Java 8)

Can have instance variables Only constants (final static)

Use 'abstract' keyword Use 'interface' keyword

Single inheritance Multiple inheritance

Can have constructors Cannot have constructors

extends keyword implements keyword


 

25. Encapsulation - Employee Details

java
class Employee {
private int empId;
private String name;
private int age;
private double salary;
private String dept;

// Setters
public void setEmpId(int empId) {
[Link] = empId;
}

public void setName(String name) {


[Link] = name;
}

public void setAge(int age) {


[Link] = age;
}

public void setSalary(double salary) {


[Link] = salary;
}

public void setDept(String dept) {


[Link] = dept;
}

// Getters
public int getEmpId() {
return empId;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

public double getSalary() {


return salary;
}

public String getDept() {


return dept;
}

public void display() {


[Link]("ID: " + empId);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Salary: " + salary);
[Link]("Department: " + dept);
}
}

UNIT 3: Exception Handling & Multithreading

1. Need for Exception Handling


Definition: Exception is an abnormal event that disrupts normal program flow.

Need:

1. Separate error handling code from regular code

2. Prevent program crash

3. Maintain normal flow

4. Provide meaningful error messages

Example:

java

try {
int result = 10 / 0; // ArithmeticException
} catch(ArithmeticException e) {
[Link]("Cannot divide by zero");
}

2. Exception Hierarchy

Object

Throwable
↙ ↘
Error Exception
↙ ↘
IOException RuntimeException
↙ ↓ ↘
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException

Two Types:

1. Checked Exception - Checked at compile time (IOException)


2. Unchecked Exception - Checked at runtime (RuntimeException)

3. Exception Types and Keywords


Types:

1. Checked Exceptions: IOException, SQLException, ClassNotFoundException

2. Unchecked Exceptions: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException


3. Errors: OutOfMemoryError, StackOverflowError

Keywords:

1. try: Block of code to monitor for exceptions

2. catch: Handles the exception

3. finally: Always executes (cleanup code)


4. throw: Explicitly throw an exception

5. throws: Declares exceptions a method might throw

Example:

java
try {
int a = 10 / 0;
} catch(ArithmeticException e) {
[Link]("Error: " + e);
} finally {
[Link]("Finally block executed");
}

4. Common Exception Scenarios


1. ArithmeticException:

java

int result = 10 / 0; // Division by zero

2. NullPointerException:

java

String s = null;
[Link]([Link]()); // Null reference

3. ArrayIndexOutOfBoundsException:

java

int[] arr = new int[5];


[Link](arr[10]); // Invalid index

4. NumberFormatException:

java

String s = "abc";
int x = [Link](s); // Invalid number format

5. ClassCastException:

java
Object obj = new Integer(10);
String s = (String) obj; // Invalid cast

[Link]([Link]("lo")); // Output: true

### 5. Java Built-in Exceptions

**Common Built-in Exceptions:**

**1. ArithmeticException**
```java
int result = 10 / 0; // Division by zero

2. NullPointerException

java

String s = null;
int length = [Link](); // Calling method on null

3. ArrayIndexOutOfBoundsException

java

int[] arr = new int[5];


[Link](arr[10]); // Invalid index

4. StringIndexOutOfBoundsException

java

String s = "Hello";
char c = [Link](10); // Invalid index

5. NumberFormatException

java

String s = "abc";
int num = [Link](s); // Invalid format
6. ClassCastException

java

Object obj = new Integer(10);


String s = (String) obj; // Invalid cast

7. IllegalArgumentException

java

Thread t = new Thread();


[Link](100); // Invalid priority (valid: 1-10)

8. FileNotFoundException

java

FileReader file = new FileReader("[Link]"); // File not found

9. IOException

java

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


String s = [Link](); // IO operation

10. ClassNotFoundException

java

[Link]("MyClass"); // Class not found

Example Program:

java
class ExceptionDemo {
public static void main(String[] args) {
// ArithmeticException
try {
int a = 10 / 0;
} catch(ArithmeticException e) {
[Link]("ArithmeticException: " + [Link]());
}

// NullPointerException
try {
String s = null;
[Link]([Link]());
} catch(NullPointerException e) {
[Link]("NullPointerException: " + [Link]());
}

// ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
[Link](arr[5]);
} catch(ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: " + [Link]());
}

// NumberFormatException
try {
int num = [Link]("abc");
} catch(NumberFormatException e) {
[Link]("NumberFormatException: " + [Link]());
}
}
}

6. Need for Multithreading


Definition: Executing multiple threads simultaneously.

Advantages:

1. Better CPU utilization


2. Concurrent execution

3. Reduced idle time


4. Improved performance
5. Responsive applications

Example: Web browser - downloading, displaying, playing video simultaneously.

7. Thread Life Cycle

New

Runnable ←→ Running
↓ ↓
└─→ Blocked/Waiting

Dead

States:

1. New: Thread created but not started


2. Runnable: Ready to run, waiting for CPU

3. Running: Thread is executing

4. Blocked/Waiting: Thread is waiting for resource


5. Dead: Thread completed execution

Methods:

start() - Begin thread execution

run() - Contains code to execute

sleep(ms) - Pause thread

wait() - Wait until notified

notify() - Wake up waiting thread

join() - Wait for thread to complete

8. Thread Priorities and Synchronization


Thread Priorities:

Range: 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY)

Default: 5 (NORM_PRIORITY)

Higher priority threads get more CPU time


java

Thread t = new Thread();


[Link](Thread.MAX_PRIORITY);

Synchronization:

Prevents thread interference

Ensures data consistency

Only one thread accesses resource at a time

java

synchronized void display() {


// critical section
// only one thread at a time
}

9. Ways to Create Thread


Method 1: Extending Thread Class

java

class MyThread extends Thread {


public void run() {
for(int i = 1; i <= 5; i++) {
[Link](i);
}
}
}

class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}

Output: 1 2 3 4 5

Method 2: Implementing Runnable Interface


java

class MyRunnable implements Runnable {


public void run() {
for(int i = 1; i <= 5; i++) {
[Link](i);
}
}
}

class Main {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
[Link]();
}
}

Output: 1 2 3 4 5

UNIT 4: Strings, Arrays, Collections

1. String in Java
Need:

Represent text data


Immutable (cannot be changed)

Thread-safe

String pool for memory efficiency

Creating String:

Method 1: String Literal

java

String s1 = "Hello";

Method 2: new Keyword

java
String s2 = new String("Hello");

Difference: Literal uses string pool, new creates object in heap.

2. String Methods (10 Methods)

java

String s = "Hello World";

// 1. length() - Returns length


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

// 2. charAt(index) - Returns character at index


[Link]([Link](0)); // Output: H

// 3. substring(start, end) - Extracts substring


[Link]([Link](0, 5)); // Output: Hello

// 4. toLowerCase() - Converts to lowercase


[Link]([Link]()); // Output: hello world

// 5. toUpperCase() - Converts to uppercase


[Link]([Link]()); // Output: HELLO WORLD

// 6. trim() - Removes leading/trailing spaces


String s2 = " Hello ";
[Link]([Link]()); // Output: Hello

// 7. replace(old, new) - Replaces characters


[Link]([Link]('l', 'x')); // Output: Hexxo Worxd

// 8. startsWith(prefix) - Checks if starts with


[Link]([Link]("Hello")); // Output: true

// 9. endsWith(suffix) - Checks if ends with


[Link]([Link]("World")); // Output: true

// 10. contains(sequence) - Checks if contains


[Link]([Link]("lo")); // Output: true
3. Types of Arrays
1. Single Dimensional Array:

java

int[] arr = new int[5];


arr[0] = 10;
arr[1] = 20;

// or
int[] arr = {10, 20, 30, 40, 50};

2. Two Dimensional Array:

java

int[][] arr = new int[3][3];


arr[0][0] = 1;

// or
int[][] arr = {{1,2,3}, {4,5,6}, {7,8,9}};

3. Jagged Array:

java

int[][] arr = new int[3][];


arr[0] = new int[2];
arr[1] = new int[3];
arr[2] = new int[4];

4. Matrix Addition and Multiplication

java
class Matrix {
public static void main(String[] args) {
int[][] a = {{1,2,3}, {4,5,6}, {7,8,9}};
int[][] b = {{9,8,7}, {6,5,4}, {3,2,1}};
int[][] sum = new int[3][3];
int[][] mul = new int[3][3];

// Addition
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}

// Multiplication
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
mul[i][j] = 0;
for(int k = 0; k < 3; k++) {
mul[i][j] += a[i][k] * b[k][j];

You might also like