Java & spring interview questions

 


Java and Spring interview questions 


Java is a high-level, object-oriented, platform-independent programming language. It is widely used for building enterprise-scale applications, web apps, mobile apps (Android), and backend systems.


Spring is a powerful, lightweight framework for building Java applications. It simplifies Java development by providing features like dependency injection, aspect-oriented programming, data access abstraction, and transaction management.


1. What is a marker interface?

A marker interface in Java is an interface with no methods or fields. It serves as a tag to provide metadata to the JVM or frameworks. Examples: Serializable, Cloneable.


2. Why use a marker interface?

Marker interfaces are used to indicate that a class has a certain property or should be treated in a special way (e.g., Serializable enables serialization).


3. When to use interface and abstract class?

Use interface to define a contract with no implementation. Use abstract class when you want to provide partial implementation or maintain state.


4. What is the use of constructor in Java?

Constructors initialize new objects. They are called when an object is created and can set default values.


5. What is a static method?

A static method belongs to the class, not instances. It can be called without creating an object.


6. Can we use static method in constructor?

Yes, you can call static methods from a constructor, but you cannot declare a constructor as static.


7. What is the contract between hashCode() and equals() methods?

- If two objects are equal (equals), they must have the same hashCode.

- If two objects have the same hashCode, they may or may not be equal.


8. What is fail-fast iteration and how to resolve it?

Fail-fast iterators throw ConcurrentModificationException if the collection is modified during iteration. To resolve, use CopyOnWriteArrayList or use iterator.remove().


9. What are virtual threads?

Virtual threads are lightweight threads introduced in Project Loom. They provide high concurrency and are more scalable than traditional threads.


10. Difference between map vs flatMap in Java 8?

- map(): transforms elements.

- flatMap(): transforms and flattens nested collections like Stream<Stream<T>>.


11. What are sealed classes?

Sealed classes restrict which other classes can extend them. Introduced in Java 17 to improve type safety.


12. What are Spring Boot advantages?

- Auto-configuration

- Embedded servers

- Easy dependency management

- Fast development with minimal configuration

- Built-in monitoring and health checks via Actuator


13. What is ApplicationContext?

It is the central interface to the Spring IoC container and provides configuration, bean lifecycle, and event propagation support.


14. What are the scopes in Spring?

  • - Singleton
  • - Prototype
  • - Request
  • - Session
  • - GlobalSession


15. Difference between prototype and request scope?

- Prototype: a new instance every time it's injected.

- Request: one instance per HTTP request (only valid in web apps).


16. What are components of Kafka?

  • - Producer
  • - Consumer
  • - Topic
  • - Partition
  • - Broker
  • - Zookeeper (older versions)


17. What is partition in Kafka?

Partitions allow a topic to be split into multiple segments. They enable parallelism and increase throughput.


18. How to handle if consumer keeps on reading same messages?

Use manual or auto-commit offset properly and ensure the consumer group ID is correctly set.


19. How to handle Dependency Injection in Spring Boot?

Use @Autowired for injection, @Component, @Service, @Repository for bean definition, and @Bean for manual bean creation.


20. What is Authentication & Authorization?

- Authentication: Verifies user identity.

- Authorization: Determines access level/permissions.


21. What are the error codes used?

  • - 200: OK
  • - 201: Created
  • - 400: Bad Request
  • - 401: Unauthorized
  • - 403: Forbidden
  • - 404: Not Found
  • - 500: Internal Server Error
  • - 503: Service Unavailable


22. What is 404, 402, 502, 503, 401 error codes?

  1. - 404: Not Found
  2. - 402: Payment Required (reserved)
  3. - 502: Bad Gateway
  4. - 503: Service Unavailable
  5. - 401: Unauthorized


23. How to handle "Not Found" error?

Use @ExceptionHandler or @ResponseStatus(HttpStatus.NOT_FOUND) in controller exception handling.


24. What is the issue behind "Bad Request" error?

Usually caused by invalid or missing input parameters or malformed requests.


25. What is @Mockito?

Mockito is a mocking framework used to mock objects in unit testing.


26. When and when not to use @Mock?

Use @Mock to simulate objects that aren’t essential for the logic under test. Don’t use it when real interactions are required.


27. What is Error and Exception?

- Error: Serious issues like OutOfMemoryError, not meant to be caught.

- Exception: Recoverable conditions that can be handled in code.


28. How to handle OutOfMemoryException?

  • - Optimize memory usage
  • - Increase heap size
  • - Use memory profilers to identify leaks


29. How to handle "Service Not Found" error even when beans are properly registered?

Check:

- Component scan path

- Bean scope mismatch

- Typo in @Autowired or @Qualifier


30. How to debug in local and remote repository?

- Local: Use IDE debugging tools.

- Remote: Enable debug port, use remote debugger or logging.


31. How to create pipeline and deploy in Jenkins?

- Create Jenkinsfile

- Define build, test, deploy stages

- Use GitHub/GitLab for source control

- Configure plugins and environment


32. What happens when there is a collision in HashMap?

Multiple keys with same hashCode are stored in a bucket using a linked list or tree (Java 8+).


33. What is hashCode() and equals() method and its uses?

These methods are used in collections like HashMap and HashSet to determine object equality and storage location.


34. What is multithreading? How multithreading is implemented in your project?

Multithreading allows parallel execution. Used via Thread, Runnable, ExecutorService, or Java concurrency utilities.


35. What is NullPointerException? and How is it handled?

Occurs when you access a member or method on a null reference. Use Optional, null checks, or Objects.requireNonNull().


36. Is server port and debug port same?

No. Server port is used by the application server. Debug port is for attaching debuggers (e.g., 5005).


37. DB @Bean and @Autowired?

- @Bean: Method-level declaration for creating beans.

- @Autowired: Injects beans into dependent classes.


39. What is FunctionalInterface?

An interface with a single abstract method. Used for lambda expressions. Example: Runnable, Comparator.


40. What is ClassCastException?

Thrown when trying to cast an object to an incompatible type.


41. How to handle Gateway Timeout and Se

rvice Unavailable error in project?

- Implement retry logic

- Use Circuit Breakers like Resilience4j

- Increase client/server timeouts

- Monitor service health

Post a Comment

0 Comments