Table of contents
- Platform Independence
- JVM vs JRE
- String Pool & String Handling
- Object-Oriented Programming: 4 Pillars
- Java Exceptions
- Java Language Features
- Threads and Synchronization
- Design Patterns
- Spring Core
- Spring Security
- Spring Data JPA
- Error Handling
- Transaction Management
- Java Collections API
- Streams API
- Functional Interfaces
- Microservices vs Monolithic Architecture
- Distributed Systems
- Immutability
Dive into essential Java concepts, from platform independence to design patterns, making this a go-to reference for your Java journey!
Platform Independence
Java's Platform Independence is achieved through bytecode, which is executed by the Java Virtual Machine (JVM). This bytecode allows Java to be platform-independent, as JVM abstracts the underlying operating system (OS) specifics.
JVM vs JRE
JVM (Java Virtual Machine): Executes Java bytecode.
JRE (Java Runtime Environment): Contains JVM and standard libraries.
String Pool & String Handling
String Pool: A memory region in the heap used to store string literals, optimizing memory use.
intern()
function: Retrieves a canonical representation for a string from the string pool.==
vs.equals()
:==
checks reference equality, while.equals()
checks for value equality.
Object-Oriented Programming: 4 Pillars
Encapsulation
Inheritance
Polymorphism
Abstraction
Java Exceptions
Superclass:
Throwable
Error vs Exception: Errors are severe issues (e.g.,
OutOfMemoryError
), while exceptions (e.g.,IOException
) are conditions that applications may handle.Checked vs Unchecked Exceptions:
Checked exceptions must be handled (e.g.,
IOException
).Unchecked exceptions (
RuntimeException
subclasses) don’t require handling.
Java Language Features
AutoBoxing: Automatic conversion between primitive types and their wrapper classes.
Java 8 Features: Lambda expressions, Stream API, Optional, Date/Time API, default methods in interfaces.
Lambda Functions: Provide concise syntax for anonymous functions, perfect for functional programming.
Indexing: Zero-based indexing for collections like arrays or lists.
Constructor in Interface: Not allowed; interfaces cannot be instantiated.
Threads and Synchronization
Example: Code for 5 Threads
class MyThread extends Thread {
private static int counter = 1;
public void run() {
System.out.println(counter++);
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new MyThread().start();
}
}
}
- Volatile vs Atomic:
volatile
ensures visibility across threads; atomic classes (e.g.,AtomicInteger
) ensure atomic operations.
Design Patterns
1. Builder Pattern:
javaCopy codepublic class Product {
private final String name;
private final int price;
private Product(Builder builder) {
this.name = builder.name;
this.price = builder.price;
}
public static class Builder {
private String name;
private int price;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setPrice(int price) {
this.price = price;
return this;
}
public Product build() {
return new Product(this);
}
}
}
2. Singleton Pattern:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Spring Core
Spring Boot: Framework for building stand-alone Spring apps with minimal configuration.
Spring Annotations:
@Qualifier
,@Value
,@Autowired
,@Component
,@Service
,@Repository
.@Controller
vs@RestController
:@Controller
returns views, while@RestController
returns JSON/XML responses.
Spring Security
OAuth: An authorization framework for third-party access via tokens.
Role-Based Access Control: Use annotations like
@PreAuthorize
for role-based security.
Spring Data JPA
Three primary interfaces:
CrudRepository
PagingAndSortingRepository
JpaRepository
Error Handling
Global Exception Handling in Controller:
javaCopy code@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Transaction Management
Transaction Propagation: Controls transactions across multiple methods (e.g., REQUIRED
, REQUIRES_NEW
).
Java Collections API
HashMap: Uses an array and linked lists/trees for storage.
HashMap vs HashTable vs ConcurrentHashMap: HashMap is unsynchronized, HashTable is synchronized, ConcurrentHashMap allows concurrent access.
List vs Set vs Map:
List: Ordered, allows duplicates.
Set: Unordered, no duplicates.
Map: Key-value pairs.
Streams API
Streams API: Abstract layer introduced in Java 8 for processing sequences.
Creating Streams: From collections, arrays, files, etc.
Streams vs Collections: Streams are for data processing, collections for data storage.
Functional Interfaces
Functional Interface: Has a single abstract method (e.g.,
Runnable
,Callable
).Default and Static Methods: Yes, interfaces can have them.
Example:
javaCopy code@FunctionalInterface
public interface MyFunctionalInterface {
void execute();
default void defaultMethod() {}
static void staticMethod() {}
}
Microservices vs Monolithic Architecture
Microservices: Small, independently deployable services.
Monolithic Architecture: Unified codebase.
Distributed Systems
CAP Theorem: Consistency, Availability, Partition Tolerance – a trade-off based on system needs.
Immutability
Making a Class Immutable
javaCopy codepublic final class ImmutableClass {
private final int value;
public ImmutableClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}