Sunday, April 19, 2015

Barclay Java Interview Questions


  1. What is an Immutable Class ? Why is it important in multi-threading context ? Can you write a Custom immutable class ? What are semantics for writing an Immutable Class in java ?
  2. How will you use your custom Object as a Key inside hashing datastructure (Hashmap, ConcurrentHashmap, hashSet, etc.)?
  3. Explain the working of put and get method of a hashmap class ? How does equals() and hashcode() comes into picture there ?
  4. What is difference between Executor Framework and ForkJoinPool ?
  5. What is difference between Executor.submit() and Executor.execute() method ?
  6. Write a code to iterate over a standard hashmap object in Java.
  7. What all things to keep in mind when you use Hashmap in multi-threaded environment ?
  8. What is difference between sleep() and wait() method ?
  9. What is Composite Design Pattern ?
  10. Write a code in java to remove elements of an array while iterating over it.
  11. What is ThreadLocal variable in Java ?
  12. What is pass-by-value and pass-by-reference ? Which mechanism is being used by Java ?
  13. Discuss through example, The Producer Consumer problem.
  14. Discuss how HashSet works internally in java ?
  15. Explain database normalization and its various usages.
  16. What are top 10 coding standards for code reviews in Java ?
  17. Write a recursive Java program to print Fibonacci Series ?
  18. How will you design a distributed algorithm for Prime Number generation in Java ? Discuss the Design only.
  19. How Garbage Collection works in Java, explain the underlying mechanism for any one of the Garbage Collector ? Give few names of existing garbage collectors ?

hCentive Java Interview Questions

Multi-threading Questions
  1. What do you understand by thread-safety ? What are various mechanisms to achieve thread-safety in java ?
  2. How will you design your own ReentrantReadWriteLock class where one thread can write and  many threads can read in parallel ? How does it affect the throughput of a multi-threaded system ?
  3. What are various methods to acquire lock in java ? discuss their comparison.
  4. How to avoid deadlock in your application ?
  5. How is ConcurrentHashMap better than hashmap in java ?
General Java
  1. What are different memory generations in Java ? What is Stack and heap memory ?
  2. Write a thread-safe Singleton Java Class.
  3. What is difference between hashtable, hashmap and Concurrenthashmap in java ?
  4. What is difference between Iterator and ListIterator in Java ?
  5. What is Immutable Class ? What is reason behind using a Immutable class in your application ?
  6. What is difference between String, StringBuffer and StringBuilder ?
  7. What is difference between CheckedException and UncheckedException ? Give some example of RuntimeException ?
Spring Framework
  1. What are different Bean scopes in Spring ? What is the default bean scope ?
  2. How many objects Spring container creates for a given bean definition ?
  3. What is Bean Lifecyle ?
  4. How do you encrypt a password in spring security ?
  5. Describe practical use of Spring Interceptors ?
  6. What is Servlet LifeCycle ?
  7. How do you declare a custom error page in Spring ?
  8. What is difference between doGet() and doPost() methods ?
  9. What is difference between Forward and Redirect ?

Saturday, April 18, 2015

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 ?

Black Rock Java Interview Questions

Design Problem
  1. 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 ? Solution is discussed in eBook
  2. There is a very Big file containing many words, how will you read and process it to print the below information ?
    a) Top 10 ranked distinct words.
    b) Occurrence of each Alphabet in the file.
  3. How will you implement a Stack using a Queue ?
  4. How will you implement a Queue using a Stack ?
  5. How will you design a two way Elevator Software for a building ?
  6. What is Immutability ? How will you make a class Immutable in Java ?
  7. How will you achieve thread-safety in your Java Program ?
  8. What are the ways to increase throughput of a multi-threaded java program ? (concurrency enhancements - use java.util.concurrent package, connection pooling, other resource pooling, caching, GC tuning, etc.)
  9. How will you troubleshoot poor memory performance of a live production program ?
  10. How will you find a single duplicate number from a large array in minimum time ?

Thursday, March 5, 2015

ION trading Java Interview Questions

Design Questions
1. Design high throughput trading application? Application is hosted in NY and we have traders all over the world accessing this application. What things we need to take care on designing this application.
Hint- High concurrency using Atomic package rather than synchronization, Timezone and Localization, Currency Conversion, Connection Pooling, No GC pauses (proper memory management), Horizontal scalability using restful architecture, ActiveMQ for asynchronous communication, etc.
2. If we have unsorted list of numbers like 3,1,4,7,9,4,7,4,9 best way to figure out if number n exists in the list? they were interested in constant time performance ?
Hint - Consider preprocessing the data using a hashtable and then query the table in O(1) complexity
3. Removing duplicates from unsorted list of integer maintaining the order of input in results? if you have unsorted list of
0,5,9,5,6,7,6,9
the result should be
0,5,9,6,7 and the performance should be best over more number of elements.
Hint - Store the list in LinkedHasSet and printing it will get expected output, Other way could be use of hashtable to store the numbers and then printing it, Counting Array can also be used to achieve the same if the input range is known and limited.
4. Describe the design of a low latency distributed environment where multiple processes( or threads) need to access shared data structure or a database for a fast ( speaking of a fraction of a milisecond) read or update. You have to process tons of request very quickly ( you can think of market price data as an example, etc). How would you build such an environment in the most efficient way? Describe the solution in details(a few sentences).
Hint- use of non-blocking algorithms and CAS (compare and Set/Swap) feature provided by java. This way we will get rid of the low throughput offered by synchronization used in thread safe programs. refer to Concurrency in practice for more details.
5. Write a program to print elements of a linked list in reverse order by using same single linked list in java.
Hint - Start traversing the singly linked list and put the nodes in a stack till you reach the end of the list. Then pop from the stack. The elements will be in the reverse order to the original linked list.
6. Design a thread-safe ObjectPool (Generic type i.e. ConnectionPool, ThreadPool, etc) in Java. Interface should look like -
interface Pool {
Connection get();
void put(Connection con);
}
Hint- Designing a thread-safe connectionPool in java
7. Describe the Producer Consumer problem using Java language ? How will you make it thread-safe ?
8. Given a huge file, design a data structure to output all possible anagrams of a particular word. For Eg the file contains: "POT, OPT, TOP". If I query for POT, I should get back all possible anagrams contained in the file.
9. Write a Java program to reverse the sequence of words in a sentence. for example "This is my world" should become "world my is this"
Hint -
With limited Space -
This can be done without any additional space in 2 pass
1) reverse the string in place
2) reverse each word of the reversed string.
With Time : O(N) and Space : O(N)
Split the words and then traverse the array in reverse direction.
10. Print n elements of a fibonacci series.
11. Find whether there is a loop in a given linked list or not ?
Hint - It can be done using one pointer but not without extra space. You can store the addresses of all the nodes visited in a hashmap. And for every next node, check its presence in hashmap.

Goldman Sachs Java Interview Questions

1. There is a String array String[] words = {"hello", "world", "HELLO", WORLD"}; How will you print output like hello-2, world-2 i.e. word followed by its count ignoring the case of the words in the input Array ?
2. There is a array of words String[] words = {"abc","bca", "cab", "cba", "def", ...} etc. So if given an input "cab", your program should print all the words that contains 'c', 'a' and 'b' i.e. "bca", "abc", "cba", etc. How will you achieve that ? Anagrams example ?
3. How will you implement your own hashmap in Java ? How will you handle collision of keys ? Basically interviewer wants to know internals of a hashing data structure.
4. How will you implement multiplication for very big numbers without using Java inbuilt classes ?
5. Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is “yyyybbbbdexxxxxxx”, then the function should return “y4b4dex7″.
6. Given a string check if the string is palindrome or not ?
7. What are the main interfaces in Java Collections framework ? What is difference between Set and List ?
8. Let's say I gave you a long String and I wanted you to tell me the most common word in that String. How would you do that?
follow-up: OK, how would you estimate the size and time complexity of this solution? How would you estimate the ACTUAL size usage? (Hint: how many words are in the English language? Would having a dictionary in front of you help?)
follow-up #2: OK, how about if I gave you the entire works of Alexandre Dumas, one of the most prolific authors in history. How would your solution work? How could you change it to solve this more specific problem?
follow-up #3: Now, what if we wanted to find the most common PHRASE in his writings. (Upon clarification, the interviewer wouldn't give a specific length, so I clarified to finding as long as a common 10 word phrase, because anything longer is unlikely.)
Hint - Find Top X occurring words in a very big file using Min-Heap and Hashtable.

9. why strings are immutable ? how many objects will be created in String temp = "A" + "B" + "C" ; explain your answer in detail.
Hint- Role of Immutable Objects in writing thread safe scalable applications.

10. You have 5 data sources. There is a program which calls these data sources and returns a count value. You need to speedup this program. How do you do that? This is a sample code
int count = getCount(ds1);
if(count < 100 )
count = count + getCount(ds2);
if(count < 100)
count = count + getCount(ds3);
if(count < 100)
count = count + getCount(ds4);
if(count < 100)
count = count + getCount(ds5);
Hint - Interviewer must be looking for multi-threading. Fetch count from all sources in parallel. Bonus points: If machine has less than 5 cores (for 5 data sources), say 4 cores, prioritize so that first 4 cores get the highest priority. Not sure how to do this in code.

11. How would one design a multi format converter that supports reading data from multiple data sources(web service, local disk, etc.). The data from the sources can be in multiple formats. The reader for each format may be different and how does one serialize this abstract data to multiple formats like image, xml etc. New readers, writers and data sources can be added later during implementation.
Hint- Design Patterns problem, look for java.io.* classes for example Reader, InputStream, etc. Decorator Design pattern. There are two variables here - 1. Multiple Datasources with common interface 2. Multiple formats with common interface. 9implementation can be provided later on. our APi should be coded over interface rather than implementation.

12. How will you reverse a linked list in Java ?
13. How will you find common ancestor of two given nodes A and B in a binary Tree ?
14. How reverse key index helps in faster data reading and what is use case for this? Complexity of B tree index?

Thursday, February 26, 2015

Java Interview Questions Covered in eBook "Cracking the Core Java Interviews (investment banking, healthcare IT and product companies)"

Cracking Java Interviews2
Core Concepts, Spring & Hibernate14
Q 1.  What are good software practices for developing Scalable, Testable and Maintainable Software ?14
Q 2.  What are good books for reference on Java Programming ?14
Q 3.  What is Growth Road Map for a Java Developer?15
Q 4.  Why should I choose Java for Software Development? What are Pros and Cons of Java 8 ?16
Q 5.  What is difference between 32 bit and 64 bit versions of Java?16
Q 6.  What are four basic principles of OOP?17
Q 7.  What are the key paradigms for Developing the Clean Object Oriented Code?17
Q 8.  How much important is requirement gathering in software development process?17
Q 9.  What is Logarithm? Why is it relevant in Software Development?19
Q 10.  What do you understand by Big O notation, why is it important in software development ?20
Q 11.  How would you determine the Time Complexity of a given algorithm, are there any general guidelines?21
Q 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'?22
Q 13.  Why Prime Numbers are given much importance in writing certain algorithms like hashcode()?27
Q 14.  What is left shift <<, right shift >> and Unsigned right shift >>> operator in Java? How are these useful?28
Q 15.  What is 2's complement notation system for Binary Numbers?30
Q 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?31
Q 17.  What is difference between Stack and Heap area of JVM Memory? What is stored inside a stack and what goes into heap?35
Q 18.  What is a Binary Tree? Where and why is this used in Java Programs?36
Q 19.  Discuss implementation and uses of TreeSet Collection?36
Q 20.  How does Session handling works in Servlet environment?37
Q 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
Q 22.  How will you write a Recursive Program?39
Q 23.  How many elements a complete binary tree could hold for a depth of 10? 39
Q 24.  Explain working of a hashing data structure, for example HashMap in Java.40
Q 25.  Discuss internal's of a concurrent hashmap provided by Java Collections Framework.41
Q 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
Q 27.  Discuss Visitor, Template, Decorator, Strategy, Observer and Facade Design Patterns?44
Q 28.  What is a strong, soft, weak and Phantom reference in Java? Where are these used?46
Q 29.  What are database transaction Isolation levels?48
Q 30.  What is difference between Primary key and Unique Key?49
Q 31.  Why do we need indexing on Database Table Columns ?49
Q 32.  What are clustered and non-clustered indexes in Sybase Database?50
Q 33.  How would you handle lazily loaded entities in web application development using hibernate?50
Q 34.  What are OneToOne, OneToMany and ManyToMany relationship mappings in database design?51
Q 35.  How would you implement ManyToMany mappings with the self entity in JPA?52
Q 36.  What is Inner Join, Left Outer Join and Right Outer Join?53
Q 37.  How will you list all the Customers from Customer Table who have no Order(s) yet?54
Q 38.  How would you fetch Employee with nth highest Age from Employee Table using SQL?54
Q 39.  Question: What is difference between Drop, Truncate and Delete Table commands in SQL?54
Q 40.  What are Inheritance strategies in JPA?55
Q 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
Q 42.  What are different types of Http Codes ?56
Q 43.  What is difference between HTTP Redirect and Forward?56
Q 44.  How will you check the owner information of a given domain name in web ?57
Q 45.  What happens when you type www.google.com in your browser's address bar from an Indian Location?58
Q 46.  What is Idiom for Creating a Hibernate Transaction ?60
Q 47.  Why do we need Spring Framework ?60
Q 48.  What is Inversion of Control (or Dependency Injection)?60
Q 49.  What is Bean Factory in Spring?61
Q 50.  What is Application Context?61
Q 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
Q 52.  What are different Bean Scope in Spring ?61
Q 53.  What are some important Spring Modules ?61
Q 54.  How will you load hierarchy of property files in Spring Context ?62
Q 55.  How to efficiently generate ID's for an Entity in Hibernate/JPA ?62
Q 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
Q 57.  How will you handle batch insert in hibernate for optimal usage of memory, network and CPU ?64
Q 58.  How will you operate on records of a large database table with million of entries in it using Hibernate ?65
Q 59.  Do you think Hibernate's SessionFactory and Session objects are thread safe ?65
Q 60.  What is difference between Hibernate's first and second level cache ?66
Q 61.  What is syntax of Cron Expression ?66
Q 62.  Explain Stream API introduced in Java 8 ?67
Q 63.  Most useful Code Snippets in Java 8 ?68
Q 64.  How will you configure custom sized ThreadPool for stream parallel operation in Java 8 ?72
Core Java Questions73
Q 65.  What are new Features added in Java 8 ?73
Q 66.  What is difference between method overloading, method overriding, method and variable hiding?74
Q 67.  What is Order of calling constructors in case of Inheritance?75
Q 68.  When should we choose Array, ArrayList, LinkedList over one another for a given Scenario and Why?76
Q 69.  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
Q 70.  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) {
            wait();
        }
        queue.add(element);
        notify();
}78
Q 71.  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
Q 72.  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
Q 73.  If hashcode() method of an object always returns 0 then what will be the impact on the functionality of software ?80
Q 74.  Iterator interface provides remove() method but no add() method. What could be the reason for such behavior?
81
Q 75.  What does Collections.unmodifiableCollection() do ? Is it a good idea to use it safely in multi-threading scenario without synchronization, Is it immutable ?81
Q 76.  If we don't override hashcode() while using a object in hashing collection, what will be the impact ?82
Q 77.  How would you detect a DeadLock in a running program ? 82
Q 78.  How would you avoid deadlock in a Java Program ?82
Q 79.  Question : How would you produce DeadLock in Java ?83
Q 80.  Which data type would you choose for storing currency values like Trading Price ? What's your opinion about Float, Double and BigDecimal ?84
Q 81.  How would you round a double value to certain decimal Precision and Scale ?86
Q 82.  How great is the Idea of synchronizing the getter methods of a shared mutable state ? What if we don't ?87
Q 83.  Can the keys in Hashing data structure be made Mutable ?87
Q 84.  Is it safe to iterate over collection returned by Collections.synchronizedCollection() method, or should we synchronize the Iterating code ?88
Q 85.  What are different type of Inner classes in Java ? How to choose a type with example ?89
Q 86.  When should we need a static inner class rather than creating a top level class in Java Program?89
Q 87.  Is it possible to write a method in Java which swaps two int/Integer ?90
Q 88.  What all collections utilizes hashcode() method ?90
Q 89.  Provide a diagram for collections framework.91
Q 90.  What is Immutable Class. Why would you choose it ? How would you make a class immutable ?92
Q 91.  Why shouldn't we prefer mutable static variables in our Java Code ?92
Q 92.  Discuss Exception class hierarchy in Java. When should we extend our custom exception from RuntimeException or Exception ?93
Q 93.  How does method parameter passing works in Java ? Does it pass-by-reference or pass-by-value ?94
Q 94.  How does an ArrayList expands itself when its maximum capacity is reached ?94
Q 95.  What is StringPool In Java ?94
Q 96.  What is instance level locking and class level locking ?95
Q 97.  Explain threading jargons ?96
Q 98.  What is float-int implicit conversion while doing calculation on mixed data type in Java?97
Q 99.  Discuss Comparable and Comparator ? Which one should be used in a given scenario ?97
Q 100.  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
Q 101.  What are the best practices for handling TimeZone in database transactions ?99
Q 102.  How would you convert time from One Time Zone to another in Java ?99
Q 103.  Will WeakHashMap's entry be collected if the value contains the only strong reference to the key ?100
Q 104.  Why HashMap's initial capacity must be power of two ?101
Q 105.  Can we traverse the list and remove its elements in the same iteration loop ?101
Q 106.  Do I need to override object's equals() and hashcode() method for its use in a TreeMap ?101
Q 107.  Implement a BlockingQueue using intrinsic locking mechanism.102
Q 108.  Is there a way to acquire a single lock over ConcurrentHashMap instance ?102
Q 109.  How will you implement a Blocking Queue using Lock and Condition Interface provided in JDK?102
Q 110.  How would you cancel a method execution after time-out expires using Java Future?103
Q 111.  Java already had Future interface, then why did they provide Completable Future class in Java 8 ?104
Q 112.  What is difference between intrinsic synchronization and explicit locking using Lock ?106
Q 113.  What are Stamped Locks ? How they are useful in Optimistic Scenario where thread contention is rare ?107
Q 114.  What is difference between Executor's submit() and execute() method ?109
Q 115.  How will you find out first non-repeating character from a string ? For example, String input = "aaabbbeggh", answer should be 'e'109
Q 116.  What is difference between Callable and Runnable Interface?110
Q 117.  What will happen when an exception occurs from within a synchronized code block ? Will lock be retained or released ?110
Q 118.  What is difference between sleep(), yield() and wait() method?110
Q 119.  How does Generics work in Java? 112
Q 120.  What are Upper and Lower bounds in Generics? Where to choose one?113
Q 121.  Discuss memory visibility of final fields in multi-threading scenario.114
Q 122.  Where would you use LinkedHashSet provided by Java Collections?116
Q 123.  What do you think is the reason for String Class to be Immutable?116
Q 124.  How is String concatenation implemented in Java using + operator? 
for example, String name = "munish" + "chandel"116
Q 125.  Which Java data type would you choose for storing sensitive information, like passwords, and Why?117
Q 126.  What is difference between StringBuilder and StringBuffer ?117
Q 127.  What is difference between using Serializable & Externalizable Interfaces in Java?117
Q 128.  How would you design Money Class in Java?118
Q 129.  Where should we use GET, PUT, POST and DELETE method?119
Q 130.  What is difference between HashMap, TreeMap and LinkedHashMap?119
Q 131.  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?120
Q 132.  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?123
Concurrency 124
Q 133.  What is Concurrency? How will you implement Concurrency in your Java Programs?124
Q 134.  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?
SOLUTION125
Q 135.  What are the different states of a Thread? What does those states tells us?126
Q 136.  Question: What do you understand by Java Memory Model? What is double-checked locking? What is different about final variables in new JMM?127
Q 137.  Is i++ thread-safe (increment operation on primitive types)? 131
Q 138.  What happens when wait() & notify() method are called?131
Q 139.  Discuss about volatile keyword and Java Memory Model?132
Q 140.  What is a CAS? How does it help writing non-blocking scalable applications? Tell something about Atomic Package provided by Java 1.6133
Q 141.  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
Q 142.  How would you implement AtomicFloat /AtomicDouble using CAS?135
Q 143.  How LongAdder and LongAccumulator are different from AtomicLong & AtomicInteger ?137
Q 144.  Can we implement check & update method (similar to compare and swap) using volatile alone?137
Q 145.  How will you track the largest value monitored by different threads in an non-blocking fashion (using Atomic Operations) ?137
Q 146.  What is difference between Fork/Join framework and ExecutorService ?138
Q 147.  How does ForkJoinPool helps in writing concurrent applications ? Please provide few examples for RecursiveTask and RecursiveAction.138
Q 148.  How will you calculate Fibonacci Sequence on a multi-core processor ?141
Q 149.  How will you increment each element of an Integer array, utilizing all the cores of processor ?142
Q 150.  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
Q 151.  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
Q 152.  What are fail-fast Iterator? what is fail safe?146
Q 153.  There is a stream of words which contains Anagrams. How would you print anagrams in a single bucket from that stream?147
Q 154.  Describe CopyOnWriteArrayList? Where is it used in Java Applications?148
Q 155.  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
Q 156.  Are there concurrent version for TreeMap and TreeSet in Java Collections Framework?148
Q 157.  Is it safe to iterate over an ArrayList and remove its elements at the same time ? When do we get ConcurrentModificationException & hidden Iterator?149
Q 158.  What is ThreadLocal class, how does it help writing multi-threading code? any usage with example?150
Q 159.  How would you implement your own Transaction Handler in Core Java, using the EntityManager created in last question?151
Q 160.   What is AtomicInteger class and how is it different than using volatile or synchronized in a concurrent environment?152
Q 161.  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
Q 162.  What are common threading issues faced by Java Developers?155
Algorithms & Data Structures 156
Q 163.  ​Given a collection of 1 million integers ranging from 1 to 9, how would you sort them in Big O(n) time?156
Q 164.  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
Q 165.  I have an Integer array where every number appears even number of time except one. Find that number.157
Q 166.  how would you check if a number is even or odd using bit wise operator in Java?158
Q 167.  How would you check if the given number is power of 2?158
Q 168.  What is a PriorityQueue? How is it implemented in Java? What are its uses?159
Q 169.  What is difference between Collections.sort() and Arrays.sort()? Which one is better in terms of time efficiency?160
Q 170.  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
Q 171.  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
Q 172.  What is technique to sort data that is too large to bring into memory ?162
Q 173.  Check if a binary tree is a Binary Search Tree or not?162
Q 174.  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
Q 175.  How would you calculate depth of a binary tree?164
Q 176.  Calculate factorial using recursive method.164
Q 177.  How will you swap two numbers using XOR operation?
SOLUTION164
Q 178.  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.165
Q 179.  Your are give a file with 1 million numbers in it. How would you find the 20 biggest numbers out of this file?165
Q 180.  Reverse the bits of a number and check if the number is palindrome or not? 166
Q 181.  How would you mirror a Binary Tree?166
Q 182.  How to calculate exponentiation of a number using squaring for performance reason?166
Q 183.  How will you implement a Queue from scratch in Java?168
Q 184.  How will you Implement a Stack using the Queue?169
Q 185.  How would you implement a simple Math.random() method for a given range say (1-16)?170
Q 186.  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
Q 187.  How would you multiply a number with 7 using bitwise hacks?171
Q 188.  What is best way to search an element from a sorted Integer Array? What will be its time complexity?171
Q 189.  How would you reverse a Singly linked List?172
Q 190.  How would you count word occurrence in a very large file ? How to keep track of top 10 occurring words?173
Q 191.  What is difference between synchronized HashMap and a hashtable?176
Q 192.  What is difference between Iterator and LisIterator?176
Q 193.  What do you understand by Token Bucket Algorithm. What is its use ?177
Q 194.  How will you implement fibonacci series using Iterative & Recursive approach in Java 8 ?179
Q 195.  How will you write a multi-threaded HttpDownloader program using Java 8 ?182
Q 196.  How will you find first non-repeatable character from a String using Java 8 ?183
Q 197.  How will you find Word Frequency in sorted order for a collection of words ?183
Q 198.  How will you calculate MD5 hash of a given String in Java ?184
Object Oriented Design 185
Q 199.  What are the key principles when designing a software for performance efficiency ?185
Q 200.  How would you describe Producer Consumer problem in Java ?185
Q 201.  How would you implement a Caching for HttpDownloader Task using Decorator Design Pattern ?187
Q 202.  Write Object Oriented design for library management system.188
Q 203.  Design ATM machine.190
Q 204.  Design a web crawler that will crawl for links(urls).191
Q 205.  Design Phone Book for a mobile using TRIE (also known as prefix tree).192
Q 206.  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
Q 207.  How would you sort 900 MB of data using 100 MB of RAM ?
What is external sort ?198
Q 208.  How would you design minimum number of platforms so that the buses can be accommodated as per their schedule ?
Bus Schedule for a given Platform201
Q 209.  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
Q 210.  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
Q 211.  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.205
Q 212.  How would you simulate a digital Clock in Object Oriented Programming Language?207
Q 213.  How would you design an elevator system for multi story building? Provide with request scheduling algorithm & Class diagram for the design.210
Q 214.  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?210
Q 215.  Design DVD renting system, database table, class and interface.211
Puzzles & Misc212
Q 216.  Why man holes are round in shape ?212
Q 217.  Solve two egg problem ?212
Q 218.  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 ?213
Q 219.  What is probability of a daat, hitting closer to centre of a circle rather than circumference ?214
Q 220.  What is financial Instrument, Bond, equity, Asset, future, option, swap and stock with example each ?214
Q 221.  Toolkit & Resources for a Java Developer.215
Q 222.  Sample Unsolved Interview Questions.216
Q 223.  Sample Unsolved Puzzles ?221
Q 224.  Few sample UNIX questions.224
Q 225.  Top Java Interview Questions ?226
Q 226.  What is the Typical Interview Coverage for Core Java Candidate ?227
Q 227.  What is the art of writing resume ?227
Q 228.  Sample Questions on Swings framework.228
Q 229.  What are the Interview questions that most candidates answer wrongly ?


For answers, refer to my eBook - 

http://www.shunyafoundation.com/cracking-java-interviews-3rd-edition-ebook

Monday, February 23, 2015

RBS Java Interview Questions

Written Test Java Questions
  1. What is the strategy to handle ConcurrentModificationException in your Java program ?
  2. What will be behavior of a Java Program where infinite recursion takes place with limited Stack memory ? Does the program complete or Stackoverflow exception is thrown ?
  3. Comparable vs Comparator ? when should I choose one over the another ?
  4. How will you remove duplicate records from a database table ? Will group by clause help ?

Core Java Interview Questions
  1. How does serialization takes place in Java ? What is purpose of externalizable interface ? What are transient variables ?
  2. Why most of methods in Collections class declared as static ?
  3. What is difference between overloading and overriding ? What is hiding of members and methods - both static and instance one ?
  4. What is ThreadLocal class used for ?
  5. What is purpose of Classloader provided by Java ? What is effect of multiple classloaders on Singleton Class ?
  6. NoClassDefFoundError vs ClassNotFoundException ?
  7. What is proxy design pattern ? What is it's practical usage ?

Design Problems
  1. How will you design a caching implementation where items in cache needs to be expired (deleted from memory) after age of 5 minutes irrespective of the access timing ?
  2. How will you design your own custom thread pool in Java ? Don't use the One provided by JDK.
  3. What do you understand by Producer Consumer Problem ?

Sapient Global Market Java Interview Questions

  1. How do we synchronize a static method to prevent data corruption in concurrent update ?
  2. How will you introduce multi-tasking in your java application ?
  3. Design a program to search files inside a directory using multi-threadig?
  4. How will you implement a LRU timed cache in Java ?
  5. There is a folder containing multiple SQL files. Each file's name contain a sequence number which determines the execution order of that particular SQL script file. Design an API that will take such folder and execute the SQL in correct order.
  6. Difference between wait() and sleep() method ?
  7. What is a deadlock situation ? How will you handle deadlock in development and production environment ?
  8. What is mechanism for inter-thread communication ?
  9. Would adding multi-threading to sorting algorithm improve its performance ?
  10. In what practical scenario's multi-threading actually improves the performance of Java application ?
  11. Do we need to synchronize getter and setter both to prevent concurrency related issues on a collection ?
  12. Explain the key classes in java.util.concurrent package ?
  13. What is purpose of ConcurrentHashMap ?
  14. What is purpose of a Future ? How will you use it ?
  15. How will you create your own custom Thread Pool ?
  16. What is a BlockingQueue ?
  17. There is three file contains flight data. File data has in csv format.
    1)Write a standalone program to search flight detail from all files depend on criteria
    2)Criteria would be departure location,arrival location, flight date.
    3)Program should follow\Oops principle. And right unit test case also.
    4)Result should be in Ascending or descending order.
    5)Data separated with pipe | .

    File A has data like below:
    FLIGHT_NUM|DEP_LOC|ARR_LOC|VALID_TILL|FLIGHT_TIME|FLIGHT_DURN|FARE
    AF299|FRA|LHR|20-11-2010|0600|4.10|480
    AF118|DUB|MUC|21-12-2010|1410|5.40|580
    AF371|AMS|MAD|30-11-2010|1210|3.45|320

    File B has data like below:
    FLIGHT_NUM|DEP_LOC|ARR_LOC_VALID_TILL|FLIGHT_TIME|FLIGHT_DURN|FARE
    BA123|DEL|AMS|12-10-2010|0050|8.00|950
    BA412|BOS|CDG|31-12-2010|0210|7.50|800
    BA413|BOS|AMS|30-11-2010|1530|7.00|750

    File C has data like below:
    FLIGHT_NUM|DEP_LOC|ARR_LOC_VALID_TILL|FLIGHT_TIME|FLIGHT_DURN|FARE
    LH348|DEL|AMS|30-11-2010|2325|11.00|1050
    LH201|LHR|MEL|21-11-2010|0230|15.30|1400
    LH342|VIE|JFK|20-10-2010|1130|14.20|980
Most of these questions has been answered in my eBook "Cracking the Core Java Interview"


Citibank Java Interview Questions

Java Questions
  1. Discuss method overriding in Java ?
  2. Discuss internals of a Hashmap ? What is Role of equals() and hashcode() method in Object class ? What will be behavior if we override hashcode() method to always return 1 ?
  3. What is difference between Future and Callable interface in Java ?
  4. When should I use StringBuilder class in a program ?
  5. Tell me about your understanding of Executor Framework. How is it different from Fork Join Framework ?
  6.  What is a Immutable Class ? How does it help in writing scalable applications ?
  7. What is thread safety ? How do you achieve it ?
  8. How will you handle ConcurrentModificationEXception ?
  9. What is difference between poll() and remove() method of an Queue ?
  10. What is difference between fail-fast and fail-safe iterators ?
  11. How are Concurrent Collections different from Synchronized collections ?
  12. What is difference between vector and ArrayList ?
  13. What is difference between HasSet and Hashmap ?
  14. What is CopyOnWriteArrayList, how it is different than ArrayList and Vector?
  15. when to use serialization vs externalizable interface?
Design Problems
  1. How do you pass a job from Thread 1 to Thread 2 to Thread 3 ?
  2. How will you implement a Queue in Java ?
  3. Discuss Singleton and Decorator Design Pattern. Discuss the practical usage of these design patterns. How to make singleton class thread safe ?
  4. How will you implement pagination in a web application ?
  5. What is difference between Factory and Abstract Factory Design Pattern ? 
  6. you have array of n size having numbers between 1 to 100. you need to provide algorithm for sorting array with BigO(n) iteration. 
  7. How will you implement your own Binary Tree in Java ?
  8. There is a very big text file containing words ? How would you read & process it to print the below output.
    1. Print the top ten ranked distinct words.
    2. Print the occurrence of the each alphabet in this file
    consider that the file can not fit into main memory of computer.
  9. How will you design your custom Connection Pool in Java ?
Misc
  1. Write a SQL to find the nth maximum salary in a employee table.
  2. What is Inner Join, Left outer join ?
  3. What are different types of database indexes ?
You will find most of these questions answered in my eBook "Cracking Core Java Interviews"

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

 
This question is taken from my eBook "Cracking Core Java Interviews" 

What happens when you type www.google.com in your browser's address bar from an Indian Location?

Skills - HTTP protocol, DNS Lookup, Networking, TCP connection, etc

There are series of events that happen when we type in www.google.com into browser's address bar from a given location, we will cover few main steps here -
  • User enters www.google.com into the address bar
  • Browser checks if the typed address is www url or the search term, if it is search term then it will use pre configured web search server (may be google or bing, etc) to search the typed term from web.
  • If the requested Object is in browser's cache and cache is valid, content is rendered from cache, otherwise
  • DNS Lookup takes place - Browser resolves the IP address for the mentioned server (www.google.com)
  1. It checks in the browser cache
  2. checks the OS Cache
  3. checks the router cache
  4. checks the ISP cache
  5. DNS recursive search until it reaches authoritative DNS Server. If multiple ip addresses are found for a given server address, then DNS Round Robin algorithm picks up any one for the further communication. If it does not recognize the domain then it gives error message.
  6. we can use <nslookup www.google.com> command on windows to check what all IP addresses are mapped to this www.google.com domain, incase they are multiple DNS server will use round robin algorithm to pick up any one from the list.
  • Browser initiates TCP connection with the IP address and issues HTTP GET request to the server, it passes along an HttpRequest that includes metadata about browser, user preferences (language, locale etc.) and cookies for that domain.
  • Google.com server receives the request, uses the passed information (cookies) to find who the user is, locale, language and region and  sends http redirects (HTTP GET 302) to browser to use local regional google server, i.e. www.google.co.in in our case (temporarily redirect)
  • Browser receives the response (302 in this case) and sends a fresh request to the newly mentioned location in the previous response, passing the user information again (cookies for that domain, metadata, etc)
  • Google.co.in receives the request the decodes the user and send the appropriate HTML response including headers (status code 200 OK, content type, etc)
  • The Browser receives the response and begins to parse it for display. if it is compressed, browser will decompress it, The HTML body will include links to css, images, js. All these links will trigger additional calls back to server to retrieve those files. CDN (Content Delivery Networks) may serve these static resource requests to speedup the process.
  • Browser layout engine will start to assemble the final page for display. css, js information may alter the layout of the page.
  • The final page is assembled and rendered to the user.
  • After this the browser may send further AJAX request to communicate with the web server even after the page is rendered.
Also, there are many other things happening in parallel to this (processing typed-in address, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipeline, connection tracking for keep-alive, etc.).

Wednesday, February 18, 2015

UBS Java Interview Questions

1. How will you design online library management system using TDD and Agile ? Using testcases for requirements.
2. Talk about concurrency utils i.e. Atomic package ?
3. What is a volatile keyword ?
4. What is a future ?
5. What is decorator design pattern ?
6. Design your own custom Threadpool executor with minimal functionality.
7. Explain Java Memory Model.
8. Why is AtomicInteger class better than a synchronized counter class ? What is CAS ?
9. What is difference between ExecutorService and ForkJoinPool ?
10. Explain Producer Consumer Problem using Java Code.
11. How will you implement a blocking queue ?

Tuesday, February 17, 2015

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


We can use ForkJoin Framework to divide this task recursively into multiple sub tasks and fork them using multiple cpu's available to the JVM. Java 7 provides us with RecursiveAction class that can be extended to utilize ForkJoinPool framework with a great ease.


Java Code for Incrementing each element of Integer Array by 1
package org.shunya.interview;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

class IncrementTask extends RecursiveAction {
    private final int THRESHOLD = 100;
    final long[] array;
    final int lo, hi;

    IncrementTask(long[] array, int lo, int hi) {
        this.array = array;
        this.lo = lo;
        this.hi = hi;
    }

    protected void compute() {
        if (hi - lo < THRESHOLD) {
            for (int i = lo; i < hi; ++i)
                array[i]++;
        } else {
            int mid = (lo + hi) >>> 1;
            invokeAll(new IncrementTask(array, lo, mid), new IncrementTask(array, mid, hi));
        }
    }

    public static void main(String[] args) {
        long[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        IncrementTask incrementTask = new IncrementTask(array, 0, 9);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.invoke(incrementTask);
    }
}

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

We can find the first non-repeating char from a string using the following algorithm in Big O(n) Time

First Pass
We can maintain a counting array for all possible alphabet values (ASCII code 0-128) and keep op counting the position of array based on Ascii value of character. This will be Big O(n) Time Complexity Task where n is number of letters in the string.

Second Pass
Iterate through the counting array and find the first index position where value is exactly 1, and then break. That will give us the ascii code of character that is non repeating.

String str = "zzzzzbbbccccddehhhhiii";
int[] countingArray = new int[128];
str.chars().forEach(value -> countingArray[value]++);
int nonRepeatingCharAsInt = 0;
for (int i = 0; i < countingArray.length; i++) {
    if (countingArray[i] == 1) {
        nonRepeatingCharAsInt = i;
        break;
    }
}
System.out.println("character = " + Character.valueOf((char) nonRepeatingCharAsInt));
Alternative approach using Java 8
import java.util.LinkedHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;

public class NonRepeatingLetter {
    public static void main(String[] args) {
        findFirstNonRepeatingLetter(args[0], System.out::println);
    }
    private static void findFirstNonRepeatingLetter(String s, Consumer callback) {
        s.chars()
                .mapToObj(i -> Character.valueOf((char) i))
                .collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting()))
                .entrySet().stream()
                .filter(entry -> entry.getValue() == 1L)
                .map(entry -> entry.getKey())
                .findFirst().map(c -> {
            callback.accept(c);
            return c;
        });
    }
}

This question is covered in my eBook - Cracking Java Interviews (Java 8, Hibernate & Spring)

Java Topics covered in Investment Banking Intreviews (Morgan Stanley, Barclays, RBS, UBS, BlackRock)

Topics covered in Investment Banking Interview includes -

Core Java
  1. Java Basics - OOP Principles, Overriding (knowledge of all Rules), exception handling, garbage collection algorithms, Immutability concepts, Serialization concepts.
  2. Collections - Internals of ArrayList, HashMap, Concurrent HashMap details, HashSet, PriorityQueue details, etc. Big O Time and Space complexity of various operations
  3. Multi-threading and Concurrency - Basics of Synchronization, Concurrency API introduced in Java 5, Producer Consumer Problem.
Algorithms, Data Structures & Design Patterns
  1. List, Queue, Binary Tree, Binary Search Tree, hashing techniques, Time and Space Complexity measurements of custom algorithms. Some knowledge of sorting and searching algorithms - at least their comparison.
  2. Awareness of Basic Design Patterns - Singleton, Factory, Decorator, Listener, Command Design Patterns etc.
Frameworks
  1. Working knowledge of Spring Core, Spring-MVC, Active MQ, Restful Webservices.
  2. Hibernate/JPA, ORM concepts (JPA inheritance strategies, Entity Relationship with examples - OneToOne, OneToMany, ManyToMany), Transaction Management, Handling concurrent updates in database, etc.
Database 
  1. Working knowledge of DB and SQL, Database indexing, Outer and Inner Join, performance tuning of queries, etc.
Unix
  1.  Familiarity with Unix commands - find a running process, kill a process, grep, vi, tasklist, etc.

Morgan Stanley Java Interview Questions

Database
  1. What are type of indexes in Sybase Database ? What is difference between these different types ?
  2. What is a stored procedure. How will you performance tune a query in sybase database ?  
  3. What is difference between Left Outer Join and Right Outer Join ?
  4. How will you find nth highest salary of an employee from Salary table ?
  5. What is database normalization ?
  6. How will you express ManyTomany relationship in database ? Give any practical usecase for ManyToMany relationship.
  7. How does Lazy loading works in Hibernate ? How will load a lazily loaded item in hibernate to avoid LazyLoadingException ?
  8. How will you handle concurrent updates to a shared row in database ? Let's say bank account table, where two or more requests are coming in parallel ?
Java (Core, Design Patterns, Concurrency, Algorithms and Data Structure)
  1. What is polymorphism ? When does a method override in Java ?
  2. What are Immutable Objects ? What are their advantages ? Design an Immutable Class that has a java.util.Date member ? (consider that Date itself is mutable)
  3. What all Design Patterns you are aware of ? What is Singleton Design Pattern ? How will you make Singleton Thread-safe ?
  4. Given a String find the first non-repeatable character in the String. Example: str="zzzzzbbbccccddehhhhiii"; Answer is : e
    Solution -
    click here
  5. What is time complexity of HashMap insertion and retrieval in Java ?
  6. Discuss internals of a Hashmap's get and put method. What is role of hashcode and equals method in get and put operation ?
  7. Data (volume, price etc.) for various stocks in coming up in the Exchange, how will you design a thread-safe class that maintains the total volume traded in the exchange at any given point in time ? It should be very high throughput design.
  8. How to sort data that can't fit into main memory ?
  9. How to sort 1 million numbers (all positive integers), considering that only 0.1 million numbers can be accommodated into main memory ?
  10. How Garbage Collection Works in Java ? Name few garbage collection algorithms ?
  11. What is use of StringBuilder class ?
  12.  What is difference between sleep() and wait() ?
  13. How will you reverse a singly linked list in Java ?
  14. How will you create an artificial OutOfMemory Error in java ?
  15. What is difference between Synchronized Map and ConcurrentHashMap ?
  16. Explain the proper use of hashcode() and equals() method.
  17. What is Queue ? How will you implement a Queue using a ArrayList ?
  18. There is a file containing large numbers, you need to print numbers and their corresponding count in the file for 2 scenarios - 1) No memory constraints 2) limited memory available and not the entire data can fit into main memory.
  19. Given a dictionary, find all the words that are anagram to each other ?
  20. Remove duplicate numbers from a sorted Array ?
  21. How will you increment each element of a huge array using all the available cpu cores  of machine ?
    Solution - Click here
Unix and Operating Systems 
  1. How to find and kill a process in Unix ?
  2. How will you figure out free available space in Unix ?
  3. How will you find files recursively that contains specific words in their filename ?
  4. How will you find files recursively that contains specific words in their contents ?
  5. How to sort a file using unix command ?
  6. How to count number of lines in a file in unix terminal ?
  7. What is piping of commands in unix ? any example ?
  8. How will you list nth column of a flat file in Unix ?
  9. How will you find a process using specific port in Unix and Windows ?
  10. How password less authentication works in Unix ?
  11. How will you copy a file from one Unix host to another Unix host ?
Aptitude & Puzzles
  1.  You are given 2 eggs. You have access to a 100-storey building. Eggs can be very hard or very fragile means it may break if dropped from the first floor or may not even break if dropped from 100 th floor.Both eggs are identical. You need to figure out the highest floor of a 100-storey building an egg can be dropped without breaking. Now the question is how many drops you need to make. You are allowed to break 2 eggs in the process.