Java Interview Questions & Answers
All 200 unique questions in one place — 62 easy, 94 medium, 44 hard — grouped by topic.
Practise by topic
Practise the way your interview works
Why is Java called platform independent?
Show answer
What are the primitive data types in Java and their sizes?
Show answer
What is the difference between == and equals() in Java?
Show answer
What is the difference between a static and an instance variable?
Show answer
Why is the main method public static void?
Show answer
What is the difference between final, finally and finalize?
Show answer
What does the var keyword do and where can it not be used?
Show answer
Write a Java program to check whether a number is prime.
Show answer
Write Java code to reverse an integer without converting it to a string.
Show answer
Why did you choose Java for your career?
Show answer
Explain the main memory areas of the JVM.
Show answer
What is garbage collection and how does the JVM decide an object is garbage?
Show answer
What is the role of the JIT compiler?
Show answer
What is autoboxing and what pitfall can it cause?
Show answer
What is a ClassLoader and what is the delegation model?
Show answer
An application gets StackOverflowError in a recursive method. What do you do?
Show answer
A team member compares two Integer values with == and the check fails only for large numbers. Explain.
Show answer
Which JVM flags would you set to start a production service with a 4 GB heap, G1 and a heap dump on OOM?
Show answer
How do you take a thread dump and a heap dump of a running Java process?
Show answer
Tell me about a time you found and fixed a difficult production bug in a Java application.
Show answer
Compare the G1, ZGC and Parallel garbage collectors.
Show answer
Your service throws OutOfMemoryError: Java heap space in production. How do you investigate?
Show answer
Users report the app is slow for the first few minutes after every deployment. Why might this happen?
Show answer
GC pauses of two seconds are causing request timeouts. How would you reduce them?
Show answer
What are the four pillars of OOP? Explain with Java examples.
Show answer
What is the difference between method overloading and method overriding?
Show answer
Why does Java not support multiple inheritance of classes?
Show answer
What is constructor chaining?
Show answer
Can you override a static or private method in Java?
Show answer
Show runtime polymorphism with a simple Java example.
Show answer
How do you explain OOP concepts to a junior developer who is new to Java?
Show answer
What is the difference between an abstract class and an interface in modern Java?
Show answer
What is the contract between equals() and hashCode()?
Show answer
How do you make a class immutable in Java?
Show answer
What is the difference between composition and inheritance, and which should you prefer?
Show answer
Explain the SOLID principles briefly.
Show answer
What are records in Java and when should you use them?
Show answer
What is the difference between static and dynamic binding?
Show answer
You need to add a new payment method to a system that has a big if-else on payment type. How would you redesign it?
Show answer
Objects used as HashMap keys cannot be found after insertion. What could be wrong?
Show answer
A getter returns an internal List and callers modify it, causing bugs. How do you fix this?
Show answer
Write a thread safe singleton class in Java.
Show answer
Implement equals() and hashCode() for an Employee class with id and email.
Show answer
Implement the Builder pattern for a User class with many optional fields.
Show answer
Write a record with validation in its compact constructor.
Show answer
Describe a time you improved the design of existing code.
Show answer
What are sealed classes and how do they help?
Show answer
What is the Liskov Substitution Principle? Give an example of breaking it.
Show answer
A deep inheritance hierarchy of six levels is hard to change. How would you refactor it?
Show answer
Why are String objects immutable in Java?
Show answer
What is the String constant pool?
Show answer
Compare String, StringBuilder and StringBuffer.
Show answer
What is the difference between checked and unchecked exceptions?
Show answer
What is try-with-resources?
Show answer
What is the difference between throw and throws?
Show answer
What are text blocks in Java?
Show answer
Write a Java method to check whether a string is a palindrome, ignoring case and non-letters.
Show answer
Count the frequency of each character in a string using Java.
Show answer
Write code to check if two strings are anagrams.
Show answer
How do you handle disagreement with a reviewer about your code?
Show answer
Does the finally block always execute?
Show answer
How do you create a custom exception and when should you?
Show answer
What is exception chaining?
Show answer
Is it good practice to catch Exception or Throwable?
Show answer
A log file shows a NullPointerException only for some users. How do you debug it?
Show answer
Code builds a large CSV report with String += inside a loop and it is very slow. Why and what is the fix?
Show answer
Exceptions are being swallowed with empty catch blocks in your codebase. How would you fix this?
Show answer
Your REST API returns stack traces to clients when errors happen. How do you design proper error handling?
Show answer
Write a custom unchecked exception and a Spring handler that returns HTTP 404.
Show answer
Find the first non-repeating character in a string.
Show answer
Read a large text file line by line efficiently and count lines containing ERROR.
Show answer
Tell me about a time a production incident happened because of your code.
Show answer
A file handle leak causes Too many open files errors after a day. What is the likely cause?
Show answer
Should a service layer throw checked or unchecked exceptions? Defend your choice.
Show answer
Explain the hierarchy of the Java Collections Framework.
Show answer
What is the difference between ArrayList and LinkedList?
Show answer
What is the difference between HashMap, LinkedHashMap and TreeMap?
Show answer
What is the difference between Comparable and Comparator?
Show answer
How does HashSet work internally?
Show answer
You need to remove items from an ArrayList while looping over it. How do you do it safely?
Show answer
Sort a list of employees by department, then by salary descending.
Show answer
Write a Java solution for the Two Sum problem using a HashMap.
Show answer
Remove duplicates from a list while keeping the original order.
Show answer
How do you prepare for coding rounds as a Java developer?
Show answer
How does HashMap work internally?
Show answer
What is the difference between HashMap and ConcurrentHashMap?
Show answer
What are fail-fast and fail-safe iterators?
Show answer
What is the difference between List.of(), Arrays.asList() and Collections.unmodifiableList()?
Show answer
You need a cache that evicts the least recently used item when full. How would you build it in Java?
Show answer
A HashMap shared by many threads sometimes loses updates. How do you fix it?
Show answer
You have to process tasks in order of priority. Which collection do you use?
Show answer
An API needs to find the price band for any amount, for example the nearest lower slab. Which structure fits?
Show answer
Implement an LRU cache using LinkedHashMap.
Show answer
Group a list of orders by city and sum the amount per city.
Show answer
When would you choose ArrayDeque over Stack and LinkedList?
Show answer
Tell me about a time you improved performance by choosing a better data structure.
Show answer
Why must you be careful when initial capacity of a HashMap is too small?
Show answer
Memory usage is high because millions of Integer objects are stored in an ArrayList. What would you do?
Show answer
Find the top K most frequent words in a list.
Show answer
What are the ways to create a thread in Java?
Show answer
What is the difference between start() and run()?
Show answer
What is the difference between wait() and sleep()?
Show answer
How do you keep up with new Java releases?
Show answer
What does the volatile keyword guarantee?
Show answer
What is the difference between synchronized and ReentrantLock?
Show answer
What is a deadlock and how can it be prevented?
Show answer
What are virtual threads and when should you use them?
Show answer
How does ExecutorService work and why use a thread pool?
Show answer
A counter shared between threads shows wrong totals. How do you fix it?
Show answer
An API calls three independent downstream services one after another and takes 900 ms. How would you speed it up?
Show answer
Implement a producer-consumer using BlockingQueue.
Show answer
Run two tasks in parallel with CompletableFuture and combine their results.
Show answer
Print numbers 1 to 10 alternately from two threads (odd and even).
Show answer
Write code that runs 10,000 blocking tasks using virtual threads.
Show answer
Use CountDownLatch to wait for three worker threads to finish.
Show answer
Describe a situation where you had to deliver under a tight deadline.
Show answer
Explain the happens-before relationship in the Java Memory Model.
Show answer
What is CompletableFuture and how is it better than Future?
Show answer
Your application hangs and CPU is near zero. How do you find out why?
Show answer
After moving to virtual threads, throughput did not improve and some requests stalled. What could cause it?
Show answer
A thread pool fills up and tasks get rejected during traffic spikes. How do you handle it?
Show answer
Two scheduled jobs on different servers process the same records twice. How do you prevent this?
Show answer
How would you write a simple thread safe rate limiter in Java?
Show answer
Tell me about a time you solved a concurrency bug.
Show answer
What is a functional interface?
Show answer
What is the difference between intermediate and terminal operations in streams?
Show answer
What is the difference between map() and flatMap()?
Show answer
What are method references? Give the four types.
Show answer
A team member chains Optional.get() everywhere and gets NoSuchElementException. What do you suggest?
Show answer
Find the second highest salary from a list of employees using streams.
Show answer
Write a stream to partition numbers into even and odd lists.
Show answer
Join a list of names into a comma separated string with brackets using streams.
Show answer
How do you handle feedback that your code is too clever?
Show answer
What is Optional and how should it be used?
Show answer
What does effectively final mean for lambdas?
Show answer
What is the difference between Collectors.toMap() and groupingBy()?
Show answer
A stream pipeline that updates a shared ArrayList in forEach gives random results with parallel(). Why?
Show answer
toMap() throws Duplicate key exception in production. How do you fix it?
Show answer
Legacy code uses anonymous classes and loops everywhere. How would you modernise it safely?
Show answer
Using streams, find the employee with the highest salary in each department.
Show answer
Write a sealed interface with records and a switch that computes area.
Show answer
Flatten a list of lists of integers and compute the sum of squares of the even numbers.
Show answer
Tell me about a time you made a codebase more readable.
Show answer
Describe a time you had to learn a new technology quickly.
Show answer
When should you avoid parallel streams?
Show answer
Explain pattern matching for switch and record patterns in Java 21.
Show answer
What is the difference between reduce() and collect()?
Show answer
You need to process a 5 GB file using streams without running out of memory. How?
Show answer
A stream over a list of orders is slow in a hot path. How do you analyse it?
Show answer
What are the main steps to connect to a database with JDBC?
Show answer
Why is PreparedStatement preferred over Statement?
Show answer
Write a JDBC method to fetch a user by email safely.
Show answer
How do you handle a situation where you made a wrong technical decision?
Show answer
What is the difference between JPA, Hibernate and Spring Data JPA?
Show answer
What is the N+1 select problem in Hibernate and how do you fix it?
Show answer
What is the difference between lazy and eager loading?
Show answer
Explain the entity lifecycle states in JPA.
Show answer
An API listing 100 orders fires 101 SQL queries. How do you fix it?
Show answer
Users get LazyInitializationException when the API returns an entity. What is happening?
Show answer
A query is fast in development but takes 8 seconds in production. How do you investigate?
Show answer
Map a one-to-many relation between Order and OrderItem in JPA.
Show answer
Write a Spring Data JPA repository method that fetches orders with items to avoid N+1.
Show answer
Write a JDBC batch insert for a list of products.
Show answer
Tell me about a time you optimised a slow database query.
Show answer
How do you make sure database changes are released safely?
Show answer
What is the first level and second level cache in Hibernate?
Show answer
What are transaction isolation levels and which problems do they prevent?
Show answer
What is optimistic versus pessimistic locking in JPA?
Show answer
Why is connection pooling important and how do you size a pool?
Show answer
A batch job inserting 1 lakh rows through JPA takes 30 minutes. How do you speed it up?
Show answer
Two users booking the last seat both succeed. How do you prevent double booking?
Show answer
Production shows Connection is not available, request timed out after 30000ms from HikariCP. What do you check?
Show answer
Add optimistic locking to an entity and handle the conflict.
Show answer
Write a JPQL query that returns a DTO projection instead of entities.
Show answer
What is Spring Boot and how is it different from the Spring Framework?
Show answer
What is dependency injection and why is constructor injection preferred?
Show answer
What is the difference between @Component, @Service, @Repository and @Controller?
Show answer
Write a simple REST controller in Spring Boot for creating and fetching products.
Show answer
Why should we hire you as a Java backend developer?
Show answer
How does Spring Boot auto-configuration work?
Show answer
Explain bean scopes in Spring.
Show answer
What is Spring Boot Actuator used for?
Show answer
A @Transactional method is not rolling back after an exception. What could be wrong?
Show answer
You must expose configuration that differs between dev, QA and production. How do you manage it?
Show answer
Clients report duplicate orders when they retry after a timeout. How do you prevent it?
Show answer
Write a unit test for a service class using JUnit 5 and Mockito.
Show answer
Bind typed configuration properties with validation in Spring Boot.
Show answer
Write a minimal Dockerfile for a Spring Boot application.
Show answer
How do you mentor junior developers on your team?
Show answer
How does @Transactional work and what are its common pitfalls?
Show answer
What are the key patterns used in microservices built with Spring Boot?
Show answer
How does JWT based authentication work in a Spring Boot API?
Show answer
A downstream payment service is slow and your API threads pile up. How do you protect your service?
Show answer
How would you split a monolith into microservices?
Show answer
An order must update inventory and payment in different services. How do you keep data consistent?
Show answer
Your Spring Boot service takes 40 seconds to start in Kubernetes and pods get killed. How do you fix it?
Show answer
Configure a Resilience4j circuit breaker on a client call in Spring Boot.
Show answer
Write a Kafka producer and consumer in Spring Boot.
Show answer
Tell me about a microservice you designed end to end.
Show answer
Frequently asked questions
What jobs can I get after learning Java?
Java leads to roles such as Java developer, backend developer, Spring Boot developer, full stack Java developer and later senior engineer or solution architect. IT services companies hire many Java freshers every year, and banks, fintechs, ecommerce firms and global capability centres hire experienced Java engineers for backend and microservice work. Java skills also help in automation testing with Selenium and in Android development.
Who can join a Java course?
Anyone who wants a software development career can learn Java, including BTech, BCA, MCA, BSc and diploma students, fresh graduates and working professionals switching from support, testing or non-IT roles. No prior coding experience is required, because the course starts from basics like variables and loops. Basic computer skills and logical thinking are enough, and regular practice matters more than your degree.
How long does it take to learn Java for a job?
With two to three hours of daily study, most learners become comfortable with core Java in about two months and job ready with Spring Boot, JPA and projects in about four months. The 16 week plan in this course follows that path. Interview readiness also needs DSA practice in Java, so plan a few extra weeks of coding problems alongside the course.
Is Java still in demand in 2026?
Yes. Java remains one of the most used backend languages in India and worldwide, especially in banking, insurance, ecommerce, payments and large enterprise systems. Regular LTS releases like Java 21 and Java 25, virtual threads and Spring Boot 3 keep it modern. Job portals consistently list Java and Spring Boot among the most requested skills for backend developers.
Which Java certification is useful?
The Oracle Certified Professional Java SE Developer certification, for Java 17 or Java 21, is the most recognised Java credential and proves strong core language knowledge. Spring Professional certification from Broadcom adds value for Spring roles. Certificates help with shortlisting, but recruiters still give more weight to projects on GitHub, problem solving ability and how well you explain your work in interviews.
Should I learn Java or Python first?
Choose based on your goal. Java is a strong first language for backend development, enterprise jobs, Android and campus placements, because many coding rounds and services companies use it. Python is better for data science, machine learning and scripting. Java's strict typing and OOP build strong fundamentals, and learning Python later becomes easy once you know Java well.