← Back to list

Top Java Interview Questions with Scenario-Based Answers (Spring Boot + SQL)

This article covers 20 must-know Java and Spring Boot interview questions, including scenario-based questions, advanced SQL concepts…

Coder_Ninja · 2026-05-09 05:43 · 1 claps · 3.1 min read
#java-interview-questions #spring-boat #scenario-based-question #java-scenario-base-questi #interview-questions
Open on Medium ↗

Top Java Interview Questions with Scenario-Based Answers (Spring Boot + SQL)

This article covers 20 must-know Java and Spring Boot interview questions, including scenario-based questions, advanced SQL concepts, interface vs abstract class differences, important Spring Boot annotations, and hard-level questions frequently asked in real company interviews. These questions are based on practical development experience and commonly asked for backend and microservices roles.Spring Boot & Java Interview Questions

1. REST API returns old cached data. How do you fix it?

Answer:

  • Check if response caching is enabled.
  • Use proper cache keys.
  • Add cache expiration (TTL).
  • Use @CacheEvict to clear old cache.
  • Verify CacheManager configuration.
  • Check browser/API gateway cache also.

Example:

@CacheEvict(value = "users", allEntries = true)

2. Two microservices communicate using REST API. One service is slow. How do you debug it?

Answer:

  • Check API response time.
  • Analyze logs and server health.
  • Verify database queries.
  • Check load balancer configuration.
  • Verify timeout settings.
  • Analyze loops/heavy processing in code.
  • Monitor CPU and memory usage.

3. One public API should not require authentication. How do you manage it?

Answer:

Use Spring Security configuration.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/public/**").permitAll()
    .anyRequest().authenticated()
);
  • Public APIs use permitAll()
  • Protected APIs require authentication.

4. Application works locally but not on server. What do you check?

Answer:

  • Database credentials
  • Active Spring profile (prod)
  • Environment variables
  • Hardcoded paths
  • SSL configuration
  • Server logs
  • Network/port access
  • Dependency version mismatch

5. API is slow because of large data. How do you improve performance?

Answer:

  • Use pagination
  • Add database indexing
  • Avoid unnecessary data fetch
  • Use projections/DTOs
  • Optimize SQL queries
  • Enable caching if needed

Pagination example:

Pageable pageable = PageRequest.of(0, 10);

6. How do you secure configuration values?

Answer:

  • Store configs in external files
  • Use environment variables
  • Encrypt sensitive data
  • Never hardcode passwords
  • Use Spring Cloud Config/Vault

7. Scheduled job runs multiple times in Spring Boot. Why?

Answer:

Possible reasons:

  • Multiple application instances running
  • Multiple schedulers enabled
  • Cluster environment issue

Solution:

  • Use distributed locking
  • Configure single scheduler instance

Example:

@EnableScheduling

8. File upload API fails for large files. How do you fix it?

Answer:

Increase multipart file size limit.

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB
  • Check server upload limit
  • Verify reverse proxy limits (Nginx/Apache)

9. After Spring Boot upgrade, custom bean stops working. Why?

Answer:

  • Deprecated APIs removed
  • Auto-configuration conflict
  • Bean initialization changes
  • Dependency incompatibility

Fix:

  • Update deprecated code
  • Check migration guide
  • Use exclusions if required

Example:

@SpringBootApplication(exclude = SecurityAutoConfiguration.class

10. API returns empty response but data exists in DB. What do you check?

Answer:

  • Verify query conditions
  • Check mapping issues
  • Validate request parameters
  • Debug service layer
  • Check transaction handling
  • Verify serialization issues

11. How do you manage centralized configuration for multiple microservices?

Answer:

Use Spring Cloud Config Server.

Benefits:

  • Centralized config management
  • Shared configuration
  • Environment-specific configs
  • Dynamic refresh support

12. Two auto-configurations create the same bean. What happens?

Answer:

Spring throws:

NoUniqueBeanDefinitionException;

Fix:

  • Use @Primary
  • Use @Qualifier
  • Disable one auto-configuration

Example:

@Primary
@Bean
public MyService myService() {
    return new MyService();
}

13. What happens if no active profile is set in Spring Boot?

Answer:

Spring Boot uses the default profile.

Example:

spring.profiles.active=prod

14. Two repositories use the same entity. How do you manage conflicts?

Answer:

Use:

  • @Primary
  • @Qualifier
  • Separate repository configuration

15. Why is String immutable in Java?

Answer:

Reasons:

  • Security
  • Thread safety
  • Memory optimization (String Pool)
  • Hashcode caching

Example:

String s = "Java";
s.concat("Code");

Original string does not change.

16. How does HashMap work internally?

Answer:

  • HashMap stores data as key-value pairs.
  • Hashcode is calculated for the key.
  • Bucket index is identified.
  • Data is stored in buckets.
  • Collision handling:
  • LinkedList (Java 7)
  • Balanced Tree (Java 8+)

Steps:

  1. Calculate hash
  2. Find bucket
  3. Store/retrieve value

17. What is ConcurrentHashMap?

Answer:

ConcurrentHashMap is thread-safe.

Features:

  • Supports concurrent read/write
  • Better performance than Hashtable
  • Uses segment locking/internal synchronization

Example:

ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();

18. What are Design Patterns in Java?

Answer:

Design patterns are reusable solutions for common software problems.

Common patterns:

  • Singleton
  • Factory
  • Builder
  • Strategy
  • Observer

19. Difference between Lazy Singleton and Eager Singleton.

Lazy Singleton

Object created only when needed.

class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Eager Singleton

Object created during class loading.

class Singleton {
    private static final Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}

20. Why is Enum Singleton considered best?

Answer:

Because it:

  • Is thread-safe
  • Prevents serialization issues
  • Prevents reflection attacks
  • Easy to implement

Example:

public enum Singleton {
    INSTANCE;
}

21. What is an Immutable Class?

Answer:

An immutable class object cannot be modified after creation.

Rules:

  • Make class final
  • Fields should be private final
  • No setter methods
  • Initialize fields using constructor

Example:

final class Employee {
    private final String name;
    public Employee(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

메타데이터
post_id
3ba04ae58b5f
slug
top-20-java-interview-questions-with-scenario-based-answers-spring-boot-sql-3ba04ae58b5f
url
https://medium.com/@onkar20/top-20-java-interview-questions-with-scenario-based-answers-spring-boot-sql-3ba04ae58b5f
canonical_url
https://medium.com/@onkar20/top-20-java-interview-questions-with-scenario-based-answers-spring-boot-sql-3ba04ae58b5f
author_url
https://medium.com/@onkar20
status
ok
fetched_at
2026-06-20 20:29:01