Core Concepts
OOP Principles
Encapsulation
public class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
}
Inheritance
public class Animal {
public void eat() {
System.out.println("Eating...");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Barking...");
}
}
Polymorphism
public interface Shape {
double area();
}
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle implements Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
Abstraction
public abstract class Vehicle {
abstract void start();
public void stop() {
System.out.println("Vehicle stopped");
}
}
Collections Framework
// List
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
// Set
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
// Map
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Streams API (Java 8+)
List<String> names = Arrays.asList("John", "Jane", "Bob", "Alice");
// Filter and collect
List<String> filtered = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());
// Map and reduce
int totalLength = names.stream()
.mapToInt(String::length)
.sum();
Lambda Expressions
// Before Java 8
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello");
}
};
// With Lambda
Runnable r2 = () -> System.out.println("Hello");
// With parameters
Comparator<String> comp = (s1, s2) -> s1.compareTo(s2);
Exception Handling
public void readFile(String path) {
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = reader.readLine();
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO error: " + e.getMessage());
} finally {
System.out.println("Cleanup complete");
}
}
Multithreading
// Using Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
// Using Runnable
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running");
}
}
// Usage
new MyThread().start();
new Thread(new MyRunnable()).start();
new Thread(() -> System.out.println("Lambda thread")).start();