Java Basics
Java is a powerful, object-oriented programming language used for building enterprise-scale applications, Android apps, and web applications.
Platform Independence
“Write Once, Run Anywhere” – Java code compiles to bytecode that runs on any Java Virtual Machine (JVM).
Memory Management
Automatic garbage collection manages memory allocation and deallocation automatically.
Object-Oriented
Everything in Java is an object, following principles of inheritance, polymorphism, and encapsulation.
Your First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Variables and Data Types
public class VariablesExample {
public static void main(String[] args) {
// Primitive data types
int age = 25;
double price = 99.99;
char grade = 'A';
boolean isJavaFun = true;
// Reference data type
String name = "John Doe";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Price: $" + price);
}
}Change variable values and see the output:
Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code.
Four Pillars of OOP
Encapsulation
Bundling data and methods that operate on that data within a single unit (class).
Inheritance
Creating new classes based on existing classes to reuse code and establish relationships.
Polymorphism
Ability of objects to take many forms – same method behaves differently based on the object.
Abstraction
Hiding implementation details and showing only essential features to the user.
Java Memory Management
public class Car {
// Attributes (Encapsulation)
private String brand;
private double speed;
// Constructor
public Car(String brand) {
this.brand = brand;
this.speed = 0;
}
// Methods
public void accelerate(double amount) {
this.speed += amount;
System.out.println("Accelerating! Speed: " + speed);
}
public void brake(double amount) {
this.speed = Math.max(0, speed - amount);
System.out.println("Braking! Speed: " + speed);
}
// Getters and Setters (Encapsulation)
public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; }
}Vehicle v = new Car();
if (v instanceof Car) {
System.out.print("Car");
} else if (v instanceof Vehicle) {
System.out.print("Vehicle");
}Collections Framework
The Java Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data.
Common Collection Types
List
Ordered collection that allows duplicates. Elements can be accessed by index.
ArrayList<String>, LinkedList<Integer>Set
Collection that contains no duplicate elements. Unordered by default.
HashSet<String>, TreeSet<Integer>Map
Object that maps keys to values. Cannot contain duplicate keys.
HashMap<String, Integer>, TreeMap<Integer, String>import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
// List Example
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Set Example
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(1); // Duplicate, won't be added
// Map Example
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
// Iterating through collections
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}Streams and Lambda Expressions (Java 8+)
import java.util.*;
import java.util.stream.*;
public class StreamsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// Filter even numbers and square them
List<Integer> result = numbers.stream()
.filter(n -> n % 2 == 0) // Lambda expression
.map(n -> n * n) // Square each number
.collect(Collectors.toList());
System.out.println("Result: " + result);
// Sum all numbers
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum: " + sum);
}
}Try different stream operations on a list of numbers:
Advanced Java Topics
Explore advanced Java concepts including multithreading, exception handling, design patterns, and modern Java features.
Multithreading
public class ThreadExample {
public static void main(String[] args) {
// Create threads
Thread thread1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start threads
thread1.start();
thread2.start();
}
}Exception Handling
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
System.out.println("Exception details: " + e.getMessage());
} finally {
System.out.println("This always executes");
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
}Modern Java Features
Records (Java 16)
Immutable data classes with automatically generated methods.
Pattern Matching (Java 21)
Simplifies conditional extraction of data from objects.
Virtual Threads (Java 21)
Lightweight threads for high-throughput concurrent applications.
