[Go to site: main page, start]

0% found this document useful (0 votes)
3 views50 pages

Java Complete Notes

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)
3 views50 pages

Java Complete Notes

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

Complete Java Study Notes - ITVedant Assess-

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

1. Getting Started With Core Java


What is Java?
• Java is a high-level, object-oriented, platform-independent programming
language developed by James Gosling at Sun Microsystems in 1995
• Follows the principle of “Write Once, Run Anywhere” (WORA)
• Multi-paradigm language supporting OOP, procedural, and functional pro-
gramming

Java vs C++

Feature Java C++


Platform Platform Independent Platform Dependent
Pointers No pointer support Supports pointers
Multiple Inheritance Not supported (uses interfaces) Supported
Memory Management Automatic (Garbage Collection) Manual
Operator Overloading Not supported Supported

Java Architecture: JVM, JRE, JDK


Java Virtual Machine (JVM)
• Core execution engine that runs Java bytecode
• Converts bytecode into machine-specific instructions

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

Java Runtime Environment (JRE)


• Runtime platform for executing Java applications
• Components:
– JVM (Java Virtual Machine)
– Core libraries and class files
– Supporting Java class files
• Does NOT include development tools (compiler, debugger)
• Used only for running Java programs

Java Development Kit (JDK)


• Complete development toolkit for Java
• Components:
– JRE (Java Runtime Environment)
– Java Compiler (javac)
– Development tools: javadoc, jar, debugger
– Archive and debugging tools
• Required for developing Java applications
Relationship: JDK � JRE � JVM

How Java Works


1. Source Code (.java): Write Java code in .java file
2. Compilation: JDK’s compiler (javac) converts source code to bytecode
(.class files)
3. Execution: JRE loads bytecode and JVM executes it
4. Platform Independence: Same bytecode runs on any platform with
JVM

First Java Program Structure


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Components: - public: Access modifier (accessible everywhere) - class:
Blueprint for objects - HelloWorld: Class name (must match filename) - static:

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)

Type Size Range Default Example


byte 1 byte -128 to 127 0 byte b = 100;
short 2 bytes -32,768 to 32,767 0 short s = 1000;
int 4 bytes -2³¹ to 2³¹-1 0 int i = 100000;
long 8 bytes -2�³ to 2�³-1 0L long l = 100000L;
float 4 bytes ~6-7 decimal digits 0.0f float f = 3.14f;
double 8 bytes ~15 decimal digits 0.0d double d = 3.14159;
char 2 bytes 0 to 65,535 (Unicode) ‘0̆000’ char c = 'A';
boolean 1 bit true or false false boolean b = true;

Non-Primitive (Reference) Data Types


• String: Sequence of characters
• Arrays: Collection of similar data types
• Classes: User-defined data types
• Interfaces: Abstract 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.

Types of Literals 1. Integer Literals


int decimal = 100; // Decimal (base 10)
int octal = 0144; // Octal (base 8) - starts with 0
int hex = 0x64; // Hexadecimal (base 16) - starts with 0x
int binary = 0b1100100; // Binary (base 2) - starts with 0b
2. Floating-Point Literals
float f = 10.5f; // f or F suffix for float
double d = 10.5; // Default is double
double exp = 3.45e2; // Scientific notation = 345.0
3. Character Literals
char letter = 'A';
char newline = '\n'; // Escape sequence
char tab = '\t'; // Tab
4. String Literals
String text = "Hello World";
5. Boolean Literals
boolean flag1 = true;
boolean flag2 = false;

3. Java Power Moves (Operators)


Types of Operators
1. Arithmetic Operators
int a = 10, b = 3;
int sum = a + b; // Addition = 13
int diff = a - b; // Subtraction = 7
int prod = a * b; // Multiplication = 30
int quot = a / b; // Division = 3
int rem = a % b; // Modulus = 1

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

int age = 18;


String result = (age >= 18) ? "Adult" : "Minor";
// result = "Adult"

Operator Precedence (High to Low)


1. Postfix: expr++, expr--
2. Unary: ++expr, --expr, +, -, !, ~
3. Multiplicative: *, /, %
4. Additive: +, -
5. Shift: <<, >>, >>>
6. Relational: <, >, <=, >=
7. Equality: ==, !=
8. Bitwise AND: &
9. Bitwise XOR: ^
10. Bitwise OR: |
11. Logical AND: &&
12. Logical OR: ||
13. Ternary: ?:
14. Assignment: =, +=, -=, etc.

4. Mastering Java Flow (Control Statements)


Decision-Making Statements
1. if Statement
if (condition) {
// code to execute if condition is true
}

// 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);

4. Enhanced for Loop (for-each)


for (dataType variable : array/collection) {
// code
}

// Example
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
[Link](num);
}

Loop Control Statements


break Statement
// Exit loop immediately
for (int i = 1; i <= 10; i++) {
if (i == 5) {

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

Array Declaration and Initialization


1. Single-Dimensional Array Declaration:
dataType[] arrayName;
// or
dataType arrayName[];
Instantiation:
arrayName = new dataType[size];
Initialization:
// Method 1: Declare, instantiate, then assign
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;

// Method 2: Direct initialization


int[] numbers = {10, 20, 30, 40, 50};

// Method 3: Declare and instantiate separately

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};

// Using for loop


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

// Using for-each loop


for (int num : numbers) {
[Link](num);
}

2. Multi-Dimensional Arrays Two-Dimensional Array:


// Declaration
int[][] matrix = new int[3][3];

// 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];

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


if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}

2. Array Reversal
int[] arr = {1, 2, 3, 4, 5};
int start = 0;
int end = [Link] - 1;

while (start < end) {


int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}

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};

// Method 1: Using clone()


int[] copy1 = [Link]();

// Method 2: Using [Link]()


int[] copy2 = [Link](original, [Link]);

// Method 3: Using [Link]()


int[] copy3 = new int[5];
[Link](original, 0, copy3, 0, [Link]);

6. Object Oriented Programming (OOP)


Four Pillars of OOP
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Classes and Objects


Class
• Blueprint or template for creating objects
• Contains variables (attributes) and methods (behaviors)
Syntax:
class ClassName {
// Instance variables (attributes)
dataType variable1;
dataType variable2;

// 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);
}
}

// Creating and using object


public class Main {
public static void main(String[] args) {
Student s1 = new Student("John", 101);
[Link]();
}
}

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;
}
}

int result = [Link](5, 3); // 15

Method Overloading (Compile-time Polymorphism)


• Same method name with different parameters
• Different parameter types, number, or order
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

Constructors
Types of Constructors 1. Default Constructor
class Student {
String name;

Student() { // Default constructor


name = "Unknown";
}
}
2. Parameterized Constructor
class Student {
String name;

15
int age;

Student(String n, int a) { // Parameterized


name = n;
age = a;
}
}
3. Copy Constructor
class Student {
String name;

Student(Student s) { // Copy constructor


[Link] = [Link];
}
}

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;
}
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
}
}

16
}

Access Modifiers

Modifier Class Package Subclass World


public � � � �
protected � � � �
default � � � �
private � � � �

this Keyword - Refers to current object - Used to distinguish between instance


variables and parameters
class Student {
String name;

Student(String name) {
[Link] = name; // [Link] = instance variable
}
}

7. OOP: Inheritance & Polymorphism


Inheritance
Definition: Mechanism where one class acquires properties and methods of
another class.
Syntax:
class SubClass extends SuperClass {
// SubClass members
}

Types of Inheritance 1. Single Inheritance


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

class Dog extends Animal {


void bark() {
[Link]("Barking...");

17
}
}
2. Multilevel Inheritance
class Animal {
void eat() { }
}

class Dog extends Animal {


void bark() { }
}

class Puppy extends Dog {


void weep() { }
}
3. Hierarchical Inheritance
class Animal {
void eat() { }
}

class Dog extends Animal { }


class Cat extends Animal { }
class Bird extends Animal { }
4. Multiple Inheritance (Through Interfaces)
interface Printable {
void print();
}

interface Showable {
void show();
}

class Document implements Printable, Showable {


public void print() {
[Link]("Printing...");
}

public void show() {


[Link]("Showing...");
}
}

18
super Keyword
• Refers to parent class
• Used to call parent class constructor or methods
class Parent {
int x = 10;

Parent() {
[Link]("Parent constructor");
}
}

class Child extends Parent {


int x = 20;

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)

void sleep() { // Concrete method


[Link]("Sleeping...");
}
}

class Dog extends Animal {


void sound() {
[Link]("Bark");
}
}

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();
}

class Rectangle implements Drawable, Printable {


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

public void print() {


[Link]("Printing rectangle");
}
}

Abstract Class vs Interface

Feature Abstract Class Interface


Methods Abstract + Non-abstract Only abstract (before Java 8)
Variables Any type public static final only
Multiple Inheritance No Yes
Constructor Can have Cannot have
Access Modifiers Any public only

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;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}
2. Runtime Polymorphism (Method Overriding) - Subclass provides
specific implementation of parent method - Resolved at runtime
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
[Link]("Cat meows");
}
}

// Usage
Animal a;
a = new Dog();
[Link](); // Dog barks (runtime polymorphism)

a = new Cat();

21
[Link](); // Cat meows

Method Overloading vs Overriding

Feature Overloading Overriding


Definition Same name, different Same signature in parent
parameters and child
Inheritance Not required Required
Polymorphism Type Compile-time Runtime
Return Type Can be different Must be same or
covariant
Access Modifier Can be different Cannot be more
restrictive

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;

final void display() {


[Link](PI);
}
}

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)

s1 = [Link](" World"); // Now s1 points to new string


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

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 s3 = new String("Hello");


[Link](s1 == s3); // false (different reference)
[Link]([Link](s3)); // true (same content)

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");

// Same methods as StringBuffer


[Link](" World");
[Link](5, ",");
[Link](7, 12, "Java");
[Link](5, 6);
[Link]();

String vs StringBuffer vs StringBuilder

Feature String StringBuffer StringBuilder


Mutability Immutable Mutable Mutable
Thread-Safe Yes Yes No
Performance Slow Moderate Fast
Storage String Pool Heap Heap
When to Use Fixed strings Multi-threaded Single-threaded

Performance Comparison:
// String (Slow - creates many objects)
String s = "";
for (int i = 0; i < 1000; i++) {
s += i; // Creates new object each time
}

// StringBuffer (Moderate - thread-safe)

25
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
[Link](i); // Modifies same object
}

// StringBuilder (Fast - not thread-safe)


StringBuilder sbl = new StringBuilder();
for (int i = 0; i < 1000; i++) {
[Link](i); // Fastest
}

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

2. Unchecked Exceptions (Runtime Exceptions)

26
• Checked at runtime
• Not mandatory to handle
• Examples: ArithmeticException, NullPointerException

3. Errors
• Serious problems that cannot be handled
• Examples: OutOfMemoryError, StackOverflowError

Exception Handling Keywords


1. try Block
• Contains code that might throw exception
• Must be followed by catch or finally
try {
// Risky code
int result = 10 / 0;
}

2. catch Block
• Handles specific exception
• Can have multiple catch blocks
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}

3. Multiple catch Blocks


try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArithmeticException e) {
[Link]("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
} catch (Exception e) {
[Link]("General error");
}

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");
}
}

public static void main(String[] args) {


try {
validate(15);
} catch (InvalidAgeException e) {
[Link]([Link]());
}
}
}

Advantages of Exception Handling


1. Separates error handling from normal code
2. Maintains normal program flow
3. Categorizes exception types
4. Propagates exceptions up the call stack

10. JDBC (Java Database Connectivity)


What is JDBC?
• API for connecting and executing queries with databases
• Bridge between Java application and database
• Part of Java SE (Standard Edition)

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)

Type 2: Native-API Driver


• Uses database-specific native libraries
• Better performance than Type 1

Type 3: Network Protocol Driver


• Middleware converts JDBC calls to database-specific calls
• Platform independent

Type 4: Thin Driver (Pure Java Driver)


• Direct communication with database
• Most commonly used
• Platform independent

JDBC Steps
1. Load Driver
[Link]("[Link]");

2. Create Connection
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "root";
String password = "password";

Connection con = [Link](url, username, password);

3. Create Statement
Statement stmt = [Link]();

4. Execute Query
// For SELECT (returns ResultSet)
ResultSet rs = [Link]("SELECT * FROM students");

// For INSERT, UPDATE, DELETE (returns int)


int rows = [Link]("INSERT INTO students VALUES(1, 'John')");

30
5. Process Results
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link](id + " " + name);
}

6. Close Connection
[Link]();
[Link]();
[Link]();

Complete JDBC Example


import [Link].*;

public class JDBCExample {


public static void main(String[] args) {
try {
// 1. Load Driver
[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);
}
}
}

Statement vs PreparedStatement vs CallableStatement

Feature Statement PreparedStatement CallableStatement


Use Simple Parameterized queries Stored procedures
queries
SQL Vulnerable Safe Safe
Injection
Performance Slow Fast (pre-compiled) Fast
Example [Link]()
[Link](1, [Link](1,
10) "name")

PreparedStatement Example
String sql = "INSERT INTO students VALUES (?, ?)";
PreparedStatement pstmt = [Link](sql);

[Link](1, 101);
[Link](2, "John");
int rows = [Link]();

[Link](rows + " row(s) inserted");

JDBC CRUD Operations


Create (INSERT)
String sql = "INSERT INTO students (id, name) VALUES (?, ?)";
PreparedStatement pstmt = [Link](sql);
[Link](1, 1);
[Link](2, "John");
[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]();

Exception Handling in JDBC


try {
// JDBC code
} catch (ClassNotFoundException e) {
[Link]("Driver not found");
} catch (SQLException e) {
[Link]("SQL error: " + [Link]());
}

11. Collection Framework


What is Collection Framework?
• Set of classes and interfaces to store and manipulate groups of objects
• Provides data structures like List, Set, Queue, Map

Collection Hierarchy
Collection (Interface)
��� List (Interface)
� ��� ArrayList
� ��� LinkedList
� ��� Vector
� ��� Stack
��� Set (Interface)
� ��� HashSet
� ��� LinkedHashSet

33
� ��� TreeSet
��� Queue (Interface)
��� PriorityQueue
��� ArrayDeque

Map (Interface) - Separate hierarchy


��� HashMap
��� LinkedHashMap
��� TreeMap
��� Hashtable

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

// With generics (type-safe)


ArrayList<String> list = new ArrayList<String>();
[Link]("String");
// [Link](10); // Compile-time error
Generic Class:
class Box<T> {
T value;

void set(T value) {


[Link] = value;
}

T get() {
return value;
}
}

Box<Integer> intBox = new Box<>();


[Link](10);

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];

ArrayList<String> list = new ArrayList<>();

// 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];

LinkedList<Integer> list = new LinkedList<>();

[Link](10);
[Link](20);
[Link](5); // Add at beginning
[Link](30); // Add at end

35
[Link]();
[Link]();

int first = [Link]();


int last = [Link]();

3. Vector
import [Link];

Vector<String> vector = new Vector<>();


[Link]("A");
[Link]("B");

// Thread-safe but slower than ArrayList

Set Interface
Characteristics: - Unordered collection (no guaranteed order) - No duplicates
allowed - No index-based access

1. HashSet
import [Link];

HashSet<String> set = new HashSet<>();

[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];

LinkedHashSet<String> set = new LinkedHashSet<>();

[Link]("C");
[Link]("A");
[Link]("B");

// Maintains insertion order: C, A, B

3. TreeSet
import [Link];

TreeSet<Integer> set = new TreeSet<>();

[Link](30);
[Link](10);
[Link](20);

// Automatically sorted: 10, 20, 30

int first = [Link](); // 10


int last = [Link](); // 30

Queue Interface
Characteristics: - FIFO (First-In-First-Out) - Used for processing elements
in order

1. PriorityQueue
import [Link];

PriorityQueue<Integer> pq = new PriorityQueue<>();

[Link](30);
[Link](10);
[Link](20);

[Link]([Link]()); // 10 (smallest first)


[Link]([Link]()); // 20
[Link]([Link]()); // 30 (peek without removing)

Map Interface
Characteristics: - Key-value pairs - Keys are unique - Fast retrieval by key

37
1. HashMap
import [Link];

HashMap<Integer, String> map = new HashMap<>();

// Put key-value pairs


[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Cherry");

// Get value by key


String value = [Link](2); // "Banana"

// 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];

LinkedHashMap<Integer, String> map = new LinkedHashMap<>();

[Link](3, "Three");
[Link](1, "One");
[Link](2, "Two");

// Maintains insertion order: 3, 1, 2

38
3. TreeMap
import [Link];

TreeMap<Integer, String> map = new TreeMap<>();

[Link](3, "Three");
[Link](1, "One");
[Link](2, "Two");

// Automatically sorted by keys: 1, 2, 3

int firstKey = [Link](); // 1


int lastKey = [Link](); // 3

List vs Set vs Map

Feature List Set Map


Order Maintains order No No
guaranteed guaranteed
order order
Duplicates Allowed Not allowed Keys unique,
values can
duplicate
Null Multiple nulls One null One null key,
(HashSet) multiple null
values
Index Yes No No
Example ArrayList, HashSet, HashMap,
LinkedList TreeSet TreeMap

12. Major Java 8 Features


Lambda Expressions
Definition: Anonymous function that provides concise way to represent func-
tional interface.
Syntax:
(parameters) -> expression
// or
(parameters) -> { statements; }
Examples:

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);
}

Calculator add = (a, b) -> a + b;


Calculator multiply = (a, b) -> a * 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();

// Can have default and static methods


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

Common Functional Interfaces


1. Predicate
• Tests a condition
• Returns boolean
import [Link];

Predicate<Integer> isEven = num -> num % 2 == 0;

40
[Link]([Link](10)); // true
[Link]([Link](15)); // false

2. Consumer
• Accepts input, returns nothing
• Used for forEach operations
import [Link];

Consumer<String> print = str -> [Link](str);


[Link]("Hello"); // Prints: Hello

List<String> list = [Link]("A", "B", "C");


[Link](print);

3. Supplier
• Provides output without input
• Factory pattern
import [Link];

Supplier<Double> randomValue = () -> [Link]();


[Link]([Link]());

4. Function<T, R>
• Accepts input, returns output
import [Link];

Function<String, Integer> length = str -> [Link]();


[Link]([Link]("Hello")); // 5

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");

Stream Operations 1. filter() - Filter elements


List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);
List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0)
.collect([Link]());
// Result: [2, 4, 6]
2. map() - Transform elements
List<String> names = [Link]("John", "Jane", "Bob");
List<Integer> lengths = [Link]()
.map(String::length)
.collect([Link]());
// Result: [4, 4, 3]
3. sorted() - Sort elements
List<Integer> numbers = [Link](5, 2, 8, 1, 3);
List<Integer> sorted = [Link]()
.sorted()
.collect([Link]());
// Result: [1, 2, 3, 5, 8]
4. forEach() - Iterate
List<String> list = [Link]("A", "B", "C");
[Link]().forEach([Link]::println);
5. collect() - Collect to collection
List<String> list = [Link]("A", "B", "C");
Set<String> set = [Link]()
.collect([Link]());
6. reduce() - Reduce to single value
List<Integer> numbers = [Link](1, 2, 3, 4, 5);
int sum = [Link]()
.reduce(0, (a, b) -> a + b);
// Result: 15
7. count() - Count elements

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]());

// Instance method reference


[Link]([Link]::println);

// 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]());
}

// ifPresent() with lambda


[Link]([Link]::println);

// orElse() - default value


String value = [Link]("Default");

43
// orElseGet() - supplier
String value = [Link](() -> "Default");

// orElseThrow() - throw exception


String value = [Link](() -> new RuntimeException("Not found"));

// filter()
Optional<String> filtered = [Link](s -> [Link]() > 3);

// map()
Optional<Integer> length = [Link](String::length);

Date and Time API


LocalDate
import [Link];

// 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);

// Combine date and time


LocalDate date = [Link]();
LocalTime time = [Link]();
LocalDateTime combined = [Link](date, time);

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
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

[Link]();
[Link]();
}
}

Method 2: Implementing Runnable Interface


class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);
}
}
}

public class Main {


public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);

[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]();

// Get thread name


String name = [Link]();

// Set thread name

46
[Link]("MyThread");

// Get current thread


Thread current = [Link]();

// Sleep (pause execution)


[Link](1000); // 1 second

// Join (wait for thread to die)


[Link]();

// Check if alive
boolean alive = [Link]();

// Priority (1-10, default 5)


[Link](Thread.MAX_PRIORITY); // 10
int priority = [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;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

2. Synchronized Block
class Counter {
private int count = 0;
private Object lock = new Object();

public void increment() {


synchronized(lock) {
count++;

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;

public synchronized void produce(int val) {


while (available) {
try {
wait();
} catch (InterruptedException e) { }
}
value = val;
available = true;
notify();
}

public synchronized int consume() {


while (!available) {
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
notify();
return value;
}
}

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

Key Points to Remember


• String is immutable
• == compares references, equals() compares content
• PreparedStatement prevents SQL injection
• ArrayList vs LinkedList: Random access vs Sequential access
• HashMap allows one null key
• Lambda works with functional interfaces only

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

Good Luck with Your Assessment! �


Study Strategy: - Focus on code examples - Practice writing code - Under-
stand concepts, don’t memorize - Review ITVedant assignments and projects -
Test yourself with sample questions

50

You might also like