0% found this document useful (0 votes)
0 views44 pages

Java Programming Full Coursee

This document outlines a comprehensive Java programming course designed for beginners to advanced learners, covering topics such as Java basics, object-oriented programming, exception handling, and Spring Boot. It includes 14 chapters with over 100 code examples and best practices. The course aims to equip learners with the skills necessary to become professional Java developers.

Uploaded by

a13syed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views44 pages

Java Programming Full Coursee

This document outlines a comprehensive Java programming course designed for beginners to advanced learners, covering topics such as Java basics, object-oriented programming, exception handling, and Spring Boot. It includes 14 chapters with over 100 code examples and best practices. The course aims to equip learners with the skills necessary to become professional Java developers.

Uploaded by

a13syed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA

PROGRAMMING
Complete Course

From Zero to Professional Developer

Beginner | Intermediate | Advanced

Java 17+ | OOP | Collections | Generics | Streams | Concurrency | Spring Boot

14 Chapters | 100+ Code Examples | Best Practices

Java Programming Full Course | Page 1


Table of Contents

Chapter 1 — Introduction to Java


› History & Features
› JDK / JRE / JVM
› First Program
› Compile & Run

Chapter 2 — Java Basics


› Primitive Types
› Variables & Constants
› Operators
› Type Casting
› Scanner Input

Chapter 3 — Control Flow


› if/else/switch
› for/while/do-while
› break & continue

Chapter 4 — Arrays & Strings


› 1D & 2D Arrays
› String Methods
› StringBuilder
› Formatting

Chapter 5 — Object-Oriented Programming


› Classes & Objects
› Encapsulation
› Inheritance
› Polymorphism
› Abstraction

Chapter 6 — Interfaces & Abstract Classes


› Interface Syntax
› Default/Static Methods
› Abstract Classes

Chapter 7 — Exception Handling


› try/catch/finally
› Custom Exceptions
› Checked vs Unchecked
› try-with-resources

Chapter 8 — Collections Framework


› List
› Set
› Map
› Queue & PriorityQueue

Chapter 9 — Generics
› Generic Classes
› Generic Methods

Java Programming Full Course | Page 2


› Wildcards

Chapter 10 — Java 8+ Features


› Lambdas
› Stream API
› Optional
› Date/Time API

Chapter 11 — File I/O & NIO


› Classic I/O
› NIO.2 Paths
› Serialization

Chapter 12 — Concurrency
› Threads
› Synchronization
› ExecutorService
› CompletableFuture

Chapter 13 — Design Patterns


› Singleton
› Builder
› Observer
› Strategy

Chapter 14 — Spring Boot


› Setup
› REST Controllers
› JPA Entities
› Repository

Java Programming Full Course | Page 3


Chapter 1

Introduction to Java

Java is a high-level, class-based, object-oriented programming language created by James Gosling at Sun
Microsystems and released in 1995. Today Java powers billions of devices — from Android smartphones
to large-scale enterprise banking systems.

1.1 History & Key Features


Java's central motto is "Write Once, Run Anywhere" . Source code is compiled to platform-neutral
bytecode that any JVM can execute.

<b>Feature</b> <b>Description</b>

Platform Independent Compiled to bytecode; runs on any OS with a JVM.

Object-Oriented Everything modelled around objects and classes.

Strongly Typed Every variable must be declared with a type.

Garbage Collection Automatic memory management — no manual free().

Multithreaded Built-in thread support via [Link].

Secure No raw pointers; bytecode verifier before execution.

Rich API Thousands of ready-to-use classes in the standard library.

1.2 JDK, JRE, and JVM


JVM — executes bytecode, handles GC, security, threads.
JRE — JVM plus standard class libraries. Used to run Java apps.
JDK — JRE plus javac, jdb, javadoc. Used to develop Java apps.

Tip: Which do I need?

Install the JDK — it contains everything. Download from [Link] (free OpenJDK builds).

1.3 Your First Java Program

// [Link]

public class HelloWorld {

public static void main(String[] args) {

Java Programming Full Course | Page 4


[Link]("Hello, World!");

• public class HelloWorld — class name must match the filename


• public static void main(String[] args) — JVM entry point
• [Link](...) — prints text + newline to stdout

1.4 Compile & Run

// Terminal

javac [Link] # produces [Link]

java HelloWorld # Output: Hello, World!

Note: IDE Tip

IntelliJ IDEA Community Edition (free) and VS Code + Java Extension Pack are excellent free IDEs.

Java Programming Full Course | Page 5


Chapter 2

Java Basics

2.1 Primitive Data Types


<b>Type</b> <b>Size</b><b>Default</b><b>Example</b>

byte 8-bit 0 byte b = 127;

short 16-bit 0 short s = 32000;

int 32-bit 0 int i = 42;

long 64-bit 0L long l = 9876543210L;

float 32-bit 0.0f float f = 3.14f;

double 64-bit 0.0d double d = 3.14159;

char 16-bit '\u0000' char c = 'A';

boolean 1-bit false boolean flag = true;

2.2 Variables & Constants

// Variables, Constants, var

int age = 25;

String name = "Alice";

double pi = 3.14159;

final int MAX = 100; // constant

var message = "Hello"; // Java 10+, inferred as String

var count = 0; // inferred as int

2.3 Operators

Java Programming Full Course | Page 6


<b>Category</b> <b>Operators</b> <b>Purpose</b>

Arithmetic + - * / % ++ -- Math operations

Relational == != > < >= <= Comparison -> boolean

Logical && || ! Boolean logic

Assignment = += -= *= /= Assign values

Ternary cond ? a : b Inline if/else

instanceof obj instanceof T Type check

2.4 Type Casting

// Widening and Narrowing

// Widening (implicit, safe)

int i = 100;

double d = i; // 100.0

// Narrowing (explicit, may lose data)

double pi = 3.99;

int trunc = (int) pi; // 3

// String conversions

int n = [Link]("42");

String s = [Link](42);

2.5 Scanner Input

// Reading User Input

import [Link];

Java Programming Full Course | Page 7


Scanner sc = new Scanner([Link]);

[Link]("Enter name: ");

String name = [Link]();

[Link]("Enter age: ");

int age = [Link]();

[Link]();

Warning: Always close Scanner

Call [Link]() to release the resource, or wrap in try-with-resources.

Java Programming Full Course | Page 8


Chapter 3

Control Flow

3.1 if / else if / else

// Grading Example

int score = 85;

if (score >= 90) [Link]("A");

else if (score >= 80) [Link]("B");

else if (score >= 70) [Link]("C");

else [Link]("F");

3.2 switch

// Traditional and Enhanced Switch

// Traditional

switch (day) {

case "MON": case "FRI": [Link]("Workday"); break;

case "SAT": case "SUN": [Link]("Weekend"); break;

default: [Link]("Midweek");

// Enhanced switch expression (Java 14+)

String type = switch (day) {

Java Programming Full Course | Page 9


case "SAT","SUN" -> "Weekend";

default -> "Weekday";

};

3.3 Loops

// for, while, do-while

// for loop

for (int i = 0; i < 5; i++) [Link](i);

// enhanced for-each

int[] nums = {10, 20, 30};

for (int n : nums) [Link](n);

// while loop

int x = 0;

while (x < 5) { [Link](x); x++; }

// do-while — runs at least once

int y = 0;

do { [Link](y); y++; } while (y < 3);

3.4 break and continue

// break and continue

// break — exit loop

Java Programming Full Course | Page 10


for (int i=0;i<10;i++) { if(i==5) break; [Link](i+" "); }

// prints: 0 1 2 3 4

// continue — skip iteration

for (int i=0;i<10;i++) {

if(i%2==0) continue;

[Link](i+" ");

// prints: 1 3 5 7 9

Java Programming Full Course | Page 11


Chapter 4

Arrays & Strings

4.1 Arrays

// 1D and 2D Arrays

int[] arr = new int[5]; // all zeros

int[] arr2 = {10, 20, 30, 40, 50}; // literal

arr2[0] = 100;

[Link]([Link]); // 5

// 2D array

int[][] grid = {{1,2,3},{4,5,6},{7,8,9}};

[Link](grid[1][2]); // 6

// Arrays utility

import [Link];

[Link](arr2);

[Link]([Link](arr2));

4.2 String Methods


Strings are immutable objects. Every modification produces a new String instance.

// Common String Methods

Java Programming Full Course | Page 12


String s = " Hello, World! ";

[Link]() // 18

[Link]() // "Hello, World!"

[Link]() // " HELLO, WORLD! "

[Link]("World") // 9

[Link]("Hello") // true

[Link]("World","Java") // " Hello, Java! "

[Link](2, 7) // "Hello"

[Link](", ") // [" Hello", "World! "]

[Link]() // Java 11+ unicode trim

[Link]() // Java 11+ — true if only whitespace

4.3 StringBuilder
Use StringBuilder for repeated string building — it is mutable and avoids creating many intermediate
String objects.

// StringBuilder

StringBuilder sb = new StringBuilder();

[Link]("Hello").append(", ").append("World");

[Link](5, " Beautiful");

[Link](5, 15);

[Link]();

String result = [Link]();

4.4 String Formatting

Java Programming Full Course | Page 13


// Format and Text Blocks

String msg = [Link]("%-10s %3d %.2f", "Alice", 30, 3.875);

[Link]("%-10s %3d%n", "Alice", 30);

// Text block (Java 15+)

String json = """

"name": "Alice",

"age": 30

}""";

Java Programming Full Course | Page 14


Chapter 5

Object-Oriented Programming

5.1 Classes & Objects

// Car Class

public class Car {

private String make, model;

private int year;

private double speed;

public Car(String make, String model, int year) {

[Link]=make; [Link]=model; [Link]=year;

public void accelerate(double amt) { speed += amt; }

public void brake(double amt) { speed = [Link](0, speed-amt); }

@Override

public String toString() {

return year+" "+make+" "+model+" @ "+speed+"km/h";

Java Programming Full Course | Page 15


Car c = new Car("Toyota","Camry",2023);

[Link](60); [Link](20);

[Link](c); // 2023 Toyota Camry @ 40.0km/h

5.2 Encapsulation
Bundle data (fields) and behaviour (methods) in a class. Use private fields with public getters/setters to
control access.

// Getters, Setters, Validation

public String getMake() { return make; }

public double getSpeed() { return speed; }

public void setYear(int y) {

if (y >= 1886 && y <= 2100) [Link] = y;

else throw new IllegalArgumentException("Bad year");

5.3 Inheritance

// ElectricCar extends Car

public class ElectricCar extends Car {

private int battery = 100;

public ElectricCar(String make, String model, int year) {

super(make, model, year);

Java Programming Full Course | Page 16


public void charge() { battery = 100; }

@Override public String toString() {

return [Link]() + " [Bat:"+battery+"%]";

5.4 Polymorphism

// Runtime Polymorphism

Car[] fleet = { new Car("Ford","Focus",2020),

new ElectricCar("Tesla","Model 3",2023) };

for (Car c : fleet) {

[Link](c); // correct toString() called

Tip: Prefer Composition over Inheritance

Ask 'IS-A or HAS-A?' before inheriting. Composition is more flexible and avoids deep class hierarchies.

Java Programming Full Course | Page 17


Chapter 6

Interfaces & Abstract Classes

6.1 Interfaces

// Interface with Default Method

public interface Drawable {

void draw(); // abstract (must implement)

default void print() { // concrete (can override)

[Link]("Printing: "+getClass().getSimpleName());

static Drawable noOp() { return () -> {}; }

public interface Resizable {

void resize(double factor);

// Multiple interface implementation

public class Circle implements Drawable, Resizable {

private double radius;

public Circle(double r) { [Link] = r; }

@Override public void draw() { [Link]("O r="+radius); }

Java Programming Full Course | Page 18


@Override public void resize(double f) { radius *= f; }

6.2 Abstract Classes

// Abstract Shape Hierarchy

public abstract class Shape {

protected String color;

public Shape(String color) { [Link] = color; }

public abstract double area();

public abstract double perimeter();

public void describe() {

[Link]("%s area=%.2f%n", color, area());

public class Rectangle extends Shape {

private double w, h;

public Rectangle(String c, double w, double h) {

super(c); this.w=w; this.h=h;

@Override public double area() { return w*h; }

Java Programming Full Course | Page 19


@Override public double perimeter() { return 2*(w+h); }

Note: Interface vs Abstract Class

Interface: contract for unrelated classes; no shared state.

Abstract class: shared fields or behaviour; use when IS-A relationship is clear.

Java Programming Full Course | Page 20


Chapter 7

Exception Handling

All exceptions extend Throwable . Errors (JVM problems) should not be caught. Exception splits into
checked (must handle) and unchecked (RuntimeException).

7.1 try / catch / finally

// Basic Exception Handling

public int divide(int a, int b) {

try {

return a / b;

} catch (ArithmeticException e) {

[Link]("Divide by zero: " + [Link]());

return 0;

} finally {

[Link]("always runs");

// Multi-catch (Java 7+)

try {

int[] arr = new int[5];

arr[10] = [Link]("abc");

} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {

Java Programming Full Course | Page 21


[Link]("Caught: " + e);

7.2 Custom Exceptions

// Custom Checked Exception

public class InsufficientFundsException extends Exception {

private final double shortfall;

public InsufficientFundsException(double shortfall) {

super("Need " + shortfall + " more");

[Link] = shortfall;

public double getShortfall() { return shortfall; }

public void withdraw(double amount) throws InsufficientFundsException {

if (amount > balance) throw new InsufficientFundsException(amount-balance);

balance -= amount;

7.3 try-with-resources
Automatically calls close() on any AutoCloseable resource — no finally needed.

// try-with-resources

try (var reader = new BufferedReader(new FileReader("[Link]"))) {

[Link]().forEach([Link]::println);

Java Programming Full Course | Page 22


} catch (IOException e) {

[Link]();

} // reader closed automatically

Java Programming Full Course | Page 23


Chapter 8

Collections Framework

The Java Collections Framework provides unified interfaces and implementations for groups of objects.
List , Set , Map , and Queue are the main interfaces.

8.1 List — ArrayList & LinkedList

// List Operations

List<String> list = new ArrayList<>();

[Link]("Apple"); [Link]("Cherry");

[Link](1, "Banana"); // insert at index

[Link]("Banana");

[Link](0); // "Apple"

[Link](list);

// LinkedList as Deque

LinkedList<Integer> deque = new LinkedList<>();

[Link](1); [Link](3);

[Link](); [Link]();

8.2 Set — HashSet & TreeSet

// Set Operations

Set<String> set = new HashSet<>();

[Link]("A"); [Link]("B"); [Link]("A"); // 2 elements

Java Programming Full Course | Page 24


// TreeSet — sorted

Set<Integer> sorted = new TreeSet<>([Link](5,2,8,1,3));

[Link](sorted); // [1, 2, 3, 5, 8]

8.3 Map — HashMap & TreeMap

// Map Operations

Map<String,Integer> scores = new HashMap<>();

[Link]("Alice",95); [Link]("Bob",87);

[Link]("Dave",0); // 0

[Link]("Alice",50); // not replaced

[Link]("Eve", k -> [Link]()); // 3

for (var entry : [Link]())

[Link]([Link]()+" -> "+[Link]());

8.4 Queue & PriorityQueue

// Queue and PriorityQueue

Queue<String> q = new LinkedList<>();

[Link]("Task1"); [Link]("Task2");

[Link](); // "Task1" (no remove)

[Link](); // "Task1" (removes)

PriorityQueue<Integer> pq = new PriorityQueue<>();

[Link]([Link](5,1,3,2,4));

Java Programming Full Course | Page 25


while (![Link]()) [Link]([Link]()+" "); // 1 2 3 4 5

Java Programming Full Course | Page 26


Chapter 9

Generics

Generics provide compile-time type safety and eliminate explicit casts. They allow classes and methods to
operate on types specified as parameters.

9.1 Generic Classes

// Generic Pair Class

public class Pair<A, B> {

private final A first;

private final B second;

public Pair(A first, B second) {

[Link] = first; [Link] = second;

public A getFirst() { return first; }

public B getSecond() { return second; }

@Override public String toString() {

return "(" + first + ", " + second + ")";

var p = new Pair<>("age", 30);

[Link](p); // (age, 30)

Java Programming Full Course | Page 27


9.2 Generic Methods & Bounded Types

// Bounded Type Parameter

public static <T extends Comparable<T>> T max(T a, T b) {

return [Link](b) >= 0 ? a : b;

max(3, 7); // 7

max("apple","banana"); // banana

9.3 Wildcards

// Wildcards

// Unbounded

public void printList(List<?> list) { [Link]([Link]::println); }

// Upper bounded — can read as Number

public double sum(List<? extends Number> list) {

return [Link]().mapToDouble(Number::doubleValue).sum();

// Lower bounded — can add Integer

public void addNums(List<? super Integer> list) {

[Link](1); [Link](2);

Java Programming Full Course | Page 28


Chapter 10

Java 8+ Features

10.1 Lambda Expressions


Lambdas implement functional interfaces (single abstract method). Syntax: (params) -> expression or {
block }

// Lambda Examples

Runnable r = () -> [Link]("Running!");

Comparator<String> byLen = (a,b) -> [Link]()-[Link]();

Predicate<Integer> isEven = n -> n % 2 == 0;

Function<String,Integer> len = String::length; // method ref

Consumer<String> print = [Link]::println;

Supplier<List<String>> factory = ArrayList::new;

List<String> names = [Link]("Charlie","Alice","Bob");

[Link]()

.filter(n -> [Link]("A"))

.sorted()

.forEach([Link]::println);

10.2 Stream API

// Stream Pipeline

List<Integer> nums = [Link](1,2,3,4,5,6,7,8,9,10);

Java Programming Full Course | Page 29


int sumOfSquaresOfEvens = [Link]()

.filter(n -> n%2==0)

.mapToInt(n -> n*n)

.sum(); // 220

Map<Integer,List<String>> byLen = [Link]("hi","hello","hey")

.collect([Link](String::length));

// flatMap

List<List<Integer>> nested = [Link]([Link](1,2), [Link](3,4));

List<Integer> flat = [Link]()

.flatMap(Collection::stream)

.collect([Link]()); // [1,2,3,4]

10.3 Optional

// Optional Usage

Optional<String> opt = [Link](getValue());

String val = [Link]("default");

String val2 = [Link](() -> compute());

[Link]([Link]::println);

Optional<Integer> len = [Link](String::length);

String must = [Link](() -> new RuntimeException("Missing"));

Java Programming Full Course | Page 30


10.4 New Date/Time API ([Link])

// [Link] Examples

LocalDate today = [Link]();

LocalDateTime dt = [Link]();

ZonedDateTime zdt = [Link]([Link]("Asia/Kolkata"));

String fmt = [Link]([Link]("dd-MM-yyyy HH:mm"));

LocalDate next = [Link](7);

long days = [Link](today, next); // 7

Period p = [Link]([Link](1990,1,1), today);

Java Programming Full Course | Page 31


Chapter 11

File I/O & NIO

11.1 Classic [Link]

// Read and Write Files

// Write

try (var w = new BufferedWriter(new FileWriter("[Link]"))) {

[Link]("Hello, File!"); [Link]();

// Read

try (var r = new BufferedReader(new FileReader("[Link]"))) {

String line;

while ((line = [Link]()) != null) [Link](line);

11.2 NIO.2 ([Link])

// Files and Path (Java 11+)

Path p = [Link]("[Link]");

[Link](p, [Link]("line1","line2"), StandardCharsets.UTF_8);

List<String> lines = [Link](p);

Java Programming Full Course | Page 32


String content = [Link](p); // Java 11+

// Walk directory

[Link]([Link]("./src"))

.filter(f -> [Link]().endsWith(".java"))

.forEach([Link]::println);

[Link](p, [Link]("[Link]"), StandardCopyOption.REPLACE_EXISTING);

[Link]([Link]("[Link]"));

11.3 Object Serialization

// Serialize & Deserialize

// POJO must implement Serializable

public class Person implements Serializable {

private static final long serialVersionUID = 1L;

String name; int age;

// Save

try (var oos = new ObjectOutputStream(new FileOutputStream("[Link]"))) {

[Link](new Person());

// Load

Java Programming Full Course | Page 33


try (var ois = new ObjectInputStream(new FileInputStream("[Link]"))) {

Person p = (Person) [Link]();

Java Programming Full Course | Page 34


Chapter 12

Concurrency & Multithreading

12.1 Creating Threads

// Thread and Runnable

// Extend Thread

class Worker extends Thread {

@Override public void run() { [Link](getName()); }

new Worker().start();

// Runnable lambda (preferred)

Thread t = new Thread(() -> [Link]("Lambda thread"));

[Link]();

[Link](); // wait for t to finish

12.2 Synchronization

// Synchronized Methods

public class BankAccount {

private double balance;

public synchronized void deposit(double amt) { balance += amt; }

Java Programming Full Course | Page 35


public void withdraw(double amt) {

synchronized (this) {

if (balance >= amt) balance -= amt;

12.3 ExecutorService

// Thread Pool

ExecutorService pool = [Link](4);

for (int i=0; i<10; i++) {

final int id = i;

[Link](() -> [Link]("Task "+id));

Future<Integer> f = [Link](() -> { [Link](500); return 42; });

[Link]([Link]()); // blocks until ready

[Link]();

12.4 CompletableFuture (Java 8+)

// Async Composition

CompletableFuture<String> cf =

Java Programming Full Course | Page 36


[Link](() -> fetchData())

.thenApply(d -> process(d))

.thenApply(String::toUpperCase)

.exceptionally(ex -> "ERROR: " + [Link]());

// Combine two futures

[Link](() -> "Hello")

.thenCombine([Link](() -> " World"),

(a,b) -> a+b)

.thenAccept([Link]::println);

Java Programming Full Course | Page 37


Chapter 13

Design Patterns

Design patterns are proven solutions to recurring software design problems, grouped into Creational ,
Structural , and Behavioral categories.

13.1 Singleton (Creational)

// Double-Checked Locking Singleton

public class Config {

private static volatile Config instance;

private Config() {}

public static Config getInstance() {

if (instance == null) {

synchronized ([Link]) {

if (instance == null) instance = new Config();

return instance;

13.2 Builder (Creational)

// Builder Pattern

Java Programming Full Course | Page 38


public class Pizza {

private String size; private boolean cheese, pepperoni;

private Pizza(Builder b){size=[Link];cheese=[Link];pepperoni=[Link];}

public static class Builder {

private String size;

private boolean cheese, pepperoni;

public Builder size(String s) { size=s; return this; }

public Builder cheese() { cheese=true; return this; }

public Builder pepperoni() { pepperoni=true; return this; }

public Pizza build() { return new Pizza(this); }

Pizza p = new [Link]().size("LARGE").cheese().build();

13.3 Observer (Behavioral)

// Observer Pattern

interface Observer { void update(String event); }

class EventBus {

private final List<Observer> obs = new ArrayList<>();

public void subscribe(Observer o) { [Link](o); }

Java Programming Full Course | Page 39


public void unsubscribe(Observer o) { [Link](o); }

public void publish(String e) { [Link](o -> [Link](e)); }

EventBus bus = new EventBus();

[Link](e -> [Link]("Log: "+e));

[Link](e -> [Link]("Email: "+e));

[Link]("UserRegistered");

13.4 Strategy (Behavioral)

// Strategy Pattern

interface SortStrategy { void sort(int[] data); }

class BubbleSort implements SortStrategy { @Override public void sort(int[] d){} }

class QuickSort implements SortStrategy { @Override public void sort(int[] d){} }

class Sorter {

private SortStrategy strategy;

public Sorter(SortStrategy s) { strategy = s; }

public void sort(int[] d) { [Link](d); }

Sorter sorter = new Sorter(new QuickSort());

[Link](new int[]{5,2,8,1,9});

Java Programming Full Course | Page 40


Chapter 14

Introduction to Spring Boot

Spring Boot makes it easy to create production-grade Spring applications with minimal configuration, an
embedded Tomcat server, and auto-configuration.

14.1 Project Setup


Visit [Link] to generate a project. Select Maven, Java 17+, and add: Spring Web, Spring
Data JPA, H2 Database.

// [Link] — key starters

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId><scope>runtime</scope>

</dependency>

14.2 REST Controller

// [Link]

Java Programming Full Course | Page 41


@RestController

@RequestMapping("/api/users")

public class UserController {

private final UserService service;

public UserController(UserService service) { [Link]=service; }

@GetMapping

public List<User> all() { return [Link](); }

@GetMapping("/{id}")

public ResponseEntity<User> one(@PathVariable Long id) {

return [Link](id)

.map(ResponseEntity::ok)

.orElse([Link]().build());

@PostMapping

@ResponseStatus([Link])

public User create(@RequestBody User user) { return [Link](user); }

@DeleteMapping("/{id}")

@ResponseStatus(HttpStatus.NO_CONTENT)

public void delete(@PathVariable Long id) { [Link](id); }

Java Programming Full Course | Page 42


}

14.3 JPA Entity & Repository

// User Entity and Repository

@Entity @Table(name="users")

public class User {

@Id @GeneratedValue(strategy=[Link])

private Long id;

@Column(nullable=false) private String name;

@Column(unique=true) private String email;

// getters / setters

public interface UserRepository extends JpaRepository<User,Long> {

List<User> findByNameContainingIgnoreCase(String name);

Optional<User> findByEmail(String email);

Tip: Running the App

Add @SpringBootApplication to your main class and run it. Tomcat starts on port 8080. Change with
[Link]=8081 in [Link].

Java Programming Full Course | Page 43


Congratulations! What's Next?

Modern Java
• Records & Sealed Classes (Java 17)
• Pattern Matching & switch expressions
• Virtual Threads (Project Loom — Java 21)
• GraalVM Native Image

Frameworks
• Spring Security & OAuth2
• Spring Cloud Microservices
• Quarkus / Micronaut
• Jakarta EE

Testing
• JUnit 5 & Parameterized Tests
• Mockito for mocking
• Testcontainers (integration tests)
• AssertJ fluent assertions

Build & DevOps


• Maven / Gradle advanced
• Docker & Kubernetes
• CI/CD with GitHub Actions
• Monitoring with Spring Actuator + Prometheus

Happy Coding! Keep building!

Java Programming Full Course | Page 44

You might also like