Cracking core java interviews - question bank

Upasana | May 19, 2019 | 15 min read | 907 views

Java Question Bank

250+ Real Interview Questions on Core Java 8, Concurrency, Algorithms, Data Structures, Design Problems, Spring, Hibernate, Puzzles & Sample Interview Questions for Investment Banks, Startups and Product based companies.

Core Concepts, Spring & Hibernate

  1. What are good software practices for developing Scalable, Testable and Maintainable Software?

  2. What are good books for reference on Java Programming?

  3. What is Growth Road Map for a Java Developer?

  4. Why should I choose Java for Software Development? What are Pros and Cons of Java 8?

  5. What is difference between 32 bit and 64 bit versions of Java?

  6. What are four basic principles of OOP?

  7. What are the key paradigms for Developing the Clean Object Oriented Code?

  8. How much important is requirement gathering in software development process?

  9. What is Logarithm? Why is it relevant in Software Development?

  10. What do you understand by Big O notation, why is it important in software development?

  11. How would you determine the Time Complexity of a given algorithm, are there any general guidelines?

  12. What is a sorting algorithm ? List down sorting algorithms by their time & memory complexity in Big O notation? When do we call a sorting algorithm 'Stable'?

  13. Why Prime Numbers are given much importance in writing certain algorithms like hashcode()?

  14. What is left shift <<, right shift >> and Unsigned right shift >>> operator in Java? How are these useful?

  15. What is 2’s complement notation system for Binary Numbers?

  16. How Heap space is divided in Java. How does Garbage Collector cleans up the unused Objects ? Why shouldn’t we use System.gc() command in production code?

  17. What is difference between Stack and Heap area of JVM Memory? What is stored inside a stack and what goes into heap?

  18. What is a Binary Tree? Where and why is this used in Java Programs?

  19. Discuss implementation and uses of TreeSet Collection?

  20. How does Session handling works in Servlet environment?

  21. How can one handle relative context path while coding the web applications? For example, your web application may be deployed at a different context path in Tomcat, how will you make sure static/dynamic resources works well at custom context path ?38

  22. How will you write a Recursive Program?39

  23. How many elements a complete binary tree could hold for a depth of 10? 39

  24. Explain working of a hashing data structure, for example HashMap in Java.40

  25. Discuss internal’s of a concurrent hashmap provided by Java Collections Framework.41

  26. Why do we need Reader Classes when we already have Streams Classes? What are the benefit of using a Reader over a stream, in what scenario one should be preferred. 43

  27. Discuss Visitor, Template, Decorator, Strategy, Observer and Facade Design Patterns?44

  28. What is a strong, soft, weak and Phantom reference in Java? Where are these used?46

  29. What are database transaction Isolation levels?48

  30. What is difference between Primary key and Unique Key?49

  31. Why do we need indexing on Database Table Columns ?49

  32. What are clustered and non-clustered indexes in Sybase Database?50

  33. How would you handle lazily loaded entities in web application development using hibernate?50

  34. What are OneToOne, OneToMany and ManyToMany relationship mappings in database design?51

  35. How would you implement ManyToMany mappings with the self entity in JPA?52

  36. What is Inner Join, Left Outer Join and Right Outer Join?53

  37. How will you list all the Customers from Customer Table who have no Order(s) yet?54

  38. How would you fetch Employee with nth highest Age from Employee Table using SQL?54

  39. Question: What is difference between Drop, Truncate and Delete Table commands in SQL?54

  40. What are Inheritance strategies in JPA?55

  41. How will you handle Concurrent updates to an database entity in JPA i.e. when two users try to update the same database entity in parallel?55

  42. What are different types of Http Codes ?56

  43. What is difference between HTTP Redirect and Forward?56

  44. How will you check the owner information of a given domain name in web ?57

  45. What happens when you type in your browser’s address bar from an Indian Location?58

  46. What is Idiom for Creating a Hibernate Transaction ?60

  47. Why do we need Spring Framework ?60

  48. What is Inversion of Control (or Dependency Injection)?60

  49. What is Bean Factory in Spring?61

  50. What is Application Context?61

  51. What are different types of Dependency Injection that spring support ? or in other words what are the ways to initialize beans in Spring ?61

  52. What are different Bean Scope in Spring ?61

  53. What are some important Spring Modules ?61

  54. How will you load hierarchy of property files in Spring Context ?62

  55. How to efficiently generate ID’s for an Entity in Hibernate/JPA ?62

  56. How to handle Bean Post Initialization and Pre Destroy Tasks in Spring Framework ? For example resource loading after bean construction and resource cleanup before shutdown of spring context ?63

  57. How will you handle batch insert in hibernate for optimal usage of memory, network and CPU ?64

  58. How will you operate on records of a large database table with million of entries in it using Hibernate ?65

  59. Do you think Hibernate’s SessionFactory and Session objects are thread safe ?65

  60. What is difference between Hibernate’s first and second level cache ?66

  61. What is syntax of Cron Expression ?66

  62. Explain Stream API introduced in Java 8 ?67

  63. Most useful Code Snippets in Java 8 ?68

  64. How will you configure custom sized ThreadPool for stream parallel operation in Java 8 ?72

Core Java Questions

  1. What are new Features added in Java 8 ?73

  2. What is difference between method overloading, method overriding, method and variable hiding?74

  3. What is Order of calling constructors in case of Inheritance?75

  4. When should we choose Array, ArrayList, LinkedList over one another for a given Scenario and Why?76

  5. We have 3 Classes A, B an C. Class C extends Class B and Class B extends Class A. Each class has an method add(), is there a way to call A’s add() method from Class C ?77

  6. Why wait is always used inside while loop as shown in the below snippet ? Discuss all the probable reasons.

    public synchronized void put(T element) throws InterruptedException {
            while(queue.size() == capacity) {
  7. We have a method which iterates over a Collection. We want to remove certain elements from that collection inside the loop in certain criteria is matched, How should we code this scenario ?79

  8. We are writing an API which will accept a Collection<Integer> as an argument and duplicate an element in the Original Collection if certain criteria in met. How would you code such an API method ?80

  9. If hashcode() method of an object always returns 0 then what will be the impact on the functionality of software ?80

  10. Iterator interface provides remove() method but no add() method. What could be the reason for such behavior?

  11. What does Collections.unmodifiableCollection() do ? Is it a good idea to use it safely in multi-threading scenario without synchronization, Is it immutable ?81

  12. If we don’t override hashcode() while using a object in hashing collection, what will be the impact ?82

  13. How would you detect a DeadLock in a running program ? 82

  14. How would you avoid deadlock in a Java Program ?82

  15. Question : How would you produce DeadLock in Java ?83

  16. Which data type would you choose for storing currency values like Trading Price ? What’s your opinion about Float, Double and BigDecimal ?84

  17. How would you round a double value to certain decimal Precision and Scale ?86

  18. How great is the Idea of synchronizing the getter methods of a shared mutable state ? What if we don’t ?87

  19. Can the keys in Hashing data structure be made Mutable ?87

  20. Is it safe to iterate over collection returned by Collections.synchronizedCollection() method, or should we synchronize the Iterating code ?88

  21. What are different type of Inner classes in Java ? How to choose a type with example ?89

  22. When should we need a static inner class rather than creating a top level class in Java Program?89

  23. Is it possible to write a method in Java which swaps two int/Integer ?90

  24. What all collections utilizes hashcode() method ?90

  25. Provide a diagram for collections framework.91

  26. What is Immutable Class. Why would you choose it ? How would you make a class immutable ?92

  27. Why shouldn’t we prefer mutable static variables in our Java Code ?92

  28. Discuss Exception class hierarchy in Java. When should we extend our custom exception from RuntimeException or Exception ?93

  29. How does method parameter passing works in Java ? Does it pass-by-reference or pass-by-value ?94

  30. How does an ArrayList expands itself when its maximum capacity is reached ?94

  31. What is StringPool In Java ?94

  32. What is instance level locking and class level locking ?95

  33. Explain threading jargons ?96

  34. What is float-int implicit conversion while doing calculation on mixed data type in Java?97

  35. Discuss Comparable and Comparator ? Which one should be used in a given scenario ?97

  36. How would you sort a collection of data based on two properties of an entity in Java, analogical to SQL’s Order by firstField, SecondField desc ?98

  37. What are the best practices for handling TimeZone in database transactions ?99

  38. How would you convert time from One Time Zone to another in Java ?99

  39. Will WeakHashMap’s entry be collected if the value contains the only strong reference to the key ?100

  40. Why HashMap’s initial capacity must be power of two ?101

  41. Can we traverse the list and remove its elements in the same iteration loop ?101

  42. Do I need to override object’s equals() and hashcode() method for its use in a TreeMap ?101

  43. Implement a BlockingQueue using intrinsic locking mechanism.102

  44. Is there a way to acquire a single lock over ConcurrentHashMap instance ?102

  45. How will you implement a Blocking Queue using Lock and Condition Interface provided in JDK?102

  46. How would you cancel a method execution after time-out expires using Java Future?103

  47. Java already had Future interface, then why did they provide Completable Future class in Java 8 ?104

  48. What is difference between intrinsic synchronization and explicit locking using Lock ?106

  49. What are Stamped Locks ? How they are useful in Optimistic Scenario where thread contention is rare ?107

  50. What is difference between Executor’s submit() and execute() method ?109

  51. How will you find out first non-repeating character from a string ? For example, String input = "aaabbbeggh", answer should be 'e'109

  52. What is difference between Callable and Runnable Interface?110

  53. What will happen when an exception occurs from within a synchronized code block ? Will lock be retained or released ?110

  54. What is difference between sleep(), yield() and wait() method?110

  55. How does Generics work in Java? 112

  56. What are Upper and Lower bounds in Generics? Where to choose one?113

  57. Discuss memory visibility of final fields in multi-threading scenario.114

  58. Where would you use LinkedHashSet provided by Java Collections?116

  59. What do you think is the reason for String Class to be Immutable?116

  60. How is String concatenation implemented in Java using + operator? for example, String name = "munish" + "chandel"116

  61. Which Java data type would you choose for storing sensitive information, like passwords, and Why?117

  62. What is difference between StringBuilder and StringBuffer ?117

  63. What is difference between using Serializable & Externalizable Interfaces in Java?117

  64. How would you design Money Class in Java?

  65. Where should we use GET, PUT, POST and DELETE method?

  66. What is difference between HashMap, TreeMap and LinkedHashMap?119

  67. How would you write high performing IO code in Java? Can you write a sample code for calculating checksum of a file in time efficient manner?

  68. We have an Application and we want that only Single Instance should run for that Application. If Application is already running then second instance should never be started. How would you handle this in Java?

Concurrency in Java

  1. What is Concurrency? How will you implement Concurrency in your Java Programs?124

  2. There are two Threads A and B operating on a shared resource R, A needs to inform B that some important changes has happened in R. What technique would you use in Java to achieve this?

  3. What are the different states of a Thread? What does those states tells us?126

  4. Question: What do you understand by Java Memory Model? What is double-checked locking? What is different about final variables in new JMM?127

  5. Is i++ thread-safe (increment operation on primitive types)? 131

  6. What happens when wait() & notify() method are called?131

  7. Discuss about volatile keyword and Java Memory Model?132

  8. What is a CAS? How does it help writing non-blocking scalable applications? Tell something about Atomic Package provided by Java 1.6133

  9. There is a object state which is represented by two variables. How would you write a high throughput non-blocking algorithm to update the state from multiple threads?134

  10. How would you implement AtomicFloat /AtomicDouble using CAS?135

  11. How LongAdder and LongAccumulator are different from AtomicLong & AtomicInteger ?137

  12. Can we implement check & update method (similar to compare and swap) using volatile alone?137

  13. How will you track the largest value monitored by different threads in an non-blocking fashion (using Atomic Operations) ?137

  14. What is difference between Fork/Join framework and ExecutorService ?138

  15. How does ForkJoinPool helps in writing concurrent applications ? Please provide few examples for RecursiveTask and RecursiveAction.138

  16. How will you calculate Fibonacci Sequence on a multi-core processor ?141

  17. How will you increment each element of an Integer array, utilizing all the cores of processor ?142

  18. You are writing a multi-threaded software piece for NSE for maintaining the volume of Trades made by its individual brokers (icici direct, reliance ). It’s highly concurrent scenario and we can not use lock based thread safety due to high demand of throughput. How would handle such scenario?143

  19. Calculate the time spread for 10 threads - Suppose T1 started earliest and T5 finished last, then the difference between T5 and T1 will give time spread. 144

  20. What are fail-fast Iterator? what is fail safe?146

  21. There is a stream of words which contains Anagrams. How would you print anagrams in a single bucket from that stream?147

  22. Describe CopyOnWriteArrayList? Where is it used in Java Applications?148

  23. There are M number of Threads who work on N number of shared synchronized resources. How would you make sure that deadlock does not happen?148

  24. Are there concurrent version for TreeMap and TreeSet in Java Collections Framework?148

  25. Is it safe to iterate over an ArrayList and remove its elements at the same time ? When do we get ConcurrentModificationException & hidden Iterator?149

  26. What is ThreadLocal class, how does it help writing multi-threading code? any usage with example?150

  27. How would you implement your own Transaction Handler in Core Java, using the EntityManager created in last question?151

  28. What is AtomicInteger class and how is it different than using volatile or synchronized in a concurrent environment?152

  29. You are writing a server application which converts microsoft word documents into pdf format. Under the hood you are launching a binary executable which does the actual conversion of document. How would you restrict the parallel launch of such binaries to 5 in Java, so as to limit the total load on the server.153

  30. What are common threading issues faced by Java Developers?155

Algorithms & Data Structures

  1. ​Given a collection of 1 million integers ranging from 1 to 9, how would you sort them in Big O(n) time?156

  2. Given 1 million trades objects, you need to write a method that searches if the specified trade is contained in the collection or not. Which collection would you choose for storing these 1 million trades and why?157

  3. I have an Integer array where every number appears even number of time except one. Find that number.157

  4. how would you check if a number is even or odd using bit wise operator in Java?158

  5. How would you check if the given number is power of 2?158

  6. What is a PriorityQueue? How is it implemented in Java? What are its uses?159

  7. What is difference between Collections.sort() and Arrays.sort()? Which one is better in terms of time efficiency?160

  8. There are 1 billion cell-phone numbers each having 10 digits, all of them stored randomly in a file. How would you check if there exists any duplicate? Only 10 MB RAM is available to the system.160

  9. What is a Binary Search Tree? Does Java provide implementation for BST? How do you do in-order, pre-order and post-order Traversal of its elements?161

  10. What is technique to sort data that is too large to bring into memory ?162

  11. Check if a binary tree is a Binary Search Tree or not?162

  12. How would you convert a sorted integer array to height balanced Binary Search Tree? Input: Array {1, 2, 3} Output: A Balanced BST 2 / \ 1 3163

  13. How would you calculate depth of a binary tree?

  14. Calculate factorial using recursive method.

  15. How will you swap two numbers using XOR operation?

  16. You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger. But it is not possible to directly compare two nuts or two bolts. Given an efficient method for solving the problem.

  17. Your are give a file with 1 million numbers in it. How would you find the 20 biggest numbers out of this file?

  18. Reverse the bits of a number and check if the number is palindrome or not?

  19. How would you mirror a Binary Tree?

  20. How to calculate exponentiation of a number using squaring for performance reason?

  21. How will you implement a Queue from scratch in Java?

  22. How will you Implement a Stack using the Queue?

  23. How would you implement a simple Math.random() method for a given range say (1-16)?

  24. How an elevator decides priority of a given request. Suppose you are in an elevator at 5th floor and one person presses 7th floor and then 2nd presses 8th floor. which data structure will be helpful to prioritize the requests? 170

  25. How would you multiply a number with 7 using bitwise hacks?171

  26. What is best way to search an element from a sorted Integer Array? What will be its time complexity?

  27. How would you reverse a Singly linked List?

  28. How would you count word occurrence in a very large file ? How to keep track of top 10 occurring words?

  29. What is difference between synchronized HashMap and a hashtable?

  30. What is difference between Iterator and LisIterator?

  31. What do you understand by Token Bucket Algorithm. What is its use?

  32. How will you implement fibonacci series using Iterative & Recursive approach in Java 8?

  33. How will you write a multi-threaded HttpDownloader program using Java 8?

  34. How will you find first non-repeatable character from a String using Java 8?

  35. How will you find Word Frequency in sorted order for a collection of words?

  36. How will you calculate MD5 hash of a given String in Java?

Object Oriented Design

  1. What are the key principles when designing a software for performance efficiency?

  2. How would you describe Producer Consumer problem in Java ?185

  3. How would you implement a Caching for HttpDownloader Task using Decorator Design Pattern?

  4. Write Object Oriented design for library management system.

  5. Design ATM machine.

  6. Design a web crawler that will crawl for links(urls).

  7. Design Phone Book for a mobile using TRIE (also known as prefix tree).

  8. How would you resolve task’s inter dependency, just as in maven/ant. Let’s consider the following task dependencies. Here first row states that task 3 is dependent on task 1 and task 5, and so on. If the two consecutive tasks have no dependency, then they can be run in any order. The output should look like - [1, 5, 3, 2 ,4] or [1, 5, 3, 4, 2]194

  9. How would you sort 900 MB of data using 100 MB of RAM ? What is external sort?

  10. How would you design minimum number of platforms so that the buses can be accommodated as per their schedule ? Bus Schedule for a given Platform

  11. There is a pricing service which connects to Reuters & Bloomberg and fetches the latest price for the given Instrument Tics. There could be multiple price events for the same Stock and we need to consider the latest one. Design a service to show prices for the Top 10 stocks of the Day ?203

  12. Design a parking lot where cars and motorcycles can be parked. What data structure to use for finding free parking spot in Parking Lot program? Assume there are million of parking slots.203

  13. Implement the classes to model two pieces of furniture (Desk and Chair) that can be constructed of one of two kinds of materials (Steel and Oak). The classes representing every piece of furniture must have a method getIgnitionPoint() that returns the integer temperature at which its material will combust. The design must be extensible to allow other pieces of furniture and other materials to be added later. Do not use multiple inheritance to implement the classes.

  14. How would you simulate a digital Clock in Object Oriented Programming Language?

  15. How would you design an elevator system for multi story building? Provide with request scheduling algorithm & Class diagram for the design.

  16. Given two log files, each with a billion username (each username appended to the log file), find the username existing in both documents in the most efficient manner?

  17. Design DVD renting system, database table, class and interface.

Puzzles & Misc

  1. Why man holes are round in shape?

  2. Solve two egg problem?

  3. There are 100 doors all closed initially.
    1st iteration opens all doors (1x multiplier)
    2nd iteration opens 2,4,6,8 .. doors (2x multiplier)
    3rd iteration opens 3,6,9,12 …​ doors (3x multiplier) and so on. In the end of 100 iterations, which all doors will be in open state?

  4. What is probability of a daat, hitting closer to centre of a circle rather than circumference?

  5. What is financial Instrument, Bond, equity, Asset, future, option, swap and stock with example each?

  6. Toolkit & Resources for a Java Developer.

  7. Sample Unsolved Interview Questions.

  8. Sample Unsolved Puzzles?

  9. Few sample UNIX questions.

  10. Top Java Interview Questions?

  11. What is the Typical Interview Coverage for Core Java Candidate ?

  12. What is the art of writing resume?

  13. Sample Questions on Swings framework.

  14. What are the Interview questions that most candidates answer wrongly?

Most of these questions are addressed in this eBook

For all these questions, you can buy my ebook:

Buy my ebook for complete question bank

Most of these questions has been answered in my eBook "Cracking the Core Java Interview" updated on June 2018, that you can buy from this link:

Buy from Shunya (DRM Free PDF download with updates)

Top articles in this category:
  1. Multi-threading Java Interview Questions for Investment Bank
  2. Citibank Java developer interview questions
  3. RBS Java Programming Interview Questions
  4. Sapient Global Market Java Interview Questions and Coding Exercise
  5. Goldman Sachs Java Interview Questions
  6. Morgan Stanley Java Interview Questions
  7. UBS Java Interview Questions

Recommended books for interview preparation:

Find more on this topic: