# Java Concepts

### 1. Object-Oriented Programming Concepts

#### Inheritance

- **Definition**: Mechanism where a class inherits properties and behaviors from another class
- **Syntax**: `public class Child extends Parent { }`
- **Types**: Single, Multilevel, Hierarchical
- **`super` keyword**: Refers to parent class objects/constructors
- **Method Overriding**: Child classes can provide specific implementation of methods

#### Encapsulation

- **Definition**: Bundling data and methods that operate on the data within a single unit
- **Implementation**: Using private fields with public getters/setters
- **Benefits**: Hides implementation details, controls access, reduces code coupling

```java
public class Account {
private double balance;

public double getBalance() {
return balance;
}

public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}

```

#### Polymorphism

- **Definition**: Ability of objects to take different forms
- **Types**:
  - **Compile-time (Method Overloading)**: Multiple methods with same name but different parameters
  - **Runtime (Method Overriding)**: Subclass implementing parent class method
- **Example**:

```java
class Animal {
void makeSound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
@Override
void makeSound() { System.out.println("Bark"); }
}

```

#### Abstraction

- **Definition**: Hiding implementation details, showing only functionality
- **Implementation**: Through abstract classes and interfaces
- **Abstract Classes**: Can have both concrete and abstract methods
- **Interfaces**: Collection of abstract methods (default/static methods allowed in Java 8+)

```java
abstract class Vehicle {
abstract void start();
void stop() { System.out.println("Stopping"); }
}

interface Flyable {
void fly();
default void land() { System.out.println("Landing"); }
}

```

### 2. Java Syntax and Language Features

#### Basic Structure

```java
package com.example;

import java.util.List;

public class MyClass {
// Fields
private int number;

// Constructor
public MyClass(int number) {
this.number = number;
}

// Methods
public void doSomething() {
// Method body
}

// Main method
public static void main(String[] args) {
// Program execution starts here
}
}

```

#### Access Modifiers

- **public**: Accessible from anywhere
- **protected**: Accessible within package and by subclasses
- **default (no modifier)**: Accessible only within package
- **private**: Accessible only within class

#### Non-Access Modifiers

- **static**: Belongs to class rather than instance
- **final**: Cannot be extended (class), overridden (method), or changed (variable)
- **abstract**: Cannot be instantiated (class), must be implemented (method)
- **synchronized**: Controls thread access to method/block
- **volatile**: Variable value always read from main memory

### 3. Data Types, Variables, and Operators

#### Primitive Data Types

| Type    | Size    | Range                                    | Default |
| ------- | ------- | ---------------------------------------- | ------- |
| byte    | 8 bits  | -128 to 127                             | 0       |
| short   | 16 bits | -32,768 to 32,767                       | 0       |
| int     | 32 bits | -2<sup>31</sup> to 2<sup>31</sup>-1     | 0       |
| long    | 64 bits | -2<sup>63</sup> to 2<sup>63</sup>-1     | 0L      |
| float   | 32 bits | ~3.40282347 x 10<sup>38</sup>           | 0.0f    |
| double  | 64 bits | ~1.79769313486231570 x 10<sup>308</sup> | 0.0d    |
| char    | 16 bits | 0 to 65,535                              | '\u0000' |
| boolean | 1 bit   | true/false                               | false   |

#### Reference Types

- **Classes**: `String`, custom classes
- **Arrays**: `int[]`, `String[]`
- **Interfaces**: Collections interfaces
- **Wrapper Classes**: `Integer`, `Boolean`, etc.

#### Variable Declaration

```java
// Primitive types
int count = 10;
double price = 23.45;

// Reference types
String name = "John";
Date today = new Date();

// Constants
final double PI = 3.14159;

```

#### Operators

- **Arithmetic**: `+`, `-`, `*`, `/`, `%`, `++`, `--`
- **Relational**: `==`, `!=`, `>`, `<`, `>=`, `<=`
- **Logical**: `&&`, `||`, `!`
- **Bitwise**: `&`, `|`, `^`, `~`, `<<`, `>>`, `>>>`
- **Assignment**: `=`, `+=`, `-=`, `*=`, `/=`, etc.
- **Ternary**: `condition ? expr1 : expr2`
- **instanceof**: Tests if object is instance of class/interface

### 4. Control Flow Statements

#### Conditional Statements

```java
// if-else
if (condition) {
// code block
} else if (anotherCondition) {
// code block
} else {
// code block
}

// switch
switch (variable) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}

// Enhanced switch (Java 14+)
switch (variable) {
case value1 -> // code or expression;
case value2 -> // code or expression;
default -> // code or expression;
}

```

#### Loops

```java
// for loop
for (int i = 0; i < 10; i++) {
// code block
}

// enhanced for loop (for-each)
for (String item : itemList) {
// code block
}

// while loop
while (condition) {
// code block
}

// do-while loop
do {
// code block
} while (condition);

```

#### Control Statements

- **break**: Exits loop or switch
- **continue**: Skips to next iteration
- **return**: Exits method, optionally returning value
- **yield**: Returns value from switch expression (Java 14+)

### 5. Exception Handling

#### Exception Hierarchy

- **Throwable**: Base class for all exceptions
  - **Error**: Serious problems, not typically caught
  - **Exception**: Base for checked exceptions
          - **RuntimeException**: Base for unchecked exceptions

#### Try-Catch-Finally

```java
try {
// code that might throw exception
} catch (ExceptionType1 e1) {
// handle exception type 1
} catch (ExceptionType2 | ExceptionType3 e2) {
// handle multiple exception types
} finally {
// always executed code
}

```

#### Try-With-Resources

```java
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// code that uses resource
// resource automatically closed
}

```

#### Throwing Exceptions

```java
if (value < 0) {
throw new IllegalArgumentException("Value cannot be negative");
}

```

#### Creating Custom Exceptions

```java
public class CustomException extends Exception {
public CustomException() { super(); }
public CustomException(String message) { super(message); }
public CustomException(String message, Throwable cause) { super(message, cause); }
}

```

#### Checked vs. Unchecked Exceptions

- **Checked**: Must be caught or declared (IOException, SQLException)
- **Unchecked**: Not required to be caught (RuntimeException and subclasses)

### 6. Java Collections Framework

#### Main Interfaces

- **Collection**: Root interface
  - **List**: Ordered collection (allows duplicates)
  - **Set**: No duplicates
  - **Queue**: Typically FIFO order
- **Map**: Key-value pairs

#### Common Implementations

- **Lists**:
  - `ArrayList`: Dynamic array, fast random access
  - `LinkedList`: Fast insertions/deletions
  - `Vector`: Synchronized version of ArrayList
- **Sets**:
  - `HashSet`: Fast operations, no order guarantee
  - `LinkedHashSet`: Preserves insertion order
  - `TreeSet`: Sorted set (implements SortedSet)
- **Maps**:
  - `HashMap`: Fast operations, no order guarantee
  - `LinkedHashMap`: Preserves insertion order
  - `TreeMap`: Sorted by keys (implements SortedMap)
  - `Hashtable`: Synchronized version of HashMap
- **Queues**:
  - `ArrayDeque`: Resizable array implementation
  - `PriorityQueue`: Elements processed by priority

#### Usage Examples

```java
// ArrayList
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.remove(0);
String first = names.get(0);

// HashMap
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
int aliceAge = ages.get("Alice");
boolean containsBob = ages.containsKey("Bob");

// HashSet
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Alice"); // Ignored (duplicate)
boolean hasAlice = uniqueNames.contains("Alice");

```

### 7. Generics

#### Basic Syntax

```java
// Generic class
public class Box<T> {
private T value;

public void set(T value) { this.value = value; }
public T get() { return value; }
}

// Usage
Box<Integer> intBox = new Box<>();
intBox.set(10);
Integer value = intBox.get();

```

#### Wildcards

```java
// Unknown type (?)
void processElements(List<?> elements) {
// Can read but not write elements
}

// Upper bounded wildcard
void addNumbers(List<? extends Number> numbers) {
// Can read elements knowing they are at least Number
}

// Lower bounded wildcard
void addIntegers(List<? super Integer> integers) {
integers.add(10); // Can write Integers
}

```

#### Type Parameters

- **Type Parameter Naming Conventions**:
  - `E`: Element
  - `K`: Key
  - `V`: Value
  - `N`: Number
  - `T`: Type
  - `S`, `U`, `V`, etc.: Additional types

#### Type Erasure

- During compilation, generic type information is removed ("erased")
- Runtime doesn't have access to generic type information

### 8. Functional Interfaces and Lambda Expressions

#### Functional Interfaces

- Interface with exactly one abstract method
- Annotated with `@FunctionalInterface`
- Common functional interfaces:
  - `Predicate<T>`: Takes T, returns boolean (`boolean test(T t)`)
  - `Consumer<T>`: Takes T, returns void (`void accept(T t)`)
  - `Function<T,R>`: Takes T, returns R (`R apply(T t)`)
  - `Supplier<T>`: Takes nothing, returns T (`T get()`)
  - `BinaryOperator<T>`: Takes two T, returns T (`T apply(T t1, T t2)`)

#### Lambda Expressions

```java
// Basic syntax
(parameters) -> expression
(parameters) -> { statements; }

// Examples
Predicate<String> isEmpty = s -> s.isEmpty();
Consumer<String> printer = s -> System.out.println(s);
Function<String, Integer> lengthFinder = s -> s.length();
Supplier<Double> random = () -> Math.random();
BinaryOperator<Integer> sum = (a, b) -> a + b;

```

#### Method References

```java
// Static method
Function<String, Integer> parseInt = Integer::parseInt;

// Instance method of specific object
Consumer<String> printer = System.out::println;

// Instance method of arbitrary object
Function<String, Integer> length = String::length;

// Constructor
Supplier<List<String>> listSupplier = ArrayList::new;

```

### 9. Streams API

#### Creating Streams

```java
// From collection
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();

// From array
String[] array = {"a", "b", "c"};
Stream<String> stream = Arrays.stream(array);

// Generate/iterate
Stream<Integer> numbers = Stream.iterate(0, n -> n + 1).limit(10);
Stream<Double> randoms = Stream.generate(Math::random).limit(5);

```

#### Common Operations

- **Intermediate Operations** (return a stream):
  - `filter(Predicate)`: Filters elements
  - `map(Function)`: Transforms elements
  - `flatMap(Function)`: Transforms and flattens
  - `sorted()`: Sorts elements
  - `distinct()`: Removes duplicates
  - `limit(n)`: Limits size
  - `skip(n)`: Skips elements
- **Terminal Operations** (produce a result):
  - `forEach(Consumer)`: Processes each element
  - `collect(Collector)`: Gathers elements
  - `reduce(BinaryOperator)`: Reduces to single value
  - `count()`: Counts elements
  - `anyMatch(Predicate)`: Tests if any match
  - `allMatch(Predicate)`: Tests if all match
  - `noneMatch(Predicate)`: Tests if none match
  - `findFirst()`, `findAny()`: Finds elements

#### Example

```java
List<String> names = Arrays.asList("John", "Jane", "Jack", "James");

List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());

```

### 10. Multithreading and Concurrency

#### Thread Creation

```java
// Extending Thread
class MyThread extends Thread {
public void run() {
// Code to execute in thread
}
}
MyThread thread = new MyThread();
thread.start();

// Implementing Runnable
class MyRunnable implements Runnable {
public void run() {
// Code to execute in thread
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();

// Lambda expression
Thread thread = new Thread(() -> {
// Code to execute in thread
});
thread.start();

```

#### Thread Lifecycle

- **New**: Created but not started
- **Runnable**: Started, waiting for scheduler
- **Blocked**: Waiting for monitor lock
- **Waiting**: Called wait() without timeout
- **Timed Waiting**: Called sleep() or wait() with timeout
- **Terminated**: Completed execution

#### Thread Synchronization

```java
// Synchronized method
synchronized void method() {
// Thread-safe code
}

// Synchronized block
synchronized (lockObject) {
// Thread-safe code
}

// Lock interface
Lock lock = new ReentrantLock();
lock.lock();
try {
// Critical section
} finally {
lock.unlock();
}

```

#### Concurrent Collections

- **ConcurrentHashMap**: Thread-safe HashMap
- **CopyOnWriteArrayList**: Thread-safe ArrayList
- **BlockingQueue**: Queue with blocking operations

#### Thread Pools (ExecutorService)

```java
// Fixed thread pool
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// Task to execute
});
executor.shutdown();

// CompletableFuture
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Async computation
return "Result";
});
future.thenAccept(System.out::println);

```

#### Atomic Variables

```java
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // Thread-safe increment

```

#### Thread Communication

- **wait()**: Causes thread to wait until notify/notifyAll
- **notify()**: Wakes up one waiting thread
- **notifyAll()**: Wakes up all waiting threads
- **join()**: Waits for thread to die

## Original Outline

### 1. Object-Oriented Programming (OOP) in Java

- Encapsulation (Access Modifiers: private, protected, public, default)
- Abstraction (abstract classes, interfaces, default methods in interfaces)
- Inheritance (extends, method overriding, super keyword, constructor chaining)
- Polymorphism (Compile-time vs. Runtime, method overloading vs. method overriding)
- Composition vs. Inheritance (Why favor composition over inheritance?)
- SOLID Principles (How they apply in Java)
- JavaBeans and POJOs (Plain Old Java Objects)

### 2. Java Data Types and Memory Management

- Primitive vs. Reference Types
- Wrapper classes (Integer, Double, Boolean, etc.)
- String handling (String, StringBuilder, StringBuffer, immutability)
- Autoboxing and Unboxing
- Memory Allocation (Heap vs. Stack)
- Garbage Collection (How it works, finalize(), weak references, types of GC algorithms)

### 3. Java Collections Framework (JCF)

- List Interface (ArrayList, LinkedList, Vector, Stack)
- Set Interface (HashSet, TreeSet, LinkedHashSet)
- Map Interface (HashMap, TreeMap, LinkedHashMap, Hashtable)
- Queue Interface (PriorityQueue, Deque, ArrayDeque)
- Concurrent Collections (ConcurrentHashMap, CopyOnWriteArrayList)
- Sorting and Searching in Collections (Comparable vs. Comparator)
- Big-O Complexity of Collection Operations
- Immutable Collections (List.of(), Set.of(), Map.of())

### 4. Exception Handling

- Checked vs. Unchecked Exceptions
- Custom Exceptions
- Try-Catch-Finally vs. Try-With-Resources (AutoCloseable)
- Throw vs. Throws
- Multi-catch blocks (catch (IOException | SQLException e))
- Best Practices for Exception Handling (Avoiding Generic Exceptions)

### 5. Java Multithreading and Concurrency

- Thread Lifecycle
- Creating Threads (Thread vs. Runnable, Callable, Future)
- Synchronization (synchronized keyword, locks, ReentrantLock, wait(), notify())
- Thread Safety and Shared Resource Handling
- Executors and Thread Pools (ExecutorService, ScheduledExecutorService)
- Atomic Variables (AtomicInteger, AtomicBoolean)
- Fork-Join Framework
- Deadlocks, Race Conditions, and Livelocks

### 6. Java Streams and Functional Programming

- Lambda Expressions ((a, b) -> a + b)
- Method References (Class::methodName)
- Functional Interfaces (Predicate, Consumer, Supplier, Function, BiFunction)
- Streams API (Intermediate vs. Terminal Operations)
- Stream Processing (map(), filter(), reduce(), collect())
- Parallel Streams (parallelStream())
- Optional Class (Optional<T>, avoiding null)

### 7. Java Input/Output (I/O) and Serialization

- Byte Streams vs. Character Streams (InputStream, OutputStream, Reader, Writer)
- File Handling (File, Files, BufferedReader, BufferedWriter)
- Object Serialization (Serializable, transient keyword)
- New I/O (NIO) (Path, Files, ByteBuffer, Channels)
- Memory-Mapped Files
- Java 11+ Features (Files.writeString(), Files.readString())

### 8. Java 8+ Features

- Default and Static Methods in Interfaces
- Optional Class
- New Date and Time API (LocalDate, LocalTime, LocalDateTime, ZonedDateTime)
- CompletableFuture (thenApply(), thenAccept(), exceptionally())
- New Collection Methods (List.of(), Set.of(), Map.of())
- Records (Java 14+)
- Pattern Matching (Java 17+)
- Sealed Classes (Java 17+)

### 9. Java Reflection and Dynamic Class Loading

- Getting Class Information (.class, Class.forName())
- Accessing Private Fields and Methods
- Dynamic Proxy and InvocationHandler
- Annotations and Annotation Processing

### 10. Java Networking (Sockets, HTTP)

- Java Sockets (ServerSocket, Socket)
- URL and HttpURLConnection
- HTTP Clients (Java 11 HttpClient)
- Multithreaded Server Applications

### 11. Java Security Basics

- Encryption and Hashing (AES, SHA, RSA)
- Java Cryptography API (MessageDigest, Cipher)
- Secure Random Numbers (SecureRandom)
- Security Manager (doPrivileged())
- Understanding Java Classloaders and Security Policies

### 12. Java Virtual Machine (JVM) Internals

- JVM Architecture (ClassLoader, Method Area, Heap, Stack, Execution Engine, Garbage Collector)
- Class Loading (ClassLoader, Bootstrap, Extensions, Application ClassLoader)
- JIT Compilation (Just-In-Time Compiler)
- Garbage Collection Algorithms (G1, ZGC, Epsilon GC)
- JVM Performance Tuning (-Xms, -Xmx, -XX:+UseG1GC)