Java & Spring Boot Interview Questions
with Answers
3. Redis:
▲ What is Redis?
Redis (Remote Dictionary Server) is an in-memory data structure store used as a database, cache,
and message broker. It supports data structures such as strings, hashes, lists, sets, and sorted sets
with range queries, bitmaps, and geospatial indexes.
▲ How to fetch map values from Redis
To fetch map (hash) values:
```
@Autowired
private StringRedisTemplate redisTemplate;
Map<Object, Object> entries = redisTemplate.opsForHash().entries("employee:1001");
```
4. Microservices:
▲ Step-by-step implementation of RestTemplate
1. Add dependency (if not included with Spring Boot).
2. Configure Bean:
```
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
```
3. Autowire and use:
```
@Autowired
private RestTemplate restTemplate;
String response = restTemplate.getForObject("http://service-url/api/data", String.class);
```
▲ Circuit Breaker pattern – Syntax (Using Resilience4j)
```
@CircuitBreaker(name = "backendService", fallbackMethod = "fallbackMethod")
public String callExternalService() {
return restTemplate.getForObject("http://external-service/api", String.class);
}
public String fallbackMethod(Throwable t) {
return "Fallback response due to error: " + t.getMessage();
}
```
5. Java Concurrency:
▲ Synchronous vs Asynchronous processing
- Synchronous: Tasks are executed sequentially; the caller waits for the response.
- Asynchronous: Tasks run in the background; the caller doesn’t wait for completion, improving
responsiveness.
▲ How to implement async in Java
Using `@Async`:
```
@EnableAsync
@SpringBootApplication
public class AppConfig {}
@Async
public CompletableFuture<String> processAsync() {
return CompletableFuture.completedFuture("Completed");
}
```
6. Threads and Locks:
▲ Basics and real-world usage of thread locks
Thread locks prevent concurrent modification of shared resources. Real-world example: In a banking
app, prevent multiple withdrawals from the same account at the same time.
▲ Banking scenario with thread lock
```
public class BankAccount {
private final Lock lock = new ReentrantLock();
private int balance;
public void withdraw(int amount) {
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
}
} finally {
lock.unlock();
}
}
}
```
7. Spring Boot Performance:
▲ Tuning techniques and best practices
- Use connection pooling (HikariCP)
- Enable caching (e.g., Redis)
- Optimize SQL queries and indexing
- Use @Transactional wisely
- Profile and monitor with Actuator & Micrometer
- Avoid N+1 query problem
8. Spring Security & JWT:
▲ JWT implementation and User validation
1. Generate Token:
```
String token = Jwts.builder()
.setSubject(username)
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
```
2. Validate Token:
```
String user = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()
.getSubject();
```
9. SQL Indexing:
▲ What is indexing?
Indexing improves query performance by allowing the database to find rows faster without scanning
the entire table.
▲ Query to apply index on salary column
```
CREATE INDEX idx_salary ON employee(salary);
```
10. SQL Querying:
▲ Find 2nd highest salary without using OFFSET
```
SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
```
11. Spring Batch:
▲ Techniques to improve DB performance and reduce load
- Use chunk-oriented processing
- Apply pagination in readers
- Use multithreading or partitioning
- Optimize commit interval
- Use job repository with persistent storage
13. DevOps Insight:
▲ What is Docker and its importance in deployments
Docker is a containerization tool that packages applications and dependencies into containers,
ensuring consistency across environments. It simplifies deployments, scaling, and microservices
orchestration.