Java Backend Developer Interview Prep

Java Backend Developer Interview Prep: Comprehensive Answers & Examples

The Java Backend Developer interview  covers foundational and advanced Java concepts, Stream API, Spring Boot, security, microservices, and more. Here’s a comprehensive guide with explanations and code snippets for each question from the interview:

Stream API Programming Questions

1. Get employee names whose age is greater than 26

List<Employee> employees = ...; // your list
List<String> names = employees.stream()
    .filter(e -> e.getAge() > 26)
    .map(Employee::getName)
    .collect(Collectors.toList());


Explanation: Filters employees older than 26 and extracts their names.

2. Group employees based on their department

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


Explanation: Utilizes groupingBy to organize employees by department.

3. Convert employee names to uppercase

List<String> upperNames = employees.stream()
    .map(e -> e.getName().toUpperCase())
    .collect(Collectors.toList());


Explanation: Converts each employee name to uppercase.

3a. Find the highest salary among all employees

double maxSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .max()
    .orElse(0.0);


Explanation: Maps salaries to a DoubleStream and retrieves the maximum.

3b. Get employees with more than 5 years of experience

List<Employee> experienced = employees.stream()
    .filter(e -> e.getExperience() > 5)
    .collect(Collectors.toList());


Explanation: Filters employees whose experience is greater than 5 years.

3c. Count employees in each department

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


Explanation: Groups and counts employees per department.

Project & Technical Questions

4. Tell me about your project experience

When responding, use the STAR method (Situation, Task, Action, Result).
Example:
"I worked on an e-commerce backend using Spring Boot and microservices. My tasks involved designing REST APIs, implementing authentication, and ensuring high performance. I used Spring Security for secure endpoints, and implemented microservice communication with REST and RabbitMQ. The project improved client onboarding time by 30%."

5. What are all the methods available in the Object class?

  • equals(Object obj)
  • hashCode()
  • toString()
  • getClass()
  • clone()
  • finalize()
  • wait(), notify(), notifyAll()

These methods provide default behaviors for objects, such as equality checks, string representation, and thread synchronization.

6. How do you handle global exceptions in Spring Boot?

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAll(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
    }
}


Explanation: Intercepts exceptions from all controllers and provides a unified response.

7. What are all the Spring annotations you have used in your projects?

  • @RestController, @Controller, @Service, @Repository, @Component
  • @Autowired, @Qualifier
  • @RequestMapping, @GetMapping, @PostMapping, etc.
  • @PathVariable, @RequestParam, @RequestBody
  • @Configuration, @Bean
  • @Transactional
  • @Value, @PropertySource
  • @EnableAutoConfiguration, @SpringBootApplication

8. What is a Garbage Collector, and how does it work?

The Java Garbage Collector (GC) automatically frees memory by removing objects no longer referenced. It primarily includes:
- Young Generation: New objects, frequent collection.
- Old Generation: Long-lived objects.
- Major/Minor GC: Minor for young generation, major for old.
Garbage collection algorithms (like G1, CMS) use mark-and-sweep and reference counting.

9. Are you familiar with Swagger API documentation?

Yes. Swagger (now OpenAPI) automates REST API documentation.
In Spring Boot, add Swagger using the springfox-swagger2 and springfox-swagger-ui dependencies, and annotate controllers:

@EnableSwagger2
public class SwaggerConfig { ... }

@ApiOperation(value = "Get employee by ID")
@GetMapping("/employee/{id}")
public Employee getEmployee(@PathVariable Long id) { ... }


It produces interactive docs, e.g., at /swagger-ui.html.

10. Are you familiar with logging frameworks?

Yes, in Java I’ve used SLF4J with Logback and Log4j.

private static final Logger logger = LoggerFactory.getLogger(MyClass.class);

logger.info("Employee created: {}", employeeId);
logger.error("Error in process", ex);


  • Log levels: TRACE, DEBUG, INFO, WARN, ERROR.
  • Logging is configurable via properties or XML.

11. Are you familiar with Spring Security?

Yes, Spring Security handles authentication and authorization, supporting role-based access, JWT, OAuth2, custom filters, etc.

12. How do you implement Spring Security in a Java application?

Basic setup:

  1. Add Spring Security dependency.
  2. Extend WebSecurityConfigurerAdapter (Spring Boot <2.7) or use SecurityFilterChain bean.
  3. Configure in-memory, JDBC, or JWT authentication.
  4. Secure endpoints using @PreAuthorize, @Secured, or via config.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and().formLogin();
    }
}


13. Explain about JWT tokens, refresh tokens, and role-based access controls

  • JWT (JSON Web Token): Compact, secure way to transmit info between parties as a JSON object. Used for stateless authentication; server validates token via secret or public key.
  • Refresh token: Long-lived token to obtain new JWT without re-login, stored securely and used to maintain sessions.
  • Role-based access control: Users are granted roles; endpoints authorize based on roles, e.g., @PreAuthorize("hasRole('ADMIN')").

14. Do you have experience with microservices?

Yes. Example:
"On my recent project, I designed distributed modules handling inventory, order, and payments as independent Spring Boot microservices communicating via REST and RabbitMQ, deploying via Docker and Kubernetes."

15. How do you handle communication between two microservices?

  • REST APIs: Synchronous, HTTP-based communication
  • Messaging queues: (e.g., RabbitMQ, Kafka) for asynchronous communication
  • Service discovery: (e.g., Eureka) to help services dynamically find each other

Example:

// Using RestTemplate/WebClient for REST calls
RestTemplate restTemplate = new RestTemplate();
Employee emp = restTemplate.getForObject("http://service-url/employees/1", Employee.class);


16. Have you implemented any fault-tolerance design patterns in your projects?

Yes. Common patterns:

  • Circuit Breaker: Prevents cascading failures (with resilience4j/Hystrix)
  • Retry: Automatically retry failed requests
  • Fallback: Provide default responses on failure
Example using Resilience4j:

@CircuitBreaker(name = "employeeService", fallbackMethod = "fallbackEmployee")
public Employee getEmployee(int id) { ... }


17. How does service discovery work in the Microservices Architecture?

Service discovery enables microservices to find and communicate without hard-coding locations. Tools:
- Eureka: Registers each service instance; others query registry for endpoints.
- Consul, Zookeeper: Other popular solutions.
Benefits: Load balancing, scaling, resilience.

Key Takeaways for Java Backend Interviews

  • Master core Java, Stream API—write code daily.
  • Get hands-on with Spring Boot and microservices by building mini-projects.
  • Understand security, logging, exception handling as critical engineering skills.
  • Apply clean code, testable and modular patterns.

By preparing detailed answers and examples as shown, you’ll demonstrate both deep technical skill and practical, project-based experience, positioning you to succeed in Java backend interviews.

Previous Post Next Post

Blog ads

ads