Matrix Operations and Collections Guide
Matrix Operations and Collections Guide
// 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
Collection (Interface)
↓
┌───────┼───────┐
↓ ↓ ↓
Map (Interface)
↓
┌───┼───┐
HashMap TreeMap LinkedHashMap
**Key Interfaces:**
java
// 1. add(int index, E element) - Add at index
[Link](0, "First");
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:
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);
// Remove element
[Link](2);
[Link]("After removal: " + v);
// Capacity
[Link]("Capacity: " + [Link]());
[Link]("Size: " + [Link]());
}
}
Output:
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");
// Check if empty
[Link]("Is empty: " + [Link]());
Output:
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");
// 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"));
// Clear all
[Link]();
[Link]("\nAfter clearing: " + letters);
[Link]("Size: " + [Link]());
[Link]("Is empty: " + [Link]());
}
}
Sample Output:
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:
8-bit bytes
2. Character Streams:
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");
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");
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:
2. Automatic buffering
3. Support for different data types
4. Error handling
4. Concurrent access
5. Data consistency
Database independent
JDBC Layout/Architecture:
Java Application
↓
JDBC API
↓
JDBC Driver Manager
↓
JDBC Driver
↓
Database
Components:
Advantages:
Performance optimization
Transaction management
java
import [Link].*;
java
[Link]("[Link]");
java
java
Statement stmt = [Link]();
java
java
while([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
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");
} 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
java
java
java
Advantages:
Easy to use
Can connect to any database with ODBC driver
No need for database-specific driver
Disadvantages:
Diagram:
┌─────────────┐
│ Java App │
└──────┬──────┘
↓
┌──────────────┐
│ JDBC-ODBC │
│ Bridge │
└──────┬───────┘
↓
┌──────────────┐
│ ODBC Driver │
└──────┬───────┘
↓
┌──────────────┐
│ Database │
└──────────────┘
Type 2: Native-API Driver
Advantages:
Disadvantages:
Platform dependent
Native library required on client
Database specific
Diagram:
┌─────────────┐
│ Java App │
└──────┬──────┘
↓
┌──────────────┐
│ JDBC Driver │
└──────┬───────┘
↓
┌──────────────┐
│Native Library│
└──────┬───────┘
↓
┌──────────────┐
│ Database │
└──────────────┘
Advantages:
Platform independent
No client-side library needed
Can access multiple databases
Disadvantages:
Maintenance overhead
Diagram:
┌─────────────┐
│ Java App │
└──────┬──────┘
↓
┌──────────────┐
│ JDBC Driver │
└──────┬───────┘
↓ (Network)
┌──────────────┐
│ Middleware │
│ Server │
└──────┬───────┘
↓
┌──────────────┐
│ Database │
└──────────────┘
Advantages:
Database specific
Diagram:
┌─────────────┐
│ Java App │
└──────┬──────┘
↓
┌──────────────┐
│Pure Java │
│JDBC Driver │
└──────┬───────┘
↓ (Direct)
┌──────────────┐
│ Database │
└──────────────┘
Comparison Table:
4. JPA Architecture
JPA (Java Persistence API):
Part of Java EE
JPA Components:
1. Entity:
java
@Entity
public class Student {
@Id
private int id;
private String name;
private int age;
}
2. EntityManager:
java
EntityManager em = [Link]();
[Link](student); // Insert
[Link]([Link], 1); // Select
[Link](student); // Delete
3. Persistence Unit:
4. EntityManagerFactory:
5. Query:
java
JPA Annotations:
java
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_age")
private int age;
// 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
Caching support
Lazy loading
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
5. Type Safety
Compile-time checking
Reduces runtime errors
ORM Concept:
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]();
java
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:
ORM Features:
1. Lazy Loading:
java
@OneToMany(fetch = [Link])
private List<Course> courses;
2. Caching:
3. Relationship Mapping:
java
@OneToMany
@ManyToOne
@OneToOne
@ManyToMany
4. Query Language:
java
Advantages:
Database portability
Automatic schema generation
Transaction management
Caching
Disadvantages:
Learning curve
Performance overhead for complex queries
6. CRUD Operations
CRUD stands for: Create, Read, Update, Delete
1. CREATE (Insert)
SQL:
sql
JDBC:
java
JPA:
java
2. READ (Select)
Purpose: Retrieve records from database
SQL:
sql
JDBC:
java
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)
SQL:
sql
JDBC:
java
JPA:
java
4. DELETE (Remove)
SQL:
sql
JDBC:
java
JPA:
java
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");
}
// 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);
}
}
}
Best Practices:
EXAM TIPS:
Write advantages/need
Platform Independence
Unit 2:
Constructor
Interface vs Abstract class
Encapsulation
Unit 3:
Exception hierarchy
Thread life cycle
Unit 4:
String methods
Array operations (matrix)
Unit 5:
JDBC steps
CRUD operations
Four Editions:
2. Platform Independence
Explanation: Java achieves platform independence through bytecode and JVM.
Diagram:
Process:
**Definition:** Reflection is a feature that allows inspection and modification of classes, interfaces, fields, and methods at
runtime.
**Example:**
```java
import [Link].*;
class Student {
private int id;
private String name;
public Student() { }
class ReflectionDemo {
public static void main(String[] args) {
try {
// Get class object
Class c = [Link]("Student");
// Get constructors
Constructor[] constructors = [Link]();
[Link]("\nConstructors: " + [Link]);
} catch(Exception e) {
[Link](e);
}
}
}
Need:
Implementation:
java
class Singleton {
// Create instance at class loading
private static Singleton instance = new Singleton();
// Private constructor
private Singleton() { }
class Main {
public static void main(String[] args) {
// Get the only object available
Singleton obj1 = [Link]();
Singleton obj2 = [Link]();
[Link]();
java
class Singleton {
private static Singleton instance;
private Singleton() { }
java
class Singleton {
private static Singleton instance;
private Singleton() { }
Key Points:
---------|---|-----|------|
| 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 |
1. Primitive Types:
byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
2. Reference Types:
Classes, Interfaces, Arrays
5. Java Operators
1. Arithmetic: +, -, *, /, %
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));
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
AreaCalculator ac = new AreaCalculator();
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");
}
}
}
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");
}
}
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");
}
}
1. Selection Statements:
if, if-else, if-else-if, switch-case
2. Iteration Statements:
for, while, do-while
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
3. Logical Expressions:
java
4. Assignment Expressions:
java
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
java
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);
java
import [Link];
class SquareRoot {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
double num = [Link]();
while(true) {
temp = (guess + num / guess) / 2;
if([Link](guess - temp) < 0.0001)
break;
guess = temp;
}
Alternative Method:
java
double sqrt = 1;
for(int i = 0; i < 10; i++) {
sqrt = (sqrt + num / sqrt) / 2;
}
[Link]("Square root: " + sqrt);
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]();
}
}
void getPersonDetails() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Age: ");
age = [Link]();
[Link]("Enter Gender: ");
gender = [Link]();
}
}
void getBalance() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Account Type: ");
acctype = [Link]();
[Link]("Enter Balance: ");
balance = [Link]();
}
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);
}
}
java
2. By Method:
java
class Student {
int id;
String name;
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
java
class Fibonacci {
int fib(int n) {
if(n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
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;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();
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 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);
}
}
java
import [Link];
class Employee {
private int empId;
private String name;
private double salary, pf, hra, totalSalary;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of employees: ");
int n = [Link]();
java
import [Link];
class Stack {
int[] stack;
int top;
int size;
Stack(int s) {
size = s;
stack = new int[size];
top = -1;
}
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]();
}
}
java
import [Link];
class Calculator {
void add(double a, double b) {
[Link]("Addition: " + (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]();
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");
}
}
}
Uses:
java
class Student {
int id;
String name;
void display() {
[Link]([Link] + " " + [Link]);
}
}
java
java
class Parent {
final void display() {
[Link]("Final method");
}
}
java
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 { }
interface A { }
interface B { }
class C implements A, B { }
Note: Java doesn't support multiple inheritance through classes to avoid ambiguity.
java
import [Link];
interface LibraryOperations {
void getDetails();
void calculateFine();
void display();
}
class Main {
public static void main(String[] args) {
Library lib = new Library();
[Link]();
[Link]();
[Link]();
}
}
java
interface Interest {
void calculate();
}
class Main {
public static void main(String[] args) {
SimpleInterest s = new SimpleInterest(10000, 5, 2);
[Link]();
}
}
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));
}
}
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
Definition: Class declared with 'abstract' keyword, cannot be instantiated, may contain abstract methods.
Features:
java
abstract class Shape {
abstract void draw(); // Abstract method
class Main {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
[Link]();
}
}
Nested Classes:
Types:
java
class Outer {
static int x = 10;
class Main {
public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}
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]();
}
}
java
class Outer {
void display() {
class Inner {
void show() {
[Link]("Local Inner Class");
}
}
Inner i = new Inner();
[Link]();
}
}
java
class Main {
public static void main(String[] args) {
Animal a = new Animal() {
void sound() {
[Link]("Animal sound");
}
};
[Link]();
}
}
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));
}
}
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) {
Level3 obj = new Level3(20, 4);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Addition: 24
Subtraction: 16
Multiplication: 80
Division: 5
Modulus: 0
java
import [Link];
interface StackOperations {
void push(int value);
void pop();
void display();
}
Stack(int size) {
[Link] = size;
stack = new int[size];
top = -1;
}
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:
java
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
[Link](super.x); // 10
[Link](x); // 20
}
}
java
class Parent {
void display() {
[Link]("Parent");
}
}
class Child extends Parent {
void display() {
[Link](); // calls parent method
[Link]("Child");
}
}
java
class Parent {
Parent() {
[Link]("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super(); // calls parent constructor
[Link]("Child Constructor");
}
}
java
class Shape {
void area() {
[Link]("Shape area");
}
}
Rectangle(double l, double b) {
this.l = l;
this.b = b;
}
void area() {
[Link]("Rectangle Area: " + (l * b));
}
}
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
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:
Can have abstract and non-abstract methods All methods abstract (before Java 8)
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;
}
// Getters
public int getEmpId() {
return empId;
}
Need:
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:
Keywords:
Example:
java
try {
int a = 10 / 0;
} catch(ArithmeticException e) {
[Link]("Error: " + e);
} finally {
[Link]("Finally block executed");
}
java
2. NullPointerException:
java
String s = null;
[Link]([Link]()); // Null reference
3. ArrayIndexOutOfBoundsException:
java
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
**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
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
7. IllegalArgumentException
java
8. FileNotFoundException
java
9. IOException
java
10. ClassNotFoundException
java
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]());
}
}
}
Advantages:
New
↓
Runnable ←→ Running
↓ ↓
└─→ Blocked/Waiting
↓
Dead
States:
Methods:
Default: 5 (NORM_PRIORITY)
Synchronization:
java
java
class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}
Output: 1 2 3 4 5
class Main {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
[Link]();
}
}
Output: 1 2 3 4 5
1. String in Java
Need:
Thread-safe
Creating String:
java
String s1 = "Hello";
java
String s2 = new String("Hello");
java
java
// or
int[] arr = {10, 20, 30, 40, 50};
java
// or
int[][] arr = {{1,2,3}, {4,5,6}, {7,8,9}};
3. Jagged Array:
java
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];