Complete Java Programming Notes - Beginner to Advanced
Table of Contents
1. Java Basics
2. Data Types
3. Variables and Operators
4. Control Flow Statements
5. Methods
6. Arrays
7. Object-Oriented Programming (OOP)
8. String Handling
9. Exception Handling
10. Collections Framework
11. File Handling
12. Input/Output (I/O)
13. Multithreading
14. Advanced Topics
Java Basics
What is Java?
Java is a high-level, object-oriented programming language developed by Sun Microsystems
(now Oracle). It’s platform-independent, meaning “Write Once, Run Anywhere” (WORA).
Setting Up Java
1. Install JDK (Java Development Kit)
2. Set environment variables (PATH, JAVA_HOME)
3. Use IDE like Eclipse, IntelliJ IDEA, or VS Code
First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation: - public class HelloWorld: Defines a public class named HelloWorld -
public static void main(String[] args): Main method where program execution
starts - System.out.println(): Prints text to console
Data Types
Primitive Data Types
1. Integer Types
byte b = 127; // 8-bit, range: -128 to 127
short s = 32767; // 16-bit, range: -32,768 to 32,767
int i = 2147483647; // 32-bit, range: -2^31 to 2^31-1
long l = 9223372036854775807L; // 64-bit, range: -2^63 to 2^63-1
2. Floating Point Types
float f = 3.14f; // 32-bit, single precision
double d = 3.141592653589793; // 64-bit, double precision
3. Character Type
char c = 'A'; // 16-bit Unicode character
char unicode = '\u0041'; // Unicode representation of 'A'
4. Boolean Type
boolean isTrue = true;
boolean isFalse = false;
Non-Primitive Data Types
• String
• Arrays
• Classes
• Interfaces
int vs Integer (Primitive vs Wrapper Classes)
int (Primitive)
int num1 = 10; // Stored directly in memory
int num2 = 20;
int sum = num1 + num2; // Direct arithmetic operation
Integer (Wrapper Class)
Integer num1 = 10; // Object wrapper around int
Integer num2 = 20;
Integer sum = num1 + num2; // Auto-boxing/unboxing happens
// Useful methods in Integer class
Integer.parseInt("123"); // Convert string to int
Integer.valueOf(123); // Create Integer object
Integer.MAX_VALUE; // Maximum int value
Integer.MIN_VALUE; // Minimum int value
Key Differences: - int: Primitive, faster, no methods, cannot be null - Integer: Object,
slower, has methods, can be null, used in collections
Variables and Operators
Variable Declaration and Initialization
// Declaration
int age;
String name;
// Initialization
age = 25;
name = "John";
// Declaration and initialization together
int height = 180;
String city = "New York";
// Constants
final int MAX_SIZE = 100;
final double PI = 3.14159;
Variable Scope
public class ScopeExample {
static int globalVar = 100; // Class variable
public void method() {
int localVar = 50; // Local variable
for (int i = 0; i < 10; i++) {
int loopVar = i; // Block variable
}
// loopVar not accessible here
}
}
Operators
Arithmetic Operators
int a = 10, b = 3;
int addition = a + b; // 13
int subtraction = a - b; // 7
int multiplication = a * b; // 30
int division = a / b; // 3 (integer division)
int modulus = a % b; // 1 (remainder)
// Increment and Decrement
int x = 5;
x++; // Post-increment: x becomes 6
++x; // Pre-increment: x becomes 7
x--; // Post-decrement: x becomes 6
--x; // Pre-decrement: x becomes 5
Comparison Operators
int a = 10, b = 20;
boolean result;
result = (a == b); // false (equal to)
result = (a != b); // true (not equal to)
result = (a < b); // true (less than)
result = (a > b); // false (greater than)
result = (a <= b); // true (less than or equal to)
result = (a >= b); // false (greater than or equal to)
Logical Operators
boolean a = true, b = false;
boolean and = a && b; // false (logical AND)
boolean or = a || b; // true (logical OR)
boolean not = !a; // false (logical NOT)
Assignment Operators
int a = 10;
a += 5; // a = a + 5, result: 15
a -= 3; // a = a - 3, result: 12
a *= 2; // a = a * 2, result: 24
a /= 4; // a = a / 4, result: 6
a %= 4; // a = a % 4, result: 2
Control Flow Statements
Conditional Statements
if Statement
int age = 18;
if (age >= 18) {
System.out.println("You are an adult");
}
if-else Statement
int marks = 75;
if (marks >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
if-else-if Ladder
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B");
} else if (marks >= 70) {
System.out.println("Grade C");
} else if (marks >= 60) {
System.out.println("Grade D");
} else {
System.out.println("Grade F");
}
Nested if
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive");
} else {
System.out.println("Get a license first");
}
} else {
System.out.println("You are too young to drive");
}
switch Statement
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println(dayName);
Enhanced switch (Java 14+)
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
Loop Statements
for Loop
// Basic for loop
for (int i = 1; i <= 10; i++) {
System.out.println("Number: " + i);
}
// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i: " + i + ", j: " + j);
}
// Nested for loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
Enhanced for Loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}
while Loop
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
// Example: Finding factorial
int n = 5;
int factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
System.out.println("Factorial of " + n + " is " + factorial);
do-while Loop
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
// Menu-driven program example
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Addition selected");
break;
case 2:
System.out.println("Subtraction selected");
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice");
}
} while (choice != 3);
Jump Statements
break Statement
// In loops
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i becomes 6
}
System.out.println(i);
}
// In nested loops with labels
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer; // Break out of outer loop
}
System.out.println("i: " + i + ", j: " + j);
}
}
continue Statement
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i); // Print only odd numbers
}
return Statement
public int findMax(int a, int b) {
if (a > b) {
return a; // Exit method and return value
} else {
return b;
}
}
Methods
Method Declaration and Definition
public class MethodExample {
// Method with no parameters and no return value
public void greet() {
System.out.println("Hello!");
}
// Method with parameters and return value
public int add(int a, int b) {
return a + b;
}
// Method with multiple parameters
public void printPersonInfo(String name, int age, double height) {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
}
// Method with array parameter
public int findSum(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
}
Method Overloading
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String add(String a, String b) {
return a + b;
}
}
Variable Arguments (Varargs)
public class VarargsExample {
public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
VarargsExample obj = new VarargsExample();
System.out.println(obj.sum(1, 2)); // 3
System.out.println(obj.sum(1, 2, 3)); // 6
System.out.println(obj.sum(1, 2, 3, 4, 5)); // 15
}
}
Recursion
public class RecursionExample {
// Factorial using recursion
public int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}
// Fibonacci using recursion
public int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Tower of Hanoi
public void towerOfHanoi(int n, char source, char destination,
char auxiliary) {
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " +
destination);
return;
}
towerOfHanoi(n - 1, source, auxiliary, destination);
System.out.println("Move disk " + n + " from " + source + " to
" + destination);
towerOfHanoi(n - 1, auxiliary, destination, source);
}
}
Arrays
One-Dimensional Arrays
Declaration and Initialization
// Declaration
int[] numbers;
String[] names;
// Declaration and initialization
int[] numbers = new int[5]; // Array of size 5
String[] names = new String[3];
// Declaration, initialization, and assignment
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
// Alternative syntax
int numbers[] = new int[5];
Accessing Array Elements
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
int first = numbers[0]; // 10
int last = numbers[4]; // 50
int length = numbers.length; // 5
// Modifying elements
numbers[2] = 35; // Changes 30 to 35
// Traversing array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
// Enhanced for loop
for (int num : numbers) {
System.out.println(num);
}
Two-Dimensional Arrays
// Declaration and initialization
int[][] matrix = new int[3][3];
// Declaration and initialization with values
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
int element = matrix[1][2]; // 6 (row 1, column 2)
// Traversing 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// Enhanced for loop for 2D array
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
Jagged Arrays
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2]; // First row has 2 columns
jaggedArray[1] = new int[4]; // Second row has 4 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns
// Initialize with values
int[][] jaggedArray = {
{1, 2},
{3, 4, 5, 6},
{7, 8, 9}
};
Array Operations Examples
public class ArrayOperations {
// Linear search
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
// Binary search (array must be sorted)
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
// Bubble sort
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Find maximum element
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
Object-Oriented Programming (OOP)
1. Classes and Objects
Class Definition
public class Student {
// Instance variables (attributes)
private String name;
private int age;
private String studentId;
private double gpa;
// Static variable (class variable)
private static int totalStudents = 0;
// Default constructor
public Student() {
totalStudents++;
}
// Parameterized constructor
public Student(String name, int age, String studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
totalStudents++;
}
// Copy constructor
public Student(Student other) {
this.name = other.name;
this.age = other.age;
this.studentId = other.studentId;
this.gpa = other.gpa;
totalStudents++;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getStudentId() {
return studentId;
}
public double getGpa() {
return gpa;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
if (age > 0 && age < 100) {
this.age = age;
}
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public void setGpa(double gpa) {
if (gpa >= 0.0 && gpa <= 4.0) {
this.gpa = gpa;
}
}
// Static method
public static int getTotalStudents() {
return totalStudents;
}
// Instance methods
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Student ID: " + studentId);
System.out.println("GPA: " + gpa);
}
public boolean isHonorStudent() {
return gpa >= 3.5;
}
// toString method
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age +
", studentId='" + studentId + "', gpa=" + gpa + "}";
}
}
Creating and Using Objects
public class StudentTest {
public static void main(String[] args) {
// Creating objects
Student student1 = new Student();
Student student2 = new Student("Alice", 20, "S001");
// Setting values
student1.setName("Bob");
student1.setAge(19);
student1.setStudentId("S002");
student1.setGpa(3.8);
// Getting values
System.out.println("Student 1 Name: " + student1.getName());
System.out.println("Student 1 GPA: " + student1.getGpa());
// Calling methods
student1.displayInfo();
System.out.println("Is honor student: " +
student1.isHonorStudent());
// Static method call
System.out.println("Total students: " +
Student.getTotalStudents());
}
}
2. Encapsulation
Encapsulation is the bundling of data and methods that operate on that data within a single
unit (class).
public class BankAccount {
private double balance; // Private data member
private String accountNumber;
private String accountHolderName;
public BankAccount(String accountNumber, String accountHolderName)
{
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = 0.0;
}
// Public methods to access private data
public double getBalance() {
return balance;
}
public String getAccountNumber() {
return accountNumber;
}
public String getAccountHolderName() {
return accountHolderName;
}
// Controlled access to modify balance
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Invalid deposit amount");
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
return true;
} else {
System.out.println("Invalid withdrawal amount or
insufficient funds");
return false;
}
}
}
3. Inheritance
Inheritance allows a class to acquire properties and methods from another class.
// Parent class (Superclass)
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
// Child class (Subclass)
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Call parent constructor
this.breed = breed;
}
// Method specific to Dog
public void bark() {
System.out.println(name + " is barking");
}
// Override parent method
@Override
public void displayInfo() {
super.displayInfo(); // Call parent method
System.out.println("Breed: " + breed);
}
// Override parent method
@Override
public void eat() {
System.out.println(name + " the dog is eating dog food");
}
}
// Another child class
public class Cat extends Animal {
private boolean isIndoor;
public Cat(String name, int age, boolean isIndoor) {
super(name, age);
this.isIndoor = isIndoor;
}
public void meow() {
System.out.println(name + " is meowing");
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Indoor cat: " + isIndoor);
}
}
Types of Inheritance
// Single Inheritance
class A { }
class B extends A { }
// Multilevel Inheritance
class A { }
class B extends A { }
class C extends B { }
// Hierarchical Inheritance
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
class Bird extends Animal { }
4. Polymorphism
Polymorphism allows objects of different types to be treated as objects of a common base
type.
Method Overriding (Runtime Polymorphism)
public class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
public double calculateArea() {
return 0;
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
@Override
public double calculateArea() {
return length * width;
}
}
// Usage
public class PolymorphismDemo {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
};
for (Shape shape : shapes) {
shape.draw(); // Calls appropriate method based on object
type
System.out.println("Area: " + shape.calculateArea());
}
}
}
5. Abstraction
Abstract Classes
public abstract class Vehicle {
protected String brand;
protected int year;
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
// Abstract method (must be implemented by subclasses)
public abstract void start();
public abstract void stop();
public abstract double calculateFuelEfficiency();
// Concrete method
public void displayInfo() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
public class Car extends Vehicle {
private int numberOfDoors;
public Car(String brand, int year, int numberOfDoors) {
super(brand, year);
this.numberOfDoors = numberOfDoors;
}
@Override
public void start() {
System.out.println("Car engine started");
}
@Override
public void stop() {
System.out.println("Car engine stopped");
}
@Override
public double calculateFuelEfficiency() {
return 25.0; // miles per gallon
}
}
public class Motorcycle extends Vehicle {
private boolean hasSidecar;
public Motorcycle(String brand, int year, boolean hasSidecar) {
super(brand, year);
this.hasSidecar = hasSidecar;
}
@Override
public void start() {
System.out.println("Motorcycle engine started");
}
@Override
public void stop() {
System.out.println("Motorcycle engine stopped");
}
@Override
public double calculateFuelEfficiency() {
return 45.0;
}
}
Interfaces
```java public interface Drawable { void draw(); // implicitly public and abstract void
resize(double factor);
// Default method (Java 8+)
default void setColor(String color) {
System.out.println("Setting color to " + color);
}
// Static method (Java 8+)
static void printInfo() {
System.out.println("This is a drawable interface");
}
}
public interface Movable { void move(int x, int y); int getX(); int getY(); }
// Multiple interface implementation public class Circle implements Drawable, Movable
{ private double radius; private int x, y;
public Circle(double radius, int x, int y) {
this.radius = radius;
this.x = x;
this.y = y;
}
@Override
public void draw() {
System.out.println("Drawing circle at (" + x + ", " + y + ") with
radius " + radius);
}
@Override
public void resize(double factor) {
radius