Java Complete Notes
Java Complete Notes
ment Preparation
Table of Contents
1. Getting Started With Core Java
2. Java Essentials
3. Java Power Moves (Operators)
4. Mastering Java Flow (Control Statements)
5. Array Adventures
6. Object Oriented Programming (OOP)
7. OOP: Inheritance & Polymorphism
8. String Secrets
9. Exception Handling
10. JDBC (Java Database Connectivity)
11. Collection Framework
12. Major Java 8 Features
13. Multithreading
Java vs C++
1
• Provides platform independence
• Components:
– Class Loader: Loads .class files into memory
– Memory Areas: Heap, Stack, Method Area
– Execution Engine: Interpreter + JIT Compiler
• Performs memory management and garbage collection
2
Method belongs to class, not instance - void: No return value - main: Entry
point of program - String[] args: Command-line arguments
2. Java Essentials
Data Types in Java
Primitive Data Types (8 types)
Variables
Variables are containers for storing data values.
Syntax:
dataType variableName = value;
Variable Naming Rules: - Must start with letter, underscore (_), or dollar
sign ($) - Cannot start with digit - Cannot use Java keywords - Case-sensitive -
Use camelCase convention
Types of Variables: 1. Local Variables: Declared inside method/block
2. Instance Variables: Declared in class but outside methods 3. Static
Variables: Declared with static keyword
Examples:
int age = 25; // Integer variable
double salary = 45000.50; // Double variable
char grade = 'A'; // Character variable
3
boolean isActive = true; // Boolean variable
String name = "John"; // String variable
Literals
Literals are fixed values directly written in code.
4
2. Relational/Comparison Operators
int x = 5, y = 10;
boolean result1 = (x == y); // Equal to: false
boolean result2 = (x != y); // Not equal to: true
boolean result3 = (x > y); // Greater than: false
boolean result4 = (x < y); // Less than: true
boolean result5 = (x >= y); // Greater than or equal: false
boolean result6 = (x <= y); // Less than or equal: true
3. Logical Operators
boolean a = true, b = false;
boolean and = a && b; // Logical AND: false
boolean or = a || b; // Logical OR: true
boolean not = !a; // Logical NOT: false
4. Assignment Operators
int x = 10;
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
5. Unary Operators
int a = 10;
a++; // Post-increment: a = 11
++a; // Pre-increment: a = 12
a--; // Post-decrement: a = 11
--a; // Pre-decrement: a = 10
int b = -a; // Unary minus: b = -10
6. Bitwise Operators
int a = 5, b = 3; // Binary: a=0101, b=0011
int and = a & b; // Bitwise AND: 0001 = 1
int or = a | b; // Bitwise OR: 0111 = 7
int xor = a ^ b; // Bitwise XOR: 0110 = 6
int complement = ~a; // Bitwise Complement: -6
int leftShift = a << 1; // Left shift: 1010 = 10
int rightShift = a >> 1; // Right shift: 0010 = 2
7. Ternary Operator
5
condition ? value_if_true : value_if_false
// Example
int age = 20;
if (age >= 18) {
[Link]("You are an adult");
}
2. if-else Statement
if (condition) {
// code if true
} else {
// code if false
}
6
// Example
int number = 15;
if (number % 2 == 0) {
[Link]("Even number");
} else {
[Link]("Odd number");
}
3. if-else-if Ladder
if (condition1) {
// code
} else if (condition2) {
// code
} else if (condition3) {
// code
} else {
// default code
}
// Example
int marks = 75;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 60) {
[Link]("Grade C");
} else {
[Link]("Grade D");
}
4. Nested if Statement
if (condition1) {
if (condition2) {
// code
}
}
// Example
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
7
[Link]("You can drive");
}
}
5. switch Statement
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
// Example
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
}
When to Use: - if-else: For range conditions and complex logic - switch:
For exact value matching (cleaner for multiple cases)
Looping Statements
1. for Loop
for (initialization; condition; increment/decrement) {
// code to repeat
}
// Example
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
8
}
2. while Loop
while (condition) {
// code to repeat
}
// Example
int i = 1;
while (i <= 5) {
[Link]("Count: " + i);
i++;
}
3. do-while Loop
do {
// code (executes at least once)
} while (condition);
// Example
int i = 1;
do {
[Link]("Count: " + i);
i++;
} while (i <= 5);
// Example
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
[Link](num);
}
9
break; // Loop terminates at i=5
}
[Link](i);
}
continue Statement
// Skip current iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip i=3
}
[Link](i); // Prints: 1, 2, 4, 5
}
5. Array Adventures
What is an Array?
• Array is a collection of similar data types stored in contiguous memory
locations
• Fixed size (cannot be changed after creation)
• Index starts from 0
• Can store primitive types or objects
10
int[] numbers;
numbers = new int[]{10, 20, 30, 40, 50};
Accessing Elements:
int[] arr = {10, 20, 30, 40, 50};
[Link](arr[0]); // 10
[Link](arr[2]); // 30
[Link]([Link]); // 5
Traversing Arrays:
int[] numbers = {1, 2, 3, 4, 5};
// Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
[Link](matrix[0][0]); // 1
[Link](matrix[1][2]); // 6
// Traversing 2D array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
11
Three-Dimensional Array:
int[][][] arr3D = new int[2][3][4];
// Initialization
int[][][] data = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
Jagged Array (Arrays with different column sizes):
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[3];
Array Operations
1. Finding Maximum/Minimum
int[] arr = {5, 2, 9, 1, 7};
int max = arr[0];
int min = arr[0];
2. Array Reversal
int[] arr = {1, 2, 3, 4, 5};
int start = 0;
int end = [Link] - 1;
3. Array Sorting
import [Link];
12
int[] arr = {5, 2, 9, 1, 7};
[Link](arr); // Sorts in ascending order
4. Copying Arrays
int[] original = {1, 2, 3, 4, 5};
// Constructor
ClassName(parameters) {
// initialization
}
// Methods (behaviors)
returnType methodName() {
13
// code
}
}
Object
• Instance of a class
• Actual entity that occupies memory
Creating Objects:
ClassName objectName = new ClassName();
Example:
class Student {
String name;
int rollNo;
// Constructor
Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}
// Method
void display() {
[Link]("Name: " + name);
[Link]("Roll No: " + rollNo);
}
}
Methods in Java
Types of Methods 1. Instance Methods
class Calculator {
int add(int a, int b) {
return a + b;
}
}
14
Calculator calc = new Calculator();
int result = [Link](5, 3); // 8
2. Static Methods
class MathUtils {
static int multiply(int a, int b) {
return a * b;
}
}
Constructors
Types of Constructors 1. Default Constructor
class Student {
String name;
15
int age;
Encapsulation
Definition: Wrapping data (variables) and methods into a single unit (class)
and hiding internal details.
Implementation: 1. Declare variables as private 2. Provide public getter
and setter methods
Example:
class BankAccount {
private double balance; // Private variable
// Getter method
public double getBalance() {
return balance;
}
// Setter method
public void setBalance(double amount) {
if (amount >= 0) {
[Link] = amount;
}
}
16
}
Access Modifiers
Student(String name) {
[Link] = name; // [Link] = instance variable
}
}
17
}
}
2. Multilevel Inheritance
class Animal {
void eat() { }
}
interface Showable {
void show();
}
18
super Keyword
• Refers to parent class
• Used to call parent class constructor or methods
class Parent {
int x = 10;
Parent() {
[Link]("Parent constructor");
}
}
Child() {
super(); // Call parent constructor
[Link]("Child constructor");
}
void display() {
[Link](super.x); // Access parent variable
[Link](this.x);
}
}
Abstract Classes
Definition: Class that cannot be instantiated and may contain abstract meth-
ods.
Rules: - Cannot create object of abstract class - Can have abstract and non-
abstract methods - Must be extended by subclass
abstract class Animal {
abstract void sound(); // Abstract method (no body)
19
// Usage
Dog d = new Dog();
[Link](); // Bark
[Link](); // Sleeping...
Interfaces
Definition: Blueprint of a class containing only abstract methods and con-
stants.
Rules: - All methods are implicitly public and abstract - All variables are
implicitly public, static, and final - A class can implement multiple interfaces
interface Drawable {
void draw(); // public abstract by default
}
interface Printable {
void print();
}
Polymorphism
Definition: Ability of an object to take many forms.
20
Types of Polymorphism 1. Compile-Time Polymorphism (Method
Overloading) - Same method name, different parameters - Resolved at compile
time
class Calculator {
int add(int a, int b) {
return a + b;
}
// Usage
Animal a;
a = new Dog();
[Link](); // Dog barks (runtime polymorphism)
a = new Cat();
21
[Link](); // Cat meows
final Keyword
Uses: 1. final variable: Cannot be changed (constant) 2. final method:
Cannot be overridden 3. final class: Cannot be inherited
final class Math {
final double PI = 3.14159;
8. String Secrets
String Class
String Creation 1. Using String Literal
String s1 = "Hello";
String s2 = "Hello";
// Both point to same object in String Pool
2. Using new Keyword
String s1 = new String("Hello");
String s2 = new String("Hello");
// Creates separate objects in heap
22
String Immutability
Why Strings are Immutable? 1. Security: Sensitive data (passwords,
URLs) cannot be changed 2. Thread Safety: Safe to share across threads 3.
Caching: String pool optimization 4. Performance: Hash code caching
Example:
String s1 = "Hello";
[Link](" World"); // Creates new string, doesn't modify s1
[Link](s1); // Output: Hello (unchanged)
String Pool
• Special memory region in heap
• Stores string literals
• Prevents duplicate strings
String s1 = "Hello";
String s2 = "Hello";
[Link](s1 == s2); // true (same reference)
String Methods
String s = "Hello World";
// Length
[Link]() // 11
// Character at index
[Link](0) // 'H'
// Substring
[Link](0, 5) // "Hello"
[Link](6) // "World"
// Concatenation
[Link]("!") // "Hello World!"
s + "!" // "Hello World!"
// Case conversion
23
[Link]() // "hello world"
[Link]() // "HELLO WORLD"
// Comparison
[Link]("Hello World") // true
[Link]("hello world") // true
[Link]("Hello") // positive (lexicographically)
// Search
[Link]("World") // true
[Link]("Hello") // true
[Link]("World") // true
[Link]("World") // 6
[Link]("l") // 9
// Replacement
[Link]('l', 'L') // "HeLLo WorLd"
[Link]("l", "L") // "HeLLo WorLd"
// Trim
" Hello ".trim() // "Hello"
// Split
[Link](" ") // ["Hello", "World"]
// Check empty
[Link]() // false
// Character array
[Link]() // ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
StringBuffer
Characteristics: - Mutable (can be modified) - Thread-safe (synchronized) -
Slower than StringBuilder - Methods are synchronized
StringBuffer sb = new StringBuffer("Hello");
// Append
[Link](" World"); // "Hello World"
// Insert
[Link](5, ","); // "Hello, World"
// Replace
[Link](7, 12, "Java"); // "Hello, Java"
24
// Delete
[Link](5, 6); // "HelloJava"
// Reverse
[Link](); // "avaJolleH"
// Capacity
[Link]() // Default: 16 + string length
// Length
[Link]()
StringBuilder
Characteristics: - Mutable (can be modified) - NOT thread-safe (not synchro-
nized) - Faster than StringBuffer - Preferred for single-threaded applications
StringBuilder sb = new StringBuilder("Hello");
Performance Comparison:
// String (Slow - creates many objects)
String s = "";
for (int i = 0; i < 1000; i++) {
s += i; // Creates new object each time
}
25
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
[Link](i); // Modifies same object
}
9. Exception Handling
What is an Exception?
• Unwanted event that disrupts normal program flow
• Object that represents an error
Exception Hierarchy
Object
��� Throwable
��� Error (Unchecked)
� ��� OutOfMemoryError
� ��� StackOverflowError
��� Exception
��� Checked Exceptions
� ��� IOException
� ��� SQLException
� ��� ClassNotFoundException
��� Unchecked Exceptions (RuntimeException)
��� ArithmeticException
��� NullPointerException
��� ArrayIndexOutOfBoundsException
��� NumberFormatException
Types of Exceptions
1. Checked Exceptions
• Checked at compile-time
• Must be handled or declared
• Examples: IOException, SQLException
26
• Checked at runtime
• Not mandatory to handle
• Examples: ArithmeticException, NullPointerException
3. Errors
• Serious problems that cannot be handled
• Examples: OutOfMemoryError, StackOverflowError
2. catch Block
• Handles specific exception
• Can have multiple catch blocks
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
4. finally Block
• Always executes (whether exception occurs or not)
• Used for cleanup code (closing resources)
27
try {
int result = 10 / 2;
} catch (Exception e) {
[Link]("Error");
} finally {
[Link]("Always executes");
}
5. throw Keyword
• Used to explicitly throw an exception
void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible");
}
}
6. throws Keyword
• Declares that a method may throw exceptions
• Used in method signature
void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
}
try-catch-finally Example
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Finally block executed");
}
}
}
// Output:
// Error: / by zero
// Finally block executed
28
Custom Exceptions
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
class TestCustomException {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age not valid");
}
}
JDBC Architecture
Components: 1. JDBC API: Application-to-JDBC Manager connection 2.
JDBC Driver API: JDBC Manager-to-Driver connection 3. Driver Man-
ager: Manages list of database drivers 4. Driver: Handles communications
with database
29
JDBC Drivers (Types)
Type 1: JDBC-ODBC Bridge Driver
• Uses ODBC driver to connect
• Not recommended (deprecated in Java 8)
JDBC Steps
1. Load Driver
[Link]("[Link]");
2. Create Connection
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "root";
String password = "password";
3. Create Statement
Statement stmt = [Link]();
4. Execute Query
// For SELECT (returns ResultSet)
ResultSet rs = [Link]("SELECT * FROM students");
30
5. Process Results
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link](id + " " + name);
}
6. Close Connection
[Link]();
[Link]();
[Link]();
// 2. Create Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);
// 3. Create Statement
Statement stmt = [Link]();
// 4. Execute Query
ResultSet rs = [Link]("SELECT * FROM students");
// 5. Process Results
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
// 6. Close Connection
[Link]();
[Link]();
[Link]();
31
} catch (Exception e) {
[Link](e);
}
}
}
PreparedStatement Example
String sql = "INSERT INTO students VALUES (?, ?)";
PreparedStatement pstmt = [Link](sql);
[Link](1, 101);
[Link](2, "John");
int rows = [Link]();
Read (SELECT)
String sql = "SELECT * FROM students";
Statement stmt = [Link]();
ResultSet rs = [Link](sql);
while ([Link]()) {
32
[Link]([Link]("id") + " " + [Link]("name"));
}
Update
String sql = "UPDATE students SET name = ? WHERE id = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, "Updated Name");
[Link](2, 1);
[Link]();
Delete
String sql = "DELETE FROM students WHERE id = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, 1);
[Link]();
Collection Hierarchy
Collection (Interface)
��� List (Interface)
� ��� ArrayList
� ��� LinkedList
� ��� Vector
� ��� Stack
��� Set (Interface)
� ��� HashSet
� ��� LinkedHashSet
33
� ��� TreeSet
��� Queue (Interface)
��� PriorityQueue
��� ArrayDeque
Generics
Definition: Allow type parameterization for type safety.
Syntax:
ClassName<Type> objectName = new ClassName<Type>();
Example:
// Without generics (not type-safe)
ArrayList list = new ArrayList();
[Link]("String");
[Link](10); // Allowed but risky
T get() {
return value;
}
}
34
Box<String> strBox = new Box<>();
[Link]("Hello");
List Interface
Characteristics: - Ordered collection (maintains insertion order) - Allows du-
plicates - Index-based access
1. ArrayList
import [Link];
// Add elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
// Get element
String fruit = [Link](0); // "Apple"
// Update element
[Link](1, "Blueberry");
// Remove element
[Link](2);
[Link]("Apple");
// Size
int size = [Link]();
// Iterate
for (String f : list) {
[Link](f);
}
2. LinkedList
import [Link];
[Link](10);
[Link](20);
[Link](5); // Add at beginning
[Link](30); // Add at end
35
[Link]();
[Link]();
3. Vector
import [Link];
Set Interface
Characteristics: - Unordered collection (no guaranteed order) - No duplicates
allowed - No index-based access
1. HashSet
import [Link];
[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // Duplicate ignored
[Link]([Link]()); // 2
// Check existence
boolean exists = [Link]("Apple"); // true
// Remove
[Link]("Banana");
// Iterate
for (String item : set) {
[Link](item);
}
2. LinkedHashSet
36
import [Link];
[Link]("C");
[Link]("A");
[Link]("B");
3. TreeSet
import [Link];
[Link](30);
[Link](10);
[Link](20);
Queue Interface
Characteristics: - FIFO (First-In-First-Out) - Used for processing elements
in order
1. PriorityQueue
import [Link];
[Link](30);
[Link](10);
[Link](20);
Map Interface
Characteristics: - Key-value pairs - Keys are unique - Fast retrieval by key
37
1. HashMap
import [Link];
// Check key/value
boolean hasKey = [Link](1); // true
boolean hasValue = [Link]("Apple"); // true
// Remove
[Link](2);
// Size
int size = [Link]();
// Iterate
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
// Key set
Set<Integer> keys = [Link]();
// Values
Collection<String> values = [Link]();
2. LinkedHashMap
import [Link];
[Link](3, "Three");
[Link](1, "One");
[Link](2, "Two");
38
3. TreeMap
import [Link];
[Link](3, "Three");
[Link](1, "One");
[Link](2, "Two");
39
// Without lambda (traditional way)
Runnable r1 = new Runnable() {
public void run() {
[Link]("Hello");
}
};
// With lambda
Runnable r2 = () -> [Link]("Hello");
// With parameters
interface Calculator {
int calculate(int a, int b);
}
[Link]([Link](5, 3)); // 8
[Link]([Link](5, 3)); // 15
Functional Interface
Definition: Interface with exactly one abstract method.
Annotation: @FunctionalInterface
@FunctionalInterface
interface MyInterface {
void myMethod();
40
[Link]([Link](10)); // true
[Link]([Link](15)); // false
2. Consumer
• Accepts input, returns nothing
• Used for forEach operations
import [Link];
3. Supplier
• Provides output without input
• Factory pattern
import [Link];
4. Function<T, R>
• Accepts input, returns output
import [Link];
Stream API
Definition: Process collections in functional style.
Stream Operations: - Intermediate: Return stream (filter, map, sorted) -
Terminal: Return result (collect, forEach, reduce)
Creating Streams
// From Collection
List<String> list = [Link]("A", "B", "C");
Stream<String> stream = [Link]();
// From Array
41
String[] arr = {"A", "B", "C"};
Stream<String> stream = [Link](arr);
// Using [Link]()
Stream<String> stream = [Link]("A", "B", "C");
42
long count = [Link]()
.filter(n -> n > 3)
.count();
8. min() / max() - Find min/max
Optional<Integer> min = [Link]().min(Integer::compare);
Optional<Integer> max = [Link]().max(Integer::compare);
Method References
Types: 1. Reference to static method: ClassName::methodName 2. Refer-
ence to instance method: object::methodName 3. Reference to constructor:
ClassName::new
// Static method reference
List<String> list = [Link]("1", "2", "3");
List<Integer> numbers = [Link]()
.map(Integer::parseInt)
.collect([Link]());
// Constructor reference
Supplier<ArrayList> listSupplier = ArrayList::new;
Optional Class
Purpose: Avoid NullPointerException by representing optional values.
import [Link];
// Create Optional
Optional<String> optional = [Link]("Hello");
Optional<String> empty = [Link]();
Optional<String> nullable = [Link](null);
// Check if present
if ([Link]()) {
[Link]([Link]());
}
43
// orElseGet() - supplier
String value = [Link](() -> "Default");
// filter()
Optional<String> filtered = [Link](s -> [Link]() > 3);
// map()
Optional<Integer> length = [Link](String::length);
// Current date
LocalDate today = [Link]();
// Specific date
LocalDate date = [Link](2024, 1, 15);
// Operations
LocalDate tomorrow = [Link](1);
LocalDate lastWeek = [Link](1);
// Get components
int year = [Link]();
int month = [Link]();
int day = [Link]();
// Comparison
boolean isBefore = [Link](today);
boolean isAfter = [Link](today);
LocalTime
import [Link];
// Current time
LocalTime now = [Link]();
// Specific time
LocalTime time = [Link](10, 30, 45);
44
// Operations
LocalTime later = [Link](2);
LocalTime earlier = [Link](30);
LocalDateTime
import [Link];
// Current date-time
LocalDateTime now = [Link]();
// Specific date-time
LocalDateTime dateTime = [Link](2024, 1, 15, 10, 30);
13. Multithreading
What is Multithreading?
• Concurrent execution of multiple threads
• Each thread runs independently
• Shares same memory space
Thread Lifecycle
1. New: Thread created but not started
2. Runnable: Ready to run
3. Running: Executing
4. Blocked/Waiting: Waiting for resource
5. Terminated: Completed execution
Creating Threads
Method 1: Extending Thread Class
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);
}
}
45
}
[Link]();
[Link]();
}
}
[Link]();
[Link]();
}
}
Runnable vs Thread: - Runnable is preferred (allows extending other classes)
- Thread extends Thread class (single inheritance limitation)
Thread Methods
Thread t = new Thread();
// Start thread
[Link]();
46
[Link]("MyThread");
// Check if alive
boolean alive = [Link]();
Synchronization
Problem: Race condition when multiple threads access shared resource.
Solution: Synchronization ensures only one thread accesses resource at a time.
1. Synchronized Method
class Counter {
private int count = 0;
2. Synchronized Block
class Counter {
private int count = 0;
private Object lock = new Object();
47
}
}
}
Inter-Thread Communication
Methods: - wait() - Thread releases lock and waits - notify() - Wakes up
one waiting thread - notifyAll() - Wakes up all waiting threads
class SharedResource {
private int value;
private boolean available = false;
Deadlock
Definition: Two or more threads waiting for each other indefinitely.
Example:
// Thread 1 locks A, waits for B
synchronized(A) {
synchronized(B) {
// code
}
}
48
// Thread 2 locks B, waits for A
synchronized(B) {
synchronized(A) {
// code
}
}
// DEADLOCK!
Prevention: - Lock resources in same order - Use timeout - Avoid nested locks
Assessment Tips
Common Question Patterns
1. MCQ on Syntax and Outputs
• Practice code snippets
• Understand operator precedence
• Know exception types
2. Code Analysis
• Trace variable values
• Understand loop iterations
• Method overloading vs overriding
3. Conceptual Questions
• OOP principles
• JVM vs JRE vs JDK
• Collection choosing (when to use what)
4. Code Writing
• Array operations
• String manipulation
• Exception handling
• JDBC operations
5. Fill in the Blanks
• Keywords (static, final, abstract)
• Access modifiers
• Method signatures
49
• synchronized ensures thread safety
• finally always executes (except [Link]())
Practice Areas
1. Write programs for:
• Array sorting and searching
• String reversal and palindrome
• Bank account with encapsulation
• JDBC CRUD operations
• Exception handling scenarios
2. Understand:
• Collection Framework hierarchy
• Stream API operations
• Thread synchronization
• Optional usage
50