What is Docker? Explained for Beginners with Real Examples

12:05 AM

Modern software applications are expected to run consistently across development, testing and production environments. However, one of the biggest challenges developers face is ensuring that an application behaves exactly the same everywhere.

Learn Docker from scratch with real-world examples. Understand Docker containers, images, architecture, benefits and why modern applications use Docker.

Docker was created to solve this problem. It has become one of the most popular containerization platforms used by developers, DevOps engineers and cloud-native organizations worldwide.

What is Docker?

Docker is an open-source containerization platform that allows developers to package applications and all their dependencies into lightweight units known as containers.

A Docker container contains everything required to run an application successfully:

  • Application Code
  • Required Libraries
  • Framework Dependencies
  • Runtime Environment
  • Configuration Files

Because everything is packaged together, the application behaves consistently regardless of where it is deployed.


The Problem Before Docker

Before Docker became popular, development and deployment teams frequently faced environment-related issues.

A common phrase in software development was:


It works on my machine.

An application might run perfectly on a developer's laptop but fail in production because of differences in operating systems, Java versions, libraries or database configurations.


Developer Environment

Java 21

MySQL 8

Spring Boot 3

        ↓

Production Environment

Java 17

MySQL 5.7

Spring Boot 2

Even small differences between environments could result in deployment failures.


How Docker Solves This Problem

Docker packages everything required by an application into a single container.


Application

+

Runtime

+

Dependencies

+

Configuration

=

Docker Container

The same Docker container can be deployed on any machine running Docker.


This eliminates the famous "works on my machine" problem.


What is a Container?

A container is a lightweight and isolated environment used to run applications.


You can think of a container as a packaged version of an application containing everything it needs to execute.


Docker Container

├── Application

├── Libraries

├── Dependencies

└── Runtime

Containers are lightweight because they share the host operating system kernel while remaining isolated from one another.


Real World Example

Suppose you build a Spring Boot application.

Without Docker, you may need to:


Install Java

Install Maven

Install MySQL

Configure Environment Variables

Deploy Application

With Docker:


docker run application

Everything required for execution has already been packaged inside the container.


What is a Docker Image?

A Docker Image is a read-only blueprint used to create Docker containers.

Images contain the application code, runtime and all dependencies required to run the application.


Docker Image

↓

Docker Container

↓

Running Application

Multiple containers can be created from a single image.


Docker Image vs Docker Container

Docker Image Docker Container
Blueprint Running Instance
Read Only Executable
Static Dynamic
Used to Create Containers Runs the Application

Docker Architecture

Docker uses a client-server architecture.


Developer

     |

     v

Docker Client

     |

     v

Docker Engine

     |

     v

Docker Containers

The Docker Client sends commands to the Docker Engine, which manages images and containers.


Key Docker Components

Docker Client

The interface used by developers to interact with Docker.


docker run

docker build

docker pull

Docker Engine

The core Docker service responsible for creating, running and managing containers.


Docker Hub

Docker Hub is a public registry where Docker images are stored and shared.

Popular images available on Docker Hub include:


nginx

mysql

postgres

redis

openjdk

Benefits of Docker

  • Consistent Deployments
  • Portable Applications
  • Faster Delivery
  • Efficient Resource Usage
  • Simplified DevOps Workflows
  • Easy Scalability

Docker vs Virtual Machines

Docker Virtual Machine
Lightweight Heavyweight
Shares OS Kernel Runs Separate OS
Fast Startup Slower Startup
Efficient Resource Usage Higher Resource Consumption

Common Docker Commands

Download an Image

docker pull nginx

Run a Container

docker run nginx

List Running Containers

docker ps

List Images

docker images

Use Cases of Docker

  • Spring Boot Applications
  • Microservices Architecture
  • Cloud Deployments
  • CI/CD Pipelines
  • Testing Environments
  • DevOps Automation

Why Docker Matters for Java Developers

Modern Java applications are increasingly deployed using containers.


Spring Boot Application

↓

Docker Container

↓

Kubernetes Cluster

↓

Production Environment

Docker has become a fundamental skill for backend developers working with Spring Boot and cloud-native applications.


Common Interview Questions

What is Docker?

Docker is a containerization platform used to package applications and their dependencies into portable containers.


What is a Docker Container?

A container is a lightweight isolated environment used to run an application.


What is a Docker Image?

A Docker Image is a blueprint used to create containers.


What is Docker Hub?

Docker Hub is a public image registry used to store and share Docker images.


How is Docker different from a Virtual Machine?

Docker containers share the operating system kernel while virtual machines run separate operating systems.


Best Practices

  • Use official Docker images whenever possible.
  • Keep images small and optimized.
  • Avoid storing secrets inside images.
  • Use versioned image tags.
  • Monitor container resource usage.

Frequently Asked Questions (FAQ)

Can multiple containers run on the same server?

Yes. Multiple containers can run simultaneously while remaining isolated from one another.


Is Docker free?

Docker offers both free and commercial plans.


Can Docker run Java applications?

Yes. Docker is widely used to package and deploy Java and Spring Boot applications.


Conclusion

Docker has transformed the way software is developed and deployed. By packaging applications and their dependencies into containers, Docker provides consistency, portability and scalability across different environments. Understanding Docker is becoming an essential skill for Java developers, DevOps engineers and cloud-native application teams.


Keywords

What is Docker, Docker Tutorial, Docker for Beginners, Docker Containers, Docker Images, Docker Architecture, Docker Explained, Docker vs Virtual Machine, Containerization, DevOps Tutorial, Spring Boot Docker, Docker Interview Questions, Cloud Native Applications, Microservices Docker, Docker Basics



What is Docker? Explained for Beginners with Real Examples What is Docker? Explained for Beginners with Real Examples Reviewed by 13thGhost on 12:05 AM Rating: 5

50 Java Stream API Coding Interview Questions with Solutions

12:38 AM

Java Stream API is one of the most frequently discussed topics in Java developer interviews. Whether you are interviewing for a Senior Java Developer, Technical Lead or Full Stack Developer position, a strong understanding of Streams is essential.

Introduced in Java 8, the Stream API provides a functional approach to processing collections of data. It allows developers to filter, transform, sort, group and aggregate data without writing excessive loops.

However, knowing the syntax of filter(), map() and collect() is not enough for experienced developers.

Interviewers often expect you to solve practical problems involving:

  • Filtering and transforming collections.

  • Sorting and finding the highest or second-highest values.

  • Grouping records using Collectors.groupingBy().

  • Working with nested collections using flatMap().

  • Handling duplicate elements.

  • Using Optional correctly.

  • Processing employee and transaction data.

  • Understanding performance and parallel streams.

This guide contains 50 Java Stream API coding interview questions, starting with basic operations and progressing to advanced real-world scenarios.

Java compatibility: Examples are primarily compatible with Java 8 and later. Newer APIs are identified separately.

Table of Contents

  1. Basic Stream API Questions

  2. Filtering and Transformation

  3. Sorting and Finding Elements

  4. Collectors and Grouping

  5. Employee-Based Real-World Problems

  6. flatMap and Nested Collections

  7. String and Character Problems

  8. Advanced Stream API Coding Problems

  9. Important Interview Concepts

  10. Frequently Asked Questions


Section 1: Basic Java Stream API Questions

Q1. Find all even numbers from a list

Problem: Given a list of integers, return only even numbers.

Solution:

List<Integer> numbers = Arrays.asList(
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
);

List<Integer> evenNumbers = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());

System.out.println(evenNumbers);

Output:

[2, 4, 6, 8, 10]

Explanation:

  • stream() creates a stream from the collection.

  • filter() selects elements satisfying the condition.

  • collect() converts the stream back into a list.

Interview concept: filter() is an intermediate operation and collect() is a terminal operation.

Q2. Find all odd numbers from a list

List<Integer> oddNumbers = numbers.stream()
    .filter(n -> n % 2 != 0)
    .collect(Collectors.toList());

System.out.println(oddNumbers);

Output:

[1, 3, 5, 7, 9]

Q3. Find the square of every number

List<Integer> squares = numbers.stream()
    .map(n -> n * n)
    .collect(Collectors.toList());

System.out.println(squares);

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Interview concept: map() transforms every element into another value.

Q4. Remove duplicate elements from a list

List<Integer> values = Arrays.asList(
    10, 20, 10, 30, 20, 40
);

List<Integer> uniqueValues = values.stream()
    .distinct()
    .collect(Collectors.toList());

System.out.println(uniqueValues);

Output:

[10, 20, 30, 40]

Interview concept: distinct() uses equality semantics to identify duplicate elements. For custom objects, implement equals() and hashCode() appropriately.

Q5. Count the number of elements in a list

long count = numbers.stream()
    .count();

System.out.println(count);

Output:

10

Q6. Convert all strings to uppercase

List<String> names = Arrays.asList(
    "java", "spring", "kafka"
);

List<String> upperCaseNames = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

System.out.println(upperCaseNames);

Output:

[JAVA, SPRING, KAFKA]

Q7. Filter strings starting with a particular character

List<String> filteredNames = names.stream()
    .filter(name -> name.startsWith("s"))
    .collect(Collectors.toList());

System.out.println(filteredNames);

Output:

[spring]

Q8. Find the longest string in a list

Optional<String> longestName = names.stream()
    .max(Comparator.comparingInt(String::length));

longestName.ifPresent(System.out::println);

Output:

spring

Interview concept: max() returns an Optional because the collection may be empty.

Q9. Find the shortest string in a list

Optional<String> shortestName = names.stream()
    .min(Comparator.comparingInt(String::length));

shortestName.ifPresent(System.out::println);

Output:

java

Q10. Join all strings with a comma separator

String result = names.stream()
    .collect(Collectors.joining(", "));

System.out.println(result);

Output:

java, spring, kafka

Section 2: Filtering and Transformation

Q11. Find the frequency of each integer

Problem: Count how many times each number appears.

List<Integer> values = Arrays.asList(
    1, 2, 2, 3, 3, 3, 4
);

Map<Integer, Long> frequency = values.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.counting()
    ));

System.out.println(frequency);

Output:

{1=1, 2=2, 3=3, 4=1}

Explanation:

  • Function.identity() returns the element itself.

  • groupingBy() groups equal elements.

  • counting() counts the elements in each group.

Q12. Find the frequency of each character in a string

String input = "programming";

Map<Character, Long> characterFrequency =
    input.chars()
        .mapToObj(c -> (char) c)
        .collect(Collectors.groupingBy(
            Function.identity(),
            Collectors.counting()
        ));

System.out.println(characterFrequency);

Output: Character frequencies are grouped into a map.

Q13. Find duplicate elements in a list

Set<Integer> duplicates = values.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.counting()
    ))
    .entrySet()
    .stream()
    .filter(entry -> entry.getValue() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());

System.out.println(duplicates);

Output:

[2, 3]

Q14. Find elements appearing exactly once

List<Integer> uniqueElements = values.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        LinkedHashMap::new,
        Collectors.counting()
    ))
    .entrySet()
    .stream()
    .filter(entry -> entry.getValue() == 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

System.out.println(uniqueElements);

Output:

[1, 4]

Q15. Find the second-highest distinct number

Optional<Integer> secondHighest = numbers.stream()
    .distinct()
    .sorted(Comparator.reverseOrder())
    .skip(1)
    .findFirst();

System.out.println(secondHighest.orElse(null));

Explanation:

  1. distinct() removes duplicate values.

  2. sorted() sorts in descending order.

  3. skip(1) skips the highest value.

  4. findFirst() returns the next value.

Interview follow-up: What happens when the collection contains fewer than two distinct values?

Answer: The result is an empty Optional.

Q16. Find the Nth highest distinct number

int n = 3;

Optional<Integer> nthHighest = numbers.stream()
    .distinct()
    .sorted(Comparator.reverseOrder())
    .skip(n - 1)
    .findFirst();

System.out.println(nthHighest.orElse(null));

Important: Validate that n is greater than zero before executing the stream.

Q17. Find the top three highest numbers

List<Integer> topThree = numbers.stream()
    .distinct()
    .sorted(Comparator.reverseOrder())
    .limit(3)
    .collect(Collectors.toList());

System.out.println(topThree);

Q18. Sort numbers in ascending order

List<Integer> ascending = numbers.stream()
    .sorted()
    .collect(Collectors.toList());

System.out.println(ascending);

Q19. Sort numbers in descending order

List<Integer> descending = numbers.stream()
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());

System.out.println(descending);

Q20. Sort strings based on their length

List<String> sortedNames = names.stream()
    .sorted(Comparator.comparingInt(String::length))
    .collect(Collectors.toList());

System.out.println(sortedNames);

Interview concept: Comparators allow custom sorting rules without modifying the original objects.


Section 3: Collectors and Grouping

Q21. Find the maximum number in a list

Optional<Integer> maximum = numbers.stream()
    .max(Integer::compareTo);

System.out.println(maximum.orElse(null));

Q22. Find the minimum number in a list

Optional<Integer> minimum = numbers.stream()
    .min(Integer::compareTo);

System.out.println(minimum.orElse(null));

Q23. Calculate the sum of all numbers

int sum = numbers.stream()
    .mapToInt(Integer::intValue)
    .sum();

System.out.println(sum);

Q24. Calculate the average of all numbers

OptionalDouble average = numbers.stream()
    .mapToInt(Integer::intValue)
    .average();

System.out.println(
    average.isPresent() ? average.getAsDouble() : 0.0
);

Interview concept: mapToInt() converts a regular object stream into an IntStream, which provides primitive operations such as sum() and average().

Q25. Partition numbers into even and odd groups

Map<Boolean, List<Integer>> partitioned =
    numbers.stream()
        .collect(Collectors.partitioningBy(
            n -> n % 2 == 0
        ));

System.out.println(partitioned);

Output structure:

{
  false=[1, 3, 5, 7, 9],
  true=[2, 4, 6, 8, 10]
}

Interview concept: partitioningBy() creates exactly two Boolean groups, whereas groupingBy() can create multiple groups.

Q26. Group strings by their length

Map<Integer, List<String>> groupedByLength =
    names.stream()
        .collect(Collectors.groupingBy(
            String::length
        ));

System.out.println(groupedByLength);

Output structure:

{
  4=[java],
  6=[spring],
  5=[kafka]
}

Q27. Group employees by department

Assume an Employee class has the following properties:

class Employee {
    private int id;
    private String name;
    private String department;
    private double salary;

    // Constructor, getters and setters
}

Create an employee list:

List<Employee> employees = Arrays.asList(
    new Employee(1, "Amit", "IT", 80000),
    new Employee(2, "Rahul", "HR", 50000),
    new Employee(3, "Priya", "IT", 95000),
    new Employee(4, "Neha", "Finance", 70000),
    new Employee(5, "Vikas", "HR", 60000)
);

Group employees by department:

Map<String, List<Employee>> employeesByDepartment =
    employees.stream()
        .collect(Collectors.groupingBy(
            Employee::getDepartment
        ));

Interview concept: This is one of the most common real-world groupingBy() interview problems.

Q28. Calculate the average salary of each department

Map<String, Double> averageSalary =
    employees.stream()
        .collect(Collectors.groupingBy(
            Employee::getDepartment,
            Collectors.averagingDouble(
                Employee::getSalary
            )
        ));

System.out.println(averageSalary);

Expected result:

{
  IT=87500.0,
  HR=55000.0,
  Finance=70000.0
}

Q29. Find the highest-paid employee in each department

Map<String, Optional<Employee>> highestPaidByDepartment =
    employees.stream()
        .collect(Collectors.groupingBy(
            Employee::getDepartment,
            Collectors.maxBy(
                Comparator.comparingDouble(
                    Employee::getSalary
                )
            )
        ));

Interview concept: maxBy() is a downstream collector. Its result is an Optional<Employee> for each group.

Q30. Find the second-highest-paid employee

Optional<Employee> secondHighestPaid =
    employees.stream()
        .sorted(
            Comparator.comparingDouble(
                Employee::getSalary
            ).reversed()
        )
        .skip(1)
        .findFirst();

secondHighestPaid.ifPresent(employee ->
    System.out.println(
        employee.getName() + " : " + employee.getSalary()
    )
);

Important interview distinction: This finds the second employee by salary, not necessarily the second-highest distinct salary. To find the second-highest distinct salary, first find the second salary value using distinct(), then select an employee with that salary.


Section 4: Employee-Based Real-World Problems

Q31. Sort employees by salary in descending order

List<Employee> sortedEmployees = employees.stream()
    .sorted(
        Comparator.comparingDouble(
            Employee::getSalary
        ).reversed()
    )
    .collect(Collectors.toList());

Q32. Get employee names belonging to the IT department

List<String> itEmployees = employees.stream()
    .filter(e -> "IT".equals(e.getDepartment()))
    .map(Employee::getName)
    .collect(Collectors.toList());

System.out.println(itEmployees);

Q33. Count employees in each department

Map<String, Long> employeeCount =
    employees.stream()
        .collect(Collectors.groupingBy(
            Employee::getDepartment,
            Collectors.counting()
        ));

System.out.println(employeeCount);

Q34. Join employee names using a comma separator

String employeeNames = employees.stream()
    .map(Employee::getName)
    .collect(Collectors.joining(", "));

System.out.println(employeeNames);

Q35. Find employees earning more than 75,000

List<Employee> highSalaryEmployees =
    employees.stream()
        .filter(e -> e.getSalary() > 75000)
        .collect(Collectors.toList());

Interview follow-up: How would you sort these employees by salary after filtering?

List<Employee> result = employees.stream()
    .filter(e -> e.getSalary() > 75000)
    .sorted(
        Comparator.comparingDouble(
            Employee::getSalary
        ).reversed()
    )
    .collect(Collectors.toList());

Q36. Find the highest salary in each department

Map<String, Double> highestSalary =
    employees.stream()
        .collect(Collectors.groupingBy(
            Employee::getDepartment,
            Collectors.mapping(
                Employee::getSalary,
                Collectors.maxBy(
                    Double::compareTo
                )
            )
        ))
        .entrySet()
        .stream()
        .collect(Collectors.toMap(
            Map.Entry::getKey,
            e -> e.getValue().orElse(0.0)
        ));

This demonstrates combining groupingBy(), mapping() and maxBy().

Q37. Convert employee list into a Map using employee ID

Map<Integer, Employee> employeeMap =
    employees.stream()
        .collect(Collectors.toMap(
            Employee::getId,
            Function.identity()
        ));

Important: If employee IDs are duplicated, toMap() throws an IllegalStateException unless you supply a merge function.

For example:

Map<Integer, Employee> employeeMap =
    employees.stream()
        .collect(Collectors.toMap(
            Employee::getId,
            Function.identity(),
            (existing, replacement) -> existing
        ));

Q38. Find the total salary expenditure of the company

double totalSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .sum();

System.out.println(totalSalary);

Q39. Find the employee with the longest name

Optional<Employee> employeeWithLongestName =
    employees.stream()
        .max(
            Comparator.comparingInt(
                e -> e.getName().length()
            )
        );

Q40. Find employees whose salary is above their department's average

Map<String, Double> departmentAverage =
    employees.stream()
        .collect(Collectors.groupingBy(
            Employee::getDepartment,
            Collectors.averagingDouble(
                Employee::getSalary
            )
        ));

List<Employee> aboveAverageEmployees =
    employees.stream()
        .filter(e -> e.getSalary() >
            departmentAverage.get(e.getDepartment()))
        .collect(Collectors.toList());

Why is this interesting?

This problem requires two stream operations:

  1. Calculate the average salary for every department.

  2. Compare each employee's salary against the corresponding department average.

This is a useful example of using streams for multi-step business logic.


Section 5: flatMap and Nested Collections

Q41. Flatten a list of lists into a single list

Problem: Convert nested collections into a single collection.

List<List<Integer>> nestedList = Arrays.asList(
    Arrays.asList(1, 2, 3),
    Arrays.asList(4, 5, 6),
    Arrays.asList(7, 8, 9)
);

List<Integer> flattenedList = nestedList.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());

System.out.println(flattenedList);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Interview concept:

  • map() transforms each element into one result.

  • flatMap() transforms each element into a stream and flattens the resulting streams into one stream.

Q42. Find common elements between two lists

List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);

List<Integer> commonElements = list1.stream()
    .filter(list2::contains)
    .distinct()
    .collect(Collectors.toList());

System.out.println(commonElements);

Output:

[3, 4, 5]

Performance tip: For large lists, convert the second collection into a HashSet first to make membership checks typically constant-time.

Q43. Find elements present in the first list but not in the second

Set<Integer> secondSet = new HashSet<>(list2);

List<Integer> difference = list1.stream()
    .filter(n -> !secondSet.contains(n))
    .collect(Collectors.toList());

System.out.println(difference);

Output:

[1, 2]

Q44. Find all unique words from a list of sentences

List<String> sentences = Arrays.asList(
    "Java is powerful",
    "Java supports streams",
    "Streams simplify Java programming"
);

List<String> uniqueWords = sentences.stream()
    .flatMap(sentence ->
        Arrays.stream(sentence.split("\\s+"))
    )
    .map(String::toLowerCase)
    .distinct()
    .collect(Collectors.toList());

System.out.println(uniqueWords);

Note: This example uses whitespace tokenisation. Punctuation normalisation would be needed for more general text processing.


Section 6: String and Character Coding Problems

Q45. Find the first non-repeating character in a string

String input = "swiss";

Optional<Character> firstNonRepeating =
    input.chars()
        .mapToObj(c -> (char) c)
        .collect(Collectors.groupingBy(
            Function.identity(),
            LinkedHashMap::new,
            Collectors.counting()
        ))
        .entrySet()
        .stream()
        .filter(entry -> entry.getValue() == 1)
        .map(Map.Entry::getKey)
        .findFirst();

System.out.println(firstNonRepeating.orElse(null));

Output:

w

Why use LinkedHashMap?

It preserves insertion order, allowing us to identify the first character that occurs only once.

Q46. Find the first repeating character

String input = "programming";

Set<Character> seen = new HashSet<>();

Optional<Character> firstRepeating =
    input.chars()
        .mapToObj(c -> (char) c)
        .filter(c -> !seen.add(c))
        .findFirst();

System.out.println(firstRepeating.orElse(null));

Output:

r

Interview concept: This uses a stateful predicate. It works for a sequential stream, but should not be used with a parallel stream because the shared mutable set is not thread-safe.

Q47. Check whether two strings are anagrams

String first = "listen";
String second = "silent";

String sortedFirst = first.chars()
    .sorted()
    .collect(
        StringBuilder::new,
        StringBuilder::appendCodePoint,
        StringBuilder::append
    )
    .toString();

String sortedSecond = second.chars()
    .sorted()
    .collect(
        StringBuilder::new,
        StringBuilder::appendCodePoint,
        StringBuilder::append
    )
    .toString();

boolean isAnagram = sortedFirst.equals(sortedSecond);

System.out.println(isAnagram);

Output:

true

This version is case-sensitive and considers whitespace significant. Normalise the inputs first if the business requirement is case-insensitive comparison.


Section 7: Advanced Java Stream API Problems

Q48. Find all prime numbers within a range

List<Integer> primes = IntStream.rangeClosed(2, 50)
    .filter(n ->
        IntStream.rangeClosed(2, (int) Math.sqrt(n))
            .allMatch(i -> n % i != 0)
    )
    .boxed()
    .collect(Collectors.toList());

System.out.println(primes);

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Explanation:

  • rangeClosed() generates numbers including the upper bound.

  • allMatch() checks whether every divisor candidate satisfies the condition.

  • boxed() converts primitive integers into Integer objects.

Q49. Calculate the sum of digits of a number

int number = 12345;

int digitSum = String.valueOf(number)
    .chars()
    .map(Character::getNumericValue)
    .sum();

System.out.println(digitSum);

Output:

15

Note: This concise example assumes a non-negative decimal integer. Handle negative values and input validation explicitly if required.

Q50. Generate the Fibonacci sequence using Stream API

List<Integer> fibonacci = Stream.iterate(
        new int[]{0, 1},
        pair -> new int[]{
            pair[1],
            pair[0] + pair[1]
        }
    )
    .limit(10)
    .map(pair -> pair[0])
    .collect(Collectors.toList());

System.out.println(fibonacci);

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Interview concept: Java 8's Stream.iterate() allows generating an infinite sequential stream. Always use a limiting operation when you need a finite result.


Section 8: Important Java Stream API Interview Concepts

Understanding coding problems is only half the preparation. Experienced developers should also understand the underlying behaviour of the Stream API.

1. Difference between map() and flatMap()

map()flatMap()
Transforms each elementTransforms and flattens
One output per inputZero, one or many outputs per input
Can produce nested structuresProduces a flattened stream
Example: String to uppercaseExample: List of Lists to List

2. Intermediate vs terminal operations

Intermediate operations:

  • filter()

  • map()

  • flatMap()

  • distinct()

  • sorted()

  • limit()

  • skip()

  • peek()

Terminal operations:

  • collect()

  • forEach()

  • count()

  • reduce()

  • min()

  • max()

  • findFirst()

  • findAny()

  • anyMatch()

  • allMatch()

  • noneMatch()

Intermediate operations are generally lazy. Processing begins when a terminal operation is invoked.

3. What is lazy evaluation?

Consider:

List<Integer> result = numbers.stream()
    .filter(n -> {
        System.out.println("Filtering: " + n);
        return n > 5;
    })
    .map(n -> n * 2)
    .collect(Collectors.toList());

The stream pipeline does not process the elements when it is created. Processing starts when collect() is executed.

This allows the Stream API to optimise execution and avoid unnecessary intermediate collections.

4. Difference between findFirst() and findAny()

  • findFirst() returns the first element according to the stream's encounter order, when one exists.

  • findAny() may return any element and is useful when the actual first element is not important, especially with parallel streams.

5. What is reduce()?

reduce() combines elements into a single result.

Example:

int total = numbers.stream()
    .reduce(0, Integer::sum);

System.out.println(total);

The identity value is 0, and the accumulator combines the values.

6. What are parallel streams?

Parallel streams divide work across multiple processing threads using the Java fork/join infrastructure.

List<Integer> result = numbers.parallelStream()
    .filter(n -> n > 5)
    .map(n -> n * 2)
    .collect(Collectors.toList());

Parallel streams are not automatically faster.

Consider:

  • Dataset size.

  • CPU-intensive versus I/O-intensive work.

  • Cost of splitting the source.

  • Combining partial results.

  • Thread safety.

  • Shared mutable state.

  • Common ForkJoinPool contention.

Use benchmarking rather than assuming parallel execution improves performance.

7. Can a stream be reused?

No. Once a terminal operation consumes a stream, it cannot be reused.

Incorrect:

Stream<Integer> stream = numbers.stream();

stream.forEach(System.out::println);

stream.count(); // IllegalStateException

Correct:

long count = numbers.stream().count();

numbers.stream().forEach(System.out::println);

Create a new stream whenever you need another pipeline.


Section 9: Common Mistakes in Java Stream API Interviews

  1. Using map() when flatMap() is required.

  2. Forgetting that streams are lazy.

  3. Reusing a stream after a terminal operation.

  4. Using get() on an empty Optional.

  5. Ignoring duplicate keys in Collectors.toMap().

  6. Using mutable shared variables in parallel streams.

  7. Assuming parallel streams are always faster.

  8. Modifying a collection while it is being streamed.

  9. Using peek() as a replacement for proper processing.

  10. Ignoring the cost of sorting large datasets.

Senior developers should be able to explain not just how a solution works, but why it is appropriate for a particular production scenario.


Section 10: Frequently Asked Questions

1. Is Java Stream API available from Java 8?

Yes. Stream API was introduced in Java 8 through java.util.stream.

2. Are Java Streams and Collections the same?

No. Collections store data. Streams provide a pipeline for processing data from a source.

3. Can we modify a collection while using its stream?

You should not structurally modify the source collection during stream processing. This can cause unpredictable behaviour or exceptions.

4. What is the difference between Collection.stream() and Collection.parallelStream()?

stream() creates a sequential stream, while parallelStream() creates a potentially parallel stream.

5. What is the difference between collect() and reduce()?

collect() is designed for mutable reduction, such as building collections or grouped results. reduce() combines values into a result using an associative reduction operation.

6. What is Collectors.groupingBy()?

It groups elements based on a classification function and can apply downstream collectors such as counting(), averagingDouble() and mapping().

7. Does Stream API modify the original collection?

Ordinary stream operations do not modify the source collection. However, side effects inside lambdas can modify external state, which should generally be avoided.

8. When should we avoid Streams?

Traditional loops can be clearer for complex stateful algorithms, heavy debugging, intricate control flow or performance-sensitive situations where benchmarking shows streams are unsuitable.


Conclusion

Java Stream API is more than a convenient replacement for traditional loops. It provides a declarative way to express data-processing operations and is particularly useful when working with collections, employee records, transactions, reporting and business data.

For experienced Java developers, the most important areas to master are:

  • map() and flatMap()

  • filter() and distinct()

  • Collectors.groupingBy()

  • Collectors.partitioningBy()

  • Collectors.toMap()

  • Collectors.mapping()

  • Collectors.reducing()

  • Optional

  • reduce()

  • Parallel stream behaviour

Practise these 50 problems, understand the underlying execution and be ready to discuss performance, edge cases and alternative implementations.


50 Java Stream API Coding Interview Questions with Solutions 50 Java Stream API Coding Interview Questions with Solutions Reviewed by 13thGhost on 12:38 AM Rating: 5

Top 25 Spring Security Interview Questions and Answers for Experienced Developers

10:07 PM

Spring Security is one of the most important frameworks in modern Java application development. Whether you are building REST APIs, microservices or enterprise applications, securing resources and controlling access is a critical requirement.


As a result, Spring Security questions frequently appear in technical interviews for Spring Boot developers, senior developers and solution architects.

This article covers the most commonly asked Spring Security interview questions along with detailed answers and practical explanations.


Who Should Read This Article?

  • Java Developers
  • Spring Boot Developers
  • Backend Engineers
  • Microservices Developers
  • Interview Candidates

1. What is Spring Security?

Spring Security is the official security framework provided by the Spring ecosystem. It offers a comprehensive set of features for authentication, authorization and protection against common security vulnerabilities.


Before Spring Security, developers often implemented authentication and authorization manually, which resulted in inconsistent security implementations and increased maintenance effort.


Spring Security standardizes application security and provides powerful capabilities such as:

  • Authentication
  • Authorization
  • Password Encoding
  • Session Management
  • CSRF Protection
  • JWT Integration
  • OAuth2 Support

Interview Tip: Mention that Spring Security is deeply integrated with Spring Boot and is the standard security framework used in enterprise Java applications.


2. What is Authentication?

Authentication is the process of verifying the identity of a user.

Authentication answers the question:


Who are you?

When a user submits credentials such as a username and password, Spring Security validates those credentials against a configured user store.

Only after successful verification is the user considered authenticated.

Examples of authentication mechanisms include:

  • Username and Password
  • JWT Authentication
  • OAuth2 Login
  • Single Sign-On (SSO)
  • Multi-Factor Authentication (MFA)

3. What is Authorization?

Authorization is the process of determining what an authenticated user is allowed to access.

Authorization answers the question:


What are you allowed to do?

For example, an ADMIN user may be allowed to delete records while a USER may only view data.

Authentication always occurs before authorization because the system must know the user's identity before assigning permissions.


4. What is the Difference Between Authentication and Authorization?

Authentication Authorization
Verifies Identity Verifies Permissions
Who Are You? What Can You Access?
Executed First Executed After Authentication

A simple way to remember:


Authentication
   ↓
Authorization

5. What is SecurityFilterChain?

SecurityFilterChain is the foundation of modern Spring Security configuration.

Every incoming request passes through a chain of security filters before reaching application controllers.


Client Request
      |
      v
SecurityFilterChain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Controller

The SecurityFilterChain is responsible for validating credentials, checking permissions and protecting application endpoints.


6. Why was WebSecurityConfigurerAdapter Deprecated?

Spring Security moved away from inheritance-based configuration in favour of bean-based configuration using SecurityFilterChain.

This approach is more flexible, easier to understand and aligns better with modern Spring Boot development practices.


7. What is UserDetailsService?

UserDetailsService is a Spring Security interface used to load user details during authentication.


UserDetailsService

When a user attempts to log in, Spring Security calls the UserDetailsService implementation to retrieve information about that user.


8. What is UserDetails?

UserDetails represents a security user inside Spring Security.

It contains information such as:

  • Username
  • Password
  • Roles
  • Authorities
  • Account Status

9. What is PasswordEncoder?

PasswordEncoder is used to securely encode passwords before storing them in a database.

Storing plain text passwords is a major security risk and should always be avoided.


10. Why is BCryptPasswordEncoder Commonly Used?

BCrypt is one of the most widely used password hashing algorithms because it generates secure hashes and automatically applies salting.

This makes password cracking significantly more difficult.


new BCryptPasswordEncoder()

11. What is JWT?

JWT stands for JSON Web Token. It is a compact and self-contained token used for stateless authentication. After successful login, the server generates a token and returns it to the client. The client includes the token in subsequent requests using the Authorization header.


Authorization:

Bearer eyJhbGciOi...

12. What are the Three Parts of JWT?

A JWT consists of three sections:


Header

Payload

Signature

The Header stores metadata, the Payload contains claims and the Signature protects token integrity.


13. Why is JWT Popular in REST APIs?

JWT supports stateless authentication.

The server does not need to maintain session information, making JWT ideal for cloud-native and microservice architectures.


14. What is Role-Based Access Control (RBAC)?

Role-Based Access Control restricts system access based on roles assigned to users.


ADMIN

MANAGER

USER

Each role receives specific permissions.


15. What is SecurityContext?

SecurityContext stores information about the currently authenticated user.

After authentication succeeds, Spring Security stores Authentication details inside the SecurityContext.


SecurityContextHolder
    .getContext()

16. What is CSRF?

CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks a user's browser into sending unwanted requests.

Spring Security provides built-in CSRF protection for web applications.


17. Why is CSRF Often Disabled for REST APIs?

Most REST APIs use stateless authentication with JWT instead of server-side sessions.

In those cases, CSRF protection is often disabled because session-based attacks are less relevant.


18. What is OncePerRequestFilter?

OncePerRequestFilter ensures a filter executes only once during request processing.

JWT validation filters commonly extend this class.


19. What is Method-Level Security?

Method-Level Security applies authorization rules directly to methods.


@PreAuthorize(
    "hasRole('ADMIN')"
)

Only users with appropriate permissions can invoke the method.


20. What is the Difference Between 401 and 403?

Status Code Meaning
401 User is not authenticated
403 User is authenticated but lacks required permissions

21. What is OAuth2?

OAuth2 is an authorization framework that allows third-party applications to access resources on behalf of users without sharing passwords.

Examples include Google Login and GitHub Login.


22. What is Session Management?

Session management controls how user sessions are created, maintained and terminated.

Traditional applications commonly rely on sessions for authentication.


23. What is Stateless Authentication?

In stateless authentication, the server does not store session information.

Each request contains all required authentication information, typically through a JWT token.


24. What are Spring Security Filters?

Filters are components that process requests before they reach controllers.

Examples include:

  • Authentication Filter
  • Authorization Filter
  • JWT Filter
  • Logout Filter

25. Explain the Spring Security Request Lifecycle.


Client Request
      |
      v
SecurityFilterChain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Security Context
      |
      v
Controller

Every incoming request passes through this process before business logic is executed.


Recommended Spring Security Learning Path


Spring Security Basics
        ↓
Authentication vs Authorization
        ↓
RBAC
        ↓
SecurityFilterChain
        ↓
JWT Authentication
        ↓
OAuth2

Related Articles

  • Spring Security Explained for Beginners with Real Examples
  • Authentication vs Authorization in Spring Security
  • JWT Authentication in Spring Boot Explained with Real Examples
  • Role-Based Access Control (RBAC) in Spring Security
  • SecurityFilterChain in Spring Security Explained with Real Examples

Conclusion

Spring Security remains one of the most important frameworks in the Java ecosystem. Understanding Authentication, Authorization, JWT, RBAC, SecurityFilterChain and password encoding concepts is essential for building secure applications and performing well in Spring Security interviews.



Top 25 Spring Security Interview Questions and Answers for Experienced Developers Top 25 Spring Security Interview Questions and Answers for Experienced Developers Reviewed by 13thGhost on 10:07 PM Rating: 5

SecurityFilterChain in Spring Security Explained with Real Examples

9:57 PM

SecurityFilterChain is one of the most important concepts in modern Spring Security. Since Spring Security 5.7, SecurityFilterChain has become the recommended approach for defining security configurations.


Understanding SecurityFilterChain is essential for securing Spring Boot applications and frequently appears in Spring Security interviews.


What is SecurityFilterChain?

SecurityFilterChain is a sequence of security filters that process every incoming HTTP request before it reaches a controller.

Each filter performs a specific security task such as authentication, authorization or JWT validation.



Request
   |
   v
Security Filters
   |
   v
Controller

Why Do We Need SecurityFilterChain?

Without SecurityFilterChain, requests would directly reach application endpoints without security validation.

SecurityFilterChain acts as a security checkpoint.



Client
   |
   v
SecurityFilterChain
   |
   v
Protected API

Request Processing Flow


Client Request
       |
       v
Authentication Filter
       |
       v
Authorization Filter
       |
       v
Security Context
       |
       v
Controller

Every request must successfully pass through the chain.


Creating a SecurityFilterChain


@Bean

public SecurityFilterChain
securityFilterChain(
        HttpSecurity http)
throws Exception {

    http

        .authorizeHttpRequests(

            auth -> auth

                .anyRequest()
                .authenticated()

        )

        .formLogin();

    return http.build();

}

This configuration requires authentication for every endpoint.


Understanding HttpSecurity

HttpSecurity is used to configure web security rules.


HttpSecurity

It controls authentication, authorization, CORS, CSRF and session management.


Allowing Public Endpoints


.authorizeHttpRequests(

    auth -> auth

    .requestMatchers(
        "/public/**"
    )

    .permitAll()

)

Anyone can access these endpoints without authentication.


Securing Specific Endpoints


.authorizeHttpRequests(

    auth -> auth

    .requestMatchers(
        "/admin/**"
    )

    .hasRole("ADMIN")

)

Only ADMIN users can access those endpoints.


Multiple Security Rules


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/public/**"
        )

        .permitAll()

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

        .requestMatchers(
            "/manager/**"
        )

        .hasRole("MANAGER")

        .anyRequest()

        .authenticated()

)

Security Context

Spring Security stores authenticated user information inside SecurityContext.


SecurityContextHolder

Controllers and services can access the current authenticated user.


Accessing Current User


Authentication auth =

SecurityContextHolder
    .getContext()
    .getAuthentication();

This returns details about the currently logged-in user.


JWT and SecurityFilterChain

JWT authentication is implemented by adding a custom JWT filter into SecurityFilterChain.


JWT Token
     |
     v
JWT Filter
     |
     v
Security Context

This enables stateless authentication.


Disabling CSRF

REST APIs often disable CSRF protection.



http.csrf(
    csrf -> csrf.disable()
);

This is common in JWT-based applications.


Common Filters in Spring Security

  • UsernamePasswordAuthenticationFilter
  • BasicAuthenticationFilter
  • JwtAuthenticationFilter
  • LogoutFilter
  • ExceptionTranslationFilter

SecurityFilterChain vs WebSecurityConfigurerAdapter

SecurityFilterChain WebSecurityConfigurerAdapter
Modern Approach Deprecated
Bean Based Inheritance Based
Spring Security 5.7+ Older Versions

Real World Example

An e-commerce platform may secure resources as follows:


/public/products

/admin/products

/admin/orders

/customer/orders

SecurityFilterChain determines who can access each endpoint.


Common Interview Questions

What is SecurityFilterChain?

It is a chain of security filters that process incoming requests before controllers are invoked.


Why was WebSecurityConfigurerAdapter removed?

Spring Security moved to a bean-based configuration model using SecurityFilterChain.


Can SecurityFilterChain work with JWT?

Yes. JWT validation is commonly implemented through custom filters.


What is HttpSecurity?

A configuration object used to define security rules.


What is SecurityContext?

A container that stores information about the authenticated user.


Best Practices

  • Use SecurityFilterChain instead of deprecated approaches.
  • Keep security rules simple and clear.
  • Use role-based authorization.
  • Protect sensitive endpoints.
  • Combine with JWT for REST APIs.

Frequently Asked Questions (FAQ)

Can multiple SecurityFilterChain beans exist?

Yes. Applications can define multiple security configurations.


Can SecurityFilterChain secure REST APIs?

Yes. It is commonly used in modern Spring Boot API security.


Should SecurityFilterChain be used with JWT?

Yes. This is a common modern security architecture.


Conclusion

SecurityFilterChain is the foundation of modern Spring Security. It processes incoming requests, performs authentication and authorization checks, and protects application resources. Understanding SecurityFilterChain is essential for building secure Spring Boot applications and succeeding in Spring Security interviews.


Keywords

SecurityFilterChain, Spring Security Filter Chain, Spring Boot Security, Spring Security Configuration, HttpSecurity, Spring Security Tutorial, JWT SecurityFilterChain, Spring Security Interview Questions, Authorization Filter, Authentication Filter, Spring Boot Authentication, Spring Boot Authorization, Java Security, Enterprise Application Security, Spring Security Architecture

SecurityFilterChain in Spring Security Explained with Real Examples SecurityFilterChain in Spring Security Explained with Real Examples Reviewed by 13thGhost on 9:57 PM Rating: 5

Role-Based Access Control (RBAC) in Spring Security with Real Examples

12:44 PM

Authentication verifies who a user is, but authentication alone is not enough. Enterprise applications must also control what users are allowed to access.


Role-Based Access Control (RBAC) is one of the most widely used authorization models in Spring Security. It allows applications to restrict access based on user roles.


What is RBAC?

RBAC stands for Role-Based Access Control.

Users are assigned roles, and roles determine what resources users can access.


User
   |
   v
Role
   |
   v
Permissions

Why Do We Need RBAC?

Consider an e-commerce application.


Customer

Manager

Administrator

Each type of user requires different access privileges.

Without RBAC, every authenticated user would have the same permissions.


Real World Example


ADMIN

Manage Users

Delete Users

View Reports

Manage Products


MANAGER

Manage Products

View Reports


USER

View Products

Place Orders

Each role has its own set of permissions.


Spring Security Role Format

Spring Security internally stores roles using the ROLE_ prefix.


ROLE_ADMIN

ROLE_MANAGER

ROLE_USER

Developers typically specify roles without the prefix.


.roles("ADMIN")

Create Users with Roles


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails admin =

        User.builder()

            .username("admin")

            .password(
                passwordEncoder()
                    .encode("admin123")
            )

            .roles("ADMIN")

            .build();

    UserDetails user =

        User.builder()

            .username("user")

            .password(
                passwordEncoder()
                    .encode("user123")
            )

            .roles("USER")

            .build();

    return new
        InMemoryUserDetailsManager(
            admin,
            user
        );
}

Secure Endpoints Using Roles


@Bean

public SecurityFilterChain
securityFilterChain(
    HttpSecurity http
)
throws Exception {

    http

    .authorizeHttpRequests(

        auth -> auth

            .requestMatchers(
                "/admin/**"
            )

            .hasRole("ADMIN")

            .requestMatchers(
                "/user/**"
            )

            .hasRole("USER")

            .anyRequest()

            .authenticated()

    );

    return http.build();
}

Spring Security automatically checks roles before allowing access.


Example Controller


@RestController

@RequestMapping("/admin")

public class AdminController {

    @GetMapping("/reports")

    public String reports() {

        return "Admin Reports";

    }

}

Only ADMIN users can access this endpoint.


Access Control Flow


Request
   |
   v
Authentication
   |
   v
Role Check
   |
   +------ Access Granted

   |
   +------ Access Denied

Using Multiple Roles

Some endpoints may allow access to multiple roles.


.hasAnyRole(

    "ADMIN",

    "MANAGER"

)

Both ADMIN and MANAGER users can access the resource.


Method Level Security

RBAC can be applied directly to methods.



@PreAuthorize(
    "hasRole('ADMIN')"
)

public void deleteUser() {

}

Spring Security verifies permissions before executing the method.


Role Hierarchy Example


ADMIN
   |
   +---- MANAGER
            |
            +---- USER

Higher roles can inherit permissions from lower roles.


Authentication vs RBAC

Authentication RBAC
Who Are You? What Can You Access?
Login Verification Permission Verification
User Identity User Access Control

HTTP Response Codes

401 Unauthorized

User is not authenticated.


403 Forbidden

User is authenticated but lacks permission.


Common Interview Questions

What is RBAC?

Role-Based Access Control restricts access based on assigned user roles.


What is the difference between Authentication and Authorization?

Authentication verifies identity. Authorization determines permissions.


What does hasRole() do?

It restricts access to users possessing a specific role.


What does hasAnyRole() do?

It allows access to multiple role types.


What is the meaning of 403 Forbidden?

The user is authenticated but lacks sufficient permissions.


Best Practices

  • Follow the principle of least privilege.
  • Avoid assigning excessive permissions.
  • Implement role hierarchies carefully.
  • Use method-level security where appropriate.
  • Test role-based authorization thoroughly.

Frequently Asked Questions (FAQ)

Can a user have multiple roles?

Yes. Spring Security supports multiple roles per user.


Can RBAC be used with JWT?

Yes. JWT claims commonly contain user roles.


Is RBAC used in enterprise applications?

Yes. RBAC is one of the most widely adopted authorization models.


Conclusion

Role-Based Access Control is a critical part of Spring Security. By assigning roles and limiting access based on permissions, developers can secure sensitive application functionality and implement scalable authorization mechanisms in enterprise applications.


Keywords

RBAC Spring Security, Role Based Access Control, Spring Security Roles, Spring Security Authorization, hasRole Example, hasAnyRole Example, Spring Security RBAC, Spring Boot Security, Role Hierarchy Spring Security, Authorization Example, Security Interview Questions, Java Security, Enterprise Security, Spring Boot Authorization, Spring Security Tutorial


Role-Based Access Control (RBAC) in Spring Security with Real Examples Role-Based Access Control (RBAC) in Spring Security with Real Examples Reviewed by 13thGhost on 12:44 PM Rating: 5

JWT Authentication in Spring Boot Explained with Real Examples

12:36 PM

Modern applications are increasingly built using REST APIs and microservices. Traditional session-based authentication is often not suitable for these architectures.


JWT (JSON Web Token) is one of the most popular solutions for securing REST APIs and is widely used in Spring Boot applications.


What is JWT?

JWT stands for JSON Web Token. It is a compact and self-contained token used to securely transmit user information between client and server.

After successful authentication, the server generates a JWT token and returns it to the client.


Why Do We Need JWT?

Consider a REST API accessed by mobile applications, web applications and third-party clients.

Using HTTP sessions becomes difficult because the server must maintain session information.

JWT solves this problem by storing user information inside the token itself.


JWT Authentication Flow


User Login
     |
     v
Authentication
     |
     v
Generate JWT
     |
     v
Return JWT
     |
     v
Store JWT
     |
     v
Send JWT with Requests
     |
     v
Validate JWT
     |
     v
Access Protected APIs

Real World Example

A customer logs into an e-commerce application.


Username:
john

Password:
password123

Credentials are validated successfully.

Spring Boot generates a JWT token.


eyJhbGciOiJIUzI1NiJ9...

The client stores this token and uses it for future requests.


JWT Structure

A JWT token contains three parts.


Header

Payload

Signature

Example


xxxxx.yyyyy.zzzzz

Header

The header contains token metadata.


{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

The payload contains claims.


{
  "sub": "john",
  "role": "USER"
}

This is where user-related data is stored.


Signature

The signature ensures token integrity.

If the token is modified, signature validation fails.


Add Required Dependency


<dependency>
    <groupId>
        io.jsonwebtoken
    </groupId>

    <artifactId>
        jjwt-api
    </artifactId>

    <version>
        0.11.5
    </version>
</dependency>

Generating JWT Token


public String generateToken(
        String username) {

    return Jwts.builder()

        .setSubject(username)

        .setIssuedAt(
            new Date()
        )

        .setExpiration(
            new Date(
                System.currentTimeMillis()
                + 86400000
            )
        )

        .signWith(
            SECRET_KEY
        )

        .compact();
}

This creates a token valid for 24 hours.


Validating JWT Token


public boolean validateToken(
        String token) {

    try {

        Jwts.parserBuilder()

            .setSigningKey(
                SECRET_KEY
            )

            .build()

            .parseClaimsJws(
                token
            );

        return true;

    }
    catch(Exception ex) {

        return false;

    }
}

Sending JWT in Requests

JWT is usually sent using the Authorization header.


Authorization:

Bearer
eyJhbGciOiJIUzI1NiJ9...

Spring Security JWT Flow


Client
   |
   v
JWT Filter
   |
   v
Validate Token
   |
   v
Security Context
   |
   v
Controller

Every request passes through a JWT filter before reaching the controller.


JWT Filter Example


public class JwtAuthenticationFilter
extends OncePerRequestFilter {

}

This filter extracts and validates the JWT token.


Benefits of JWT

  • Stateless Authentication
  • Scalable Architecture
  • Microservices Friendly
  • Reduced Server Memory Usage
  • Widely Supported

Limitations of JWT

  • Token Revocation Complexity
  • Payload Visibility
  • Larger Request Size
  • Secret Key Management Required

JWT vs Session-Based Authentication

JWT Session
Stateless Stateful
Scalable Requires Session Storage
API Friendly Web Applications
Popular for Microservices Traditional Applications

Common Interview Questions

What is JWT?

A JSON Web Token used for secure authentication and authorization.


What are the three parts of JWT?

Header, Payload and Signature.


Is JWT encrypted?

No. JWT is encoded and signed, not encrypted by default.


Why use JWT in REST APIs?

Because it provides stateless authentication and good scalability.


Where is JWT stored?

Typically inside local storage, session storage or HTTP-only cookies.


Best Practices

  • Keep token expiration short.
  • Use HTTPS.
  • Never store sensitive information in payload.
  • Protect secret keys.
  • Implement refresh token strategy.

Frequently Asked Questions (FAQ)

Can JWT contain roles?

Yes. Roles and permissions can be included in claims.


Can JWT be used with Spring Security?

Yes. Spring Security commonly integrates with JWT authentication.


Is JWT suitable for microservices?

Yes. JWT is widely used in microservice architectures.


Conclusion

JWT Authentication has become the standard approach for securing REST APIs and microservices. Understanding token generation, validation, filters, claims and SecurityContext integration is essential for building secure Spring Boot applications and succeeding in modern Java interviews.


Keywords

JWT Authentication, Spring Boot JWT, Spring Security JWT, JSON Web Token, JWT Tutorial, JWT Interview Questions, Spring Boot Security, JWT Filter, Stateless Authentication, JWT Authentication Example, REST API Security, Microservices Security, Spring Security Tutorial, Java Backend Security, Enterprise Java Development



JWT Authentication in Spring Boot Explained with Real Examples JWT Authentication in Spring Boot Explained with Real Examples Reviewed by 13thGhost on 12:36 PM Rating: 5

Authentication vs Authorization in Spring Security with Real Examples

12:27 PM

Authentication and Authorization are two fundamental security concepts that every Spring Boot developer must understand.


Although these terms are often used together, they solve different security challenges inside an application.

Understanding this difference is a common requirement in Spring Security interviews and real-world enterprise projects.


What is Authentication?

Authentication is the process of verifying the identity of a user.

Authentication answers the question:


Who are you?

The system validates the credentials supplied by the user.

Example


Username:
john

Password:
secret123

Spring Security verifies whether these credentials are correct.


Real World Authentication Example

Consider internet banking.

Before accessing an account, the user must log in.



Enter Username
       +
Enter Password
       |
       v
Identity Verified

This process is Authentication.


What is Authorization?

Authorization determines what an authenticated user is allowed to do.

Authorization answers the question:


What are you allowed to access?

After identity verification, Spring Security evaluates permissions and roles.


Real World Authorization Example


ADMIN
   |
   +---- Create User

   +---- Delete User

   +---- View Reports

USER
   |
   +---- View Profile

   +---- Update Profile

Both users are authenticated.

However, their permissions differ.


Authentication vs Authorization

Authentication Authorization
Verifies Identity Verifies Permissions
Who Are You? What Can You Do?
Occurs First Occurs After Authentication
Username & Password Roles & Permissions

Spring Security Flow


User Request
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Protected Resource

Authentication always occurs before authorization.


Authentication Example in Spring Security


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails user =

        User.builder()

            .username("john")

            .password(
                passwordEncoder()
                .encode("password")
            )

            .roles("USER")

            .build();

    return new InMemoryUserDetailsManager(
        user
    );

}

Spring Security authenticates users using stored credentials.


Authorization Example in Spring Security


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

)

Only users with ADMIN role can access admin endpoints.


Scenario 1: Successful Authentication


Username: admin

Password: admin123

Credentials match.

User is authenticated successfully.


Scenario 2: Failed Authentication


Username: admin

Password: wrongPassword

Credentials do not match.

Access is denied immediately.

Authorization never occurs.


Scenario 3: Authorization Failure

Suppose a USER attempts to access an ADMIN endpoint.


Role:
USER

Request:
GET /admin/users

Authentication succeeds.

Authorization fails.

Spring Security returns:


403 Forbidden

Role-Based Authorization

Spring Security commonly uses roles.


ROLE_ADMIN

ROLE_MANAGER

ROLE_USER

Each role receives different permissions.


Method Level Authorization

Authorization can be applied at method level.



@PreAuthorize(
    "hasRole('ADMIN')"
)

public void deleteUser() {

}

Only ADMIN users can execute this method.


Authentication Mechanisms

Common authentication methods include:


  • Username and Password
  • JWT Authentication
  • OAuth2
  • Single Sign-On (SSO)
  • Multi-Factor Authentication

Authorization Models

  • Role-Based Access Control (RBAC)
  • Permission-Based Access
  • Attribute-Based Access Control

Real World Example

Consider an e-commerce application.



Customer
      |
      +---- View Products

      +---- Place Orders

Admin
      |
      +---- Manage Products

      +---- Manage Orders

      +---- View Reports

Authentication identifies the user.

Authorization controls accessible features.


Common Interview Questions

What is Authentication?

Authentication verifies the identity of a user.


What is Authorization?

Authorization determines what actions a user can perform.


Which comes first?

Authentication always occurs before Authorization.


What HTTP status code indicates authorization failure?

403 Forbidden.


Can Authorization occur without Authentication?

Generally no. The user's identity must be verified first.


Best Practices

  • Always authenticate users before granting access.
  • Follow least privilege principles.
  • Use role-based security.
  • Encrypt passwords using BCrypt.
  • Protect sensitive endpoints.

Frequently Asked Questions (FAQ)

Can multiple roles be assigned to a user?

Yes. A user may have multiple roles and permissions.


Is JWT Authentication or Authorization?

JWT primarily supports Authentication but can also carry authorization information such as roles.


Do all applications require Authorization?

Most enterprise applications require authorization to protect resources.


Conclusion

Authentication and Authorization are core security concepts in Spring Security. Authentication verifies identity while Authorization determines permissions. Understanding the difference between these concepts is essential for designing secure applications and succeeding in Spring Security interviews.


Keywords

Authentication vs Authorization, Spring Security Authentication, Spring Security Authorization, Spring Boot Security, RBAC Spring Security, Security Interview Questions, Spring Security Tutorial, Role Based Access Control, Authentication Example, Authorization Example, Spring Boot Authentication, Spring Boot Authorization, SecurityFilterChain, Java Security, Enterprise Application Security

Authentication vs Authorization in Spring Security with Real Examples Authentication vs Authorization in Spring Security with Real Examples Reviewed by 13thGhost on 12:27 PM Rating: 5

Spring Security Explained for Beginners with Real Examples

12:19 PM

Security is one of the most important requirements of modern web applications. Without proper security controls, unauthorized users may access sensitive information and business functionality.


Spring Security is the official security framework for Spring applications that provides authentication, authorization and protection against common security threats.


What is Spring Security?

Spring Security is a framework that helps secure Spring applications.

It provides:

  • Authentication
  • Authorization
  • Password Protection
  • CSRF Protection
  • Session Management
  • Role-Based Access Control

Why Do We Need Spring Security?

Imagine an online banking application.

Without security:



Anyone
      |
      v
View Accounts

Transfer Money

Access Customer Data

Clearly this is dangerous.

Spring Security ensures only authorised users can access sensitive resources.


Authentication vs Authorization

These terms are frequently confused.


Authentication

Authentication answers:


Who are you?

Example:



Username:
admin

Password:
secret123

Spring verifies the identity of the user.


Authorization

Authorization answers:


What are you allowed to do?

Example:



ADMIN
    |
    +---- Create User

    +---- Delete User

USER
    |
    +---- View Profile

After authentication, Spring determines permissions.


Spring Security Flow


User Request
      |
      v
Security Filter Chain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Controller

Every incoming request passes through Spring Security.


Add Spring Security Dependency

Add the following dependency to pom.xml.



<dependency>

    <groupId>
        org.springframework.boot
    </groupId>

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

</dependency>

What Happens After Adding Dependency?

Spring Boot automatically secures all endpoints.

When you start the application, a generated password appears in the console.



Using generated security password:

8c3f1c9d-xxxx-yyyy-zzzz

This default user can access the application.


Securing an API


@RestController

@RequestMapping("/api")
public class EmployeeController {

    @GetMapping("/employees")
    public String employees() {

        return "Employees Data";

    }
}

After adding Spring Security, authentication is required automatically.


Configure In-Memory Users


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails admin =

        User.builder()

            .username("admin")

            .password(
                passwordEncoder()
                    .encode("admin123")
            )

            .roles("ADMIN")

            .build();

    return new InMemoryUserDetailsManager(
        admin
    );
}

This creates a simple in-memory administrator account.


Password Encoding

Passwords should never be stored as plain text.



@Bean

public PasswordEncoder
passwordEncoder() {

    return new BCryptPasswordEncoder();

}

BCrypt is one of the most commonly used password encoders.


Role-Based Security

Spring Security supports roles.


ADMIN

USER

MANAGER

Endpoints can be restricted to specific roles.


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

)

Only ADMIN users can access those endpoints.


SecurityFilterChain Configuration


@Bean

public SecurityFilterChain
securityFilterChain(
    HttpSecurity http
) throws Exception {

    http

        .authorizeHttpRequests(

            auth -> auth

                .anyRequest()

                .authenticated()

        )

        .formLogin();

    return http.build();

}

This tells Spring Security to require authentication for all requests.


Common Security Features

  • Authentication
  • Authorization
  • Password Encryption
  • Session Management
  • CSRF Protection
  • Role Management

Real World Example

Consider an e-commerce application.



Customer
      |
      +---- View Products

Admin
      |
      +---- Add Products

      +---- Remove Products

      +---- Manage Orders

Different users have different access levels.

Spring Security manages these permissions.


Common Interview Questions

What is Spring Security?

A framework that provides authentication and authorization for Spring applications.


What is Authentication?

Authentication verifies the identity of a user.


What is Authorization?

Authorization determines what a user is allowed to do.


What is SecurityFilterChain?

A component that defines security rules for incoming requests.


Why use BCryptPasswordEncoder?

To securely store encrypted passwords instead of plain text passwords.


Best Practices

  • Always encrypt passwords.
  • Use role-based access control.
  • Never store passwords in plain text.
  • Secure sensitive endpoints.
  • Apply the principle of least privilege.

Frequently Asked Questions (FAQ)

Does Spring Boot provide Security automatically?

Yes. Adding Spring Security dependency automatically secures endpoints.


Can Spring Security work with JWT?

Yes. JWT is commonly used in modern REST APIs.


Can Spring Security secure REST APIs?

Yes. It is widely used to secure RESTful applications.


Conclusion

Spring Security is the standard framework for securing Spring Boot applications. Understanding Authentication, Authorization, SecurityFilterChain, Password Encoding and Role-Based Access Control provides a strong foundation for building secure enterprise applications.


Keywords

Spring Security Tutorial, Spring Security Basics, Spring Boot Security, Authentication vs Authorization, SecurityFilterChain, BCryptPasswordEncoder, Spring Boot Authentication, Spring Boot Authorization, Spring Security Interview Questions, Spring Boot REST Security, Role Based Access Control, Secure Spring Boot APIs, Java Backend Security, Spring Framework Security, Enterprise Java Security

Spring Security Explained for Beginners with Real Examples Spring Security Explained for Beginners with Real Examples Reviewed by 13thGhost on 12:19 PM Rating: 5

Top 25 Spring Data JPA Interview Questions and Answers for Experienced Developers

11:47 AM

Spring Data JPA is one of the most widely used persistence frameworks in enterprise Java applications. As a result, it is frequently discussed in Spring Boot interviews ranging from beginner to architect-level positions.


This article covers some of the most frequently asked Spring Data JPA interview questions along with concise explanations.


1. What is Spring Data JPA?

Spring Data JPA is a framework built on top of JPA that simplifies database access by reducing boilerplate code and providing repository-based data access.


2. What is JPA?

JPA (Java Persistence API) is a specification for managing relational data in Java applications.

It defines how Java objects are mapped to database tables.


3. Is JPA a Framework?

No.

JPA is a specification. Hibernate is one of the most popular implementations of JPA.


4. What is Hibernate?

Hibernate is an ORM framework that implements JPA and provides additional features such as caching, lazy loading and performance optimization.


5. What is ORM?

Object Relational Mapping (ORM) is a technique that maps Java objects to database tables.


6. What is an Entity?

An Entity is a Java class mapped to a database table using the @Entity annotation.



@Entity
public class Employee {

}

7. What is JpaRepository?

JpaRepository is the most commonly used Spring Data JPA repository interface that provides CRUD, Pagination, Sorting and JPA-specific functionality.


8. Difference Between CrudRepository and JpaRepository?

CrudRepository provides basic CRUD functionality. JpaRepository extends CrudRepository and adds Pagination, Sorting and batch operations.


9. What is @Id?

@Id identifies the primary key of an entity.



@Id
private Long id;

10. What is @GeneratedValue?

@GeneratedValue automatically generates primary key values.


11. What is @Transactional?

@Transactional manages database transactions and ensures operations are committed or rolled back together.


12. What Are ACID Properties?

  • Atomicity
  • Consistency
  • Isolation
  • Durability

13. What is FetchType.LAZY?

Related entities are loaded only when explicitly accessed.


14. What is FetchType.EAGER?

Related entities are loaded immediately with the parent entity.


15. Which Fetch Strategy Is Preferred?

LAZY loading is generally preferred because it improves performance and reduces unnecessary database queries.


16. What is the N+1 Query Problem?

The N+1 Query Problem occurs when Hibernate executes one query for parent entities and additional queries for each child entity.


It can significantly impact performance.


17. How Can N+1 Be Solved?

  • Fetch Join
  • Entity Graph
  • DTO Projection

18. What is JPQL?

JPQL is an object-oriented query language that works with entities rather than database tables.


19. What is a Native Query?

A Native Query is a standard SQL query executed directly against the database.


20. Difference Between JPQL and Native Query?

JPQL is database-independent and entity-based. Native Queries use actual table names and database-specific SQL.


21. What Are Cascade Types?

Cascade Types control how operations such as save, update and delete are propagated from parent entities to child entities.


22. What is CascadeType.ALL?

CascadeType.ALL enables all available cascade operations:



PERSIST

MERGE

REMOVE

REFRESH

DETACH

23. What is First Level Cache?

First Level Cache is a session-scoped cache automatically provided by Hibernate.


24. What is Second Level Cache?

Second Level Cache is shared across multiple sessions and reduces database access for frequently requested data.


25. What Are Common JPA Relationship Types?

  • @OneToOne
  • @OneToMany
  • @ManyToOne
  • @ManyToMany

Bonus Question: Which Repository Should Be Used in Most Spring Boot Applications?

JpaRepository is generally the preferred choice because it includes CRUD, Pagination, Sorting and JPA-specific features.


Quick Revision Table

Topic Key Point
JPA Specification
Hibernate JPA Implementation
JpaRepository CRUD + Pagination + Sorting
@Transactional Manages Transactions
LAZY Load On Demand
EAGER Load Immediately
N+1 Performance Problem
JPQL Entity-Based Query
Native Query SQL Query
First Level Cache Session Scoped
Second Level Cache Shared Cache

Best Practices for Interviews

  • Understand entity relationships.
  • Know transaction management.
  • Learn FetchType differences.
  • Understand N+1 Query Problem.
  • Be comfortable with JpaRepository.
  • Know caching concepts.
  • Practice explaining real-world examples.

Conclusion

Spring Data JPA remains one of the most important technologies in modern Spring Boot development. Understanding repositories, transactions, relationships, fetching strategies, caching and query optimization will significantly improve both interview performance and real-world application development skills.


Keywords

Spring Data JPA Interview Questions, Spring Boot Interview Questions, JPA Interview Questions, Hibernate Interview Questions, JpaRepository Questions, @Transactional Interview Questions, JPQL Interview Questions, FetchType Lazy vs Eager, N+1 Query Problem, Hibernate Cache, Spring Data JPA Tutorial, Enterprise Java Interview Questions, Backend Developer Interview Questions, Java Persistence API, Spring Boot Development

Top 25 Spring Data JPA Interview Questions and Answers for Experienced Developers Top 25 Spring Data JPA Interview Questions and Answers for Experienced Developers Reviewed by 13thGhost on 11:47 AM Rating: 5

Recommended Posts

Powered by Blogger.