0% found this document useful (0 votes)
9 views

Java-InterviewQuestions

sample
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java-InterviewQuestions

sample
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

HTML

1. (Easy) What are HTML attributes?


Answer: Attributes provide additional information about an element, e.g., href for <a> or src for <img>.

2. (Moderate) How do you create an accessible navigation menu?


Answer: Use <nav> for semantic grouping, ARIA roles (role="navigation"), and keyboard navigation.

3. (Difficult) Explain the difference between semantic and non-semantic elements.


Answer: Semantic elements like <header>, <article> convey meaning, while non-semantic elements like <div>
do not.

4. (Tricky) What are the implications of omitting alt attributes for images?
Answer: Screen readers cannot describe the image, impacting accessibility and SEO.

CSS

5. (Easy) What are pseudo-elements in CSS? Provide examples.


Answer: Pseudo-elements target parts of an element, e.g., ::before and ::after.

6. (Moderate) How does the z-index property work?


Answer: Determines stacking order. Higher values appear on top; only works on positioned elements.

7. (Difficult) How would you implement a flexbox-based layout for a responsive navbar?
Answer: Use display: flex; and properties like justify-content and align-items for alignment.

8. (Tricky) What is the difference between relative units (em, rem) and absolute units (px, cm)?
Answer: Relative units scale with context; absolute units are fixed regardless of screen size.

Bootstrap

9. (Easy) What are the advantages of using Bootstrap?


Answer: Speeds up development with pre-built components, responsive grid, and CSS utilities.

10. (Moderate) How do you use Bootstrap's modal component?


Answer: Include data-toggle="modal" and data-target="#modalId" attributes in a button/link.

11. (Difficult) How would you customize Bootstrap themes?


Answer: Use SASS/SCSS variables or override default styles with custom CSS.

12. (Tricky) What is the difference between btn-primary and btn-outline-primary classes in Bootstrap?
Answer: btn-primary has a filled background, while btn-outline-primary has a transparent background with a
border.

ES6 and TypeScript

13. (Easy) What are arrow functions, and how are they different from regular functions?
Answer: Arrow functions have a concise syntax and do not bind their own this.

14. (Moderate) Explain destructuring in ES6 with an example.


Answer: Extract values from arrays or objects:
javascript

Copy code

const {name, age} = person;

15. (Difficult) What are TypeScript decorators, and how do you create one?
Answer: Metadata annotations used to modify classes or methods. Example:

typescript

Copy code

function Log(target: any, propertyKey: string) {

console.log(`${propertyKey} was called`);

16. (Tricky) How does the readonly modifier work in TypeScript?


Answer: Prevents reassignment of properties after initialization.

Angular

17. (Easy) What is the role of ngFor in Angular?


Answer: Iterates over a collection and renders the DOM for each item.

18. (Moderate) How do you share data between components in Angular?


Answer: Use @Input for parent-to-child communication and @Output with EventEmitter for child-to-parent.

19. (Difficult) What is Dependency Injection (DI), and how does Angular implement it?
Answer: DI is a design pattern where dependencies are injected into components. Angular provides services
using providers in modules or components.

20. (Tricky) What is Ahead-of-Time (AOT) Compilation in Angular?


Answer: Pre-compiles Angular templates during the build process, improving performance and reducing
runtime errors.

Core Java

21. (Easy) What are Java’s primitive data types?


Answer: byte, short, int, long, float, double, char, and boolean.

22. (Moderate) How does Java achieve platform independence?


Answer: Java compiles code into bytecode, which is interpreted by the JVM on any platform.

23. (Difficult) What is the difference between abstract classes and interfaces?
Answer: Abstract classes allow defined and undefined methods, while interfaces (before Java 8) allowed only
abstract methods. Interfaces support multiple inheritance.

24. (Tricky) Explain the difference between == and .equals() in Java.


Answer: == compares references, while .equals() compares values (if overridden).
Hibernate

25. (Easy) What is Hibernate?


Answer: An ORM framework for mapping Java objects to database tables.

26. (Moderate) What is the use of @Entity and @Table annotations?


Answer: @Entity marks a class as a table, and @Table specifies the table name and schema.

27. (Difficult) What is the role of SessionFactory in Hibernate?


Answer: It creates Session objects and manages connection pooling.

28. (Tricky) How would you handle a One-to-Many relationship in Hibernate?


Answer: Use @OneToMany and @JoinColumn annotations.

Spring

29. (Easy) What is the difference between BeanFactory and ApplicationContext?


Answer: ApplicationContext is a superset of BeanFactory, offering additional features like event handling.

30. (Moderate) What is the purpose of Spring Boot's application.properties file?


Answer: Configures application settings like database connections and server ports.

31. (Difficult) Explain the use of @Transactional annotation in Spring.


Answer: Manages transaction boundaries and rollback behavior.

32. (Tricky) What are some common pitfalls of using Spring’s @Autowired?
Answer: Circular dependencies and lack of explicit bean definitions.

DevOps

33. (Easy) What is Docker, and why is it used?


Answer: Docker containerizes applications, ensuring consistency across environments.

34. (Moderate) What is the difference between CI and CD?


Answer: CI (Continuous Integration) automates code testing and merging; CD (Continuous Deployment)
automates releasing to production.

35. (Difficult) How do you monitor logs in a Kubernetes environment?


Answer: Use tools like ELK Stack or kubectl logs for individual pods.

36. (Tricky) What is a Helm chart, and why is it used in Kubernetes?


Answer: Helm is a package manager for Kubernetes, used for deploying and managing complex applications.

Advanced Java Topics

37. (Easy) What is a functional interface in Java?


Answer: An interface with a single abstract method, e.g., Runnable.

38. (Moderate) What are Java Streams, and how do they differ from collections?
Answer: Streams process data in a functional style and are lazily evaluated, while collections store data.
39. (Difficult) What is a CompletableFuture, and how does it differ from Future?
Answer: CompletableFuture supports non-blocking and chaining operations, unlike Future.

40. (Tricky) How do you avoid deadlocks in Java?


Answer: Use consistent lock ordering, timeout-based locking, or ReentrantLock.

Advanced Java Topics (Continued)

41. (Easy) What is the difference between a HashSet and a TreeSet?


Answer: HashSet is unordered and based on hashing, while TreeSet is ordered and uses a Red-Black tree.

42. (Moderate) What is the significance of the final keyword in Java?


Answer: It prevents reassignment for variables, inheritance for classes, and overriding for methods.

43. (Difficult) What are Phantom References in Java?


Answer: A Phantom Reference is used to track objects that are being finalized by the Garbage Collector.

44. (Tricky) Explain how the try-with-resources statement works.


Answer: Automatically closes resources implementing AutoCloseable when the block exits, even during
exceptions.

Spring (Continued)

45. (Easy) What is the difference between @Component and @Service annotations?
Answer: Both mark beans, but @Service is semantically intended for business logic.

46. (Moderate) How does Spring handle bean scopes?


Answer: Scopes like singleton, prototype, request, and session determine the lifecycle of beans.

47. (Difficult) What is the @EnableAutoConfiguration annotation in Spring Boot?


Answer: Triggers auto-configuration of Spring Boot applications based on classpath dependencies.

48. (Tricky) How do you implement event-driven programming in Spring?


Answer: Use @EventListener and ApplicationEventPublisher to publish and listen for events.

Hibernate (Continued)

49. (Easy) What is the purpose of the @GeneratedValue annotation in Hibernate?


Answer: Automatically generates unique primary key values for entities.

50. (Moderate) How does the @Cache annotation work in Hibernate?


Answer: Enables second-level caching for an entity with caching strategies like READ_ONLY.

51. (Difficult) What are Hibernate’s fetching strategies?


Answer:

o Lazy Fetching: Loads relationships only when accessed.

o Eager Fetching: Loads relationships immediately.

52. (Tricky) How would you optimize a Hibernate query that performs poorly due to N+1 issues?
Answer: Use JOIN FETCH or @EntityGraph to fetch relationships in a single query.
Database and SQL

53. (Easy) What are the different types of SQL joins?


Answer: INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.

54. (Moderate) How do you use indexes to optimize database performance?


Answer: Index frequently queried columns to speed up search operations.

55. (Difficult) What is the difference between OLTP and OLAP systems?
Answer: OLTP handles transaction-oriented tasks (e.g., banking), while OLAP supports analytical processing
(e.g., data warehousing).

56. (Tricky) How do you handle database migrations in production environments?


Answer: Use tools like Flyway or Liquibase for versioned schema updates.

Angular (Continued)

57. (Easy) What is the purpose of Angular pipes?


Answer: Transform data in templates, e.g., date, uppercase, or custom pipes.

58. (Moderate) How does Angular manage routes?


Answer: Uses RouterModule with Routes configuration for navigation.

59. (Difficult) What are Angular Guards, and how do you use them?
Answer: Guards control route access. Example: CanActivate prevents unauthorized users from accessing a
route.

60. (Tricky) Explain how Angular uses Zones for change detection.
Answer: Zones monkey-patch asynchronous APIs to trigger change detection after tasks like setTimeout.

JavaScript and ES6 (Continued)

61. (Easy) What is the difference between map() and forEach() in JavaScript?
Answer: map() returns a new array, while forEach() executes a function for each element without returning.

62. (Moderate) How do promises work in JavaScript?


Answer: Promises handle asynchronous operations with states (pending, fulfilled, rejected) and methods like
.then() and .catch().

63. (Difficult) What is the purpose of async/await in JavaScript?


Answer: Simplifies promises by allowing synchronous-like code for asynchronous tasks.

64. (Tricky) How does the Event Loop work in JavaScript?


Answer: Handles asynchronous callbacks using the call stack, task queue, and microtask queue.

DevOps (Continued)

65. (Easy) What is a container, and how does it differ from a virtual machine?
Answer: Containers are lightweight and share the host OS, while VMs include the entire OS.

66. (Moderate) How do you set up a basic Jenkins job?


Answer: Configure a new job with SCM settings, build steps, and post-build actions.
67. (Difficult) What are Kubernetes pods, and why are they important?
Answer: Pods are the smallest deployable units in Kubernetes, encapsulating one or more containers.

68. (Tricky) What is blue-green deployment? How would you implement it?
Answer: It’s a zero-downtime deployment strategy where two environments (blue and green) are alternated.
Use Kubernetes services to switch traffic between environments.

Design Patterns

69. (Easy) What is the Singleton pattern?


Answer: Ensures a class has only one instance and provides global access to it.

70. (Moderate) What is the Factory Method pattern?


Answer: Defines an interface for creating objects but allows subclasses to alter the type of objects.

71. (Difficult) What is the Observer pattern?


Answer: Allows objects (observers) to listen and react to changes in another object (subject).

72. (Tricky) How would you implement the Builder pattern for constructing immutable objects?
Answer: Use chained methods in a Builder class to set properties and return the immutable object.

Concurrency in Java

73. (Easy) What is the difference between synchronized and Lock?


Answer: Lock offers finer control and supports try-locking, while synchronized is simpler but less flexible.

74. (Moderate) How does the volatile keyword work?


Answer: Ensures visibility of changes to variables across threads.

75. (Difficult) What is the Fork/Join framework?


Answer: Splits tasks into smaller subtasks, executes them recursively, and merges the results.

76. (Tricky) How do you prevent deadlocks in multithreaded applications?


Answer: Avoid circular dependencies, use timeouts for locks, and implement lock ordering.

Advanced Topics

77. (Easy) What is a Stream in Java?


Answer: A sequence of elements supporting functional-style operations.

78. (Moderate) How do you implement parallel streams?


Answer: Use .parallelStream() for data processing across multiple threads.

79. (Difficult) What is the CompletableFuture API?


Answer: An extension of Future with chaining and non-blocking features.

80. (Tricky) What are Phasers in Java concurrency?


Answer: Advanced synchronization tools for managing dynamic parties in concurrent tasks.

Testing
81. (Easy) What is JUnit used for?
Answer: Unit testing Java applications.

82. (Moderate) How do you parameterize tests in JUnit?


Answer: Use @ParameterizedTest and @ValueSource.

83. (Difficult) How do you mock dependencies in a Spring application?


Answer: Use @Mock and @InjectMocks with Mockito.

84. (Tricky) What are some best practices for writing effective test cases?
Answer: Use meaningful names, isolate dependencies, and cover edge cases.

Advanced Topics (Continued)

85. (Easy) What is the difference between a shallow copy and a deep copy in Java?
Answer: A shallow copy copies object references, while a deep copy duplicates the entire object, including
referenced objects.

86. (Moderate) What are WeakHashMaps in Java? How do they differ from HashMaps?
Answer: A WeakHashMap uses weak references for keys, allowing them to be garbage collected when no
strong references exist. HashMap uses strong references, preventing garbage collection.

87. (Difficult) How does the Garbage Collector handle circular references in Java?
Answer: Java's Garbage Collector uses algorithms like Mark-and-Sweep that can detect and collect circular
references.

88. (Tricky) How would you implement a thread-safe Singleton in Java?


Answer: Use double-checked locking with volatile:

java

Copy code

class Singleton {

private static volatile Singleton instance;

private Singleton() {}

public static Singleton getInstance() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

return instance;

}
}

Spring (Continued)

89. (Easy) What are @Primary and @Qualifier annotations in Spring?


Answer: @Primary marks a default bean for autowiring, while @Qualifier specifies which bean to use when
multiple options exist.

90. (Moderate) What is the purpose of the @RestControllerAdvice annotation in Spring?


Answer: Centralized exception handling for RESTful controllers.

91. (Difficult) How does Spring manage transactions with nested method calls?
Answer: Nested transactions use propagation behaviors like REQUIRED, REQUIRES_NEW, and NESTED.

92. (Tricky) How would you secure sensitive configuration properties in Spring Boot?
Answer: Use tools like Spring Cloud Config with encryption or the jasypt-spring-boot library to encrypt
sensitive values.

Hibernate (Continued)

93. (Easy) What is a Hibernate Query Language (HQL)?


Answer: HQL is an object-oriented query language for Hibernate, similar to SQL but operates on entity
objects.

94. (Moderate) What is the difference between getCurrentSession and openSession in Hibernate?
Answer: getCurrentSession uses a single session per transaction, while openSession creates a new session
every time.

95. (Difficult) How do you handle batching in Hibernate?


Answer: Use Hibernate properties like hibernate.jdbc.batch_size to optimize multiple inserts/updates.

96. (Tricky) What are dynamic inserts and updates in Hibernate, and when would you use them?
Answer: They only include non-null fields in SQL statements, improving efficiency for sparse data updates.

Microservices and DevOps

97. (Easy) What is an API Gateway in a microservices architecture?


Answer: A single entry point for routing, authentication, and monitoring microservices.

98. (Moderate) What is the Circuit Breaker pattern, and how does it work?
Answer: Protects services from cascading failures by stopping requests to a failing service after a threshold.

99. (Difficult) How do you implement centralized logging in a microservices architecture?


Answer: Use tools like the ELK Stack (Elasticsearch, Logstash, Kibana) or Fluentd for aggregating logs.

100. (Tricky) How would you implement service discovery in a Kubernetes-based microservices setup?
Answer: Use Kubernetes’ built-in DNS or service mesh tools like Istio to dynamically discover services.

1. E-Commerce Platform with Full-Stack Integration

• Objective: Build a dynamic e-commerce platform using Java Spring Boot (backend) and Angular/React
(frontend).
• Features:

o User authentication with JWT.

o Product listing with categories, filtering, and search.

o Shopping cart with concurrency control for multi-user sessions.

o Payment integration using a mock API.

o RESTful APIs secured using Spring Security.

• Skills Tested:

o Full-stack development, REST API design, and security.

2. Employee Management System

• Objective: Create a CRUD-based employee management system using Spring Boot, Hibernate, and
Thymeleaf.

• Features:

o Add, update, and delete employee details.

o Role-based access control (Admin/User).

o Integration with a MySQL/PostgreSQL database.

o Generate employee performance reports using JasperReports.

• Skills Tested:

o MVC architecture, Hibernate ORM, and templating.

3. Hotel Reservation System

• Objective: Design a system to manage hotel reservations using Spring MVC and Hibernate.

• Features:

o Room availability checking and booking.

o User login and registration.

o Invoice generation for bookings.

o Admin dashboard to manage rooms and pricing.

• Skills Tested:

o Relational database design, authentication, and Hibernate relationships.

4. Real-Time Chat Application

• Objective: Build a real-time chat application using Java Spring Boot and WebSockets.
• Features:

o User authentication and friend list management.

o Real-time messaging using WebSocket and STOMP protocol.

o Chat history stored in MongoDB.

o Group chat functionality.

• Skills Tested:

o Real-time communication, WebSocket integration, and MongoDB usage.

5. Library Management System

• Objective: Develop a library system to manage book inventory and user activities using JavaFX for the
frontend and Spring Boot for the backend.

• Features:

o Book lending and return functionality.

o User fines calculation for overdue books.

o Admin panel for adding/removing books.

o Reports on most borrowed books.

• Skills Tested:

o Desktop application development, relational databases, and backend APIs.

6. Online Exam Portal

• Objective: Create an online exam portal for conducting timed quizzes using Spring Boot and Hibernate.

• Features:

o User login and registration.

o Question bank with categories and difficulty levels.

o Timer-based exam submission.

o Result analysis with a leaderboard.

• Skills Tested:

o Transaction management, Hibernate relationships, and session handling.

7. Task Management Application

• Objective: Build a task management application using Java Spring Boot and React/Angular.

• Features:
o User authentication and role-based permissions.

o Create, update, delete, and assign tasks to team members.

o Real-time status updates using WebSockets.

o Push notifications for task deadlines.

• Skills Tested:

o REST API design, WebSockets, and frontend-backend integration.

8. RESTful Microservices for Movie Ticket Booking

• Objective: Design a microservices-based movie ticket booking system using Spring Boot.

• Features:

o Separate services for user management, movie catalog, and ticket booking.

o Centralized configuration using Spring Cloud Config.

o Service discovery with Eureka and API Gateway integration.

o Resilience with Circuit Breaker (Hystrix or Resilience4J).

• Skills Tested:

o Microservices architecture, resilience patterns, and distributed logging.

9. Banking System with Distributed Architecture

• Objective: Develop a distributed banking system using Spring Boot and Kafka.

• Features:

o Account management and transaction history.

o Fund transfer using Kafka for asynchronous communication.

o Fraud detection alerts for suspicious transactions.

o Integration with Elasticsearch for transaction searching.

• Skills Tested:

o Kafka, distributed systems, and Elasticsearch.

10. Image Sharing Platform

• Objective: Create an image-sharing platform like Instagram using Spring Boot, Hibernate, and Angular/React.

• Features:

o User registration and login.

o Image upload with size and format validations.


o Like, comment, and share features for images.

o Image storage using Amazon S3 or a local file system.

• Skills Tested:

o File handling, cloud integration, and frontend-backend interaction.

Project Selection Guidance

• Junior Developers: Focus on simpler CRUD-based projects like the Library Management System or Employee
Management System.

• Mid-Level Developers: Assign projects like E-Commerce Platform, Task Management Application, or Hotel
Reservation System to test API and database integration.

• Senior Developers: Assign challenging projects like Microservices for Movie Ticket Booking, Banking System,
or Image Sharing Platform to evaluate architectural skills and advanced problem-solving.

Let me know if you need additional details or enhancements for any of these projects!

You might also like