Tuesday, May 28, 2013

Array vs arraylist vs linkedlist vs Vector

Array vs arraylist vs linkedlist vs Vector with very good overview and examples. An ArrayList is ordered collection (also known as a sequence). It means that the user of controls where each element is inserted. This class is very similar to the Vector class, excepting that it is not synchronized. It must be synchronized externally.

An ArrayList is better than Array to use when you have no knowledge in advance about elements number. ArrayList are slower than Arrays. So, if you need efficiency try to use Arrays if possible.

Short Overview on main features of ArrayList:
- The add operation runs O(n) time. - The isEmpty, size, iterator, set, get and listIterator operations require the same amount of time, independently of element you access. - Only Objects can be added to an ArrayList - Implements all methods from the List interface - Permits null elements An arraylist could be a good choice if you need very flexible Array type of collection with limited functionality.

One small remark for those who needs faster arraylist. arraylists internally implemented as an Array. So when run an "add" command a new Array will be created with n+1 dimension. All "older" elements will be copied to first n elements and last n+1 one will filled with the value which you provide with add() method. To avoid that internal re-copying of Arrays you should use ensureCapacity(int requestCapacity) method - it will create an array only once.
If you have higher requirements on number of accessible methods for your Array like collection instead of arraylist you have better choice - linkedlist.
linkedlist is much more flexible and lets you insert, add and remove elements from both sides of your collection - it can be used as queue and even double-ended queue!

Internally a linkedlist does not use arrays, it is much more modern! linkedlist is a sequence of nodes, which are double linked. Each node contains header, where actually objects are stored, and two links or pointers to next or previous node. A linkedlist looks like a chain, consisting of people who hold each other's hand. You can insert people or node into that chain or remove. Linked lists permit node insert/remove operation at any point in the list in constant time.

linkedlist is actually luxury extension of an arraylist: it gives you many methods which you usually implement yourself around of different type of collections.
For example if you need to add new element to the end of an arraylist you have to look at the size of the collection and then add that new element at n+1 place. In linkedlist you do it directly by addLast(E e) method.

Another example. Depending on your expectations you can chose either getFirst/getLast or peekFirst/peekLast methods. Last "peek" methods are completelly new sort of methods and introduced in Java 1.6.
 
They slightly differs from set/get methods - they do not throw any kind of exceptions if this list is empty, return just null.
 
New "poll" methods - pollFirst and pollLast combine two methods: get and remove an element from your collection. For example pollFirst() method gets and removes the first element from this list. This method does throw any kind of exception like IndexOutOfBoundsException in case of arraylist, instead it just returns null (if this list is empty).
Because the linkedlist implements queue interface you can pop and push new elements from/into your collection.
 
If you created capacity restricted collection you can "examine" the result of an operation by using offerFirst/offerLast methods. They are also new (since Java 1.6) and return boolean result on the operations instead of throwing IllegalStateException as addFirst/addLast methods do. In case if possible to insert an element at the beginning/end of collection you you get "true" result.
When you write your code especially collections require some loops, complex logic or just much code. In such case to avoid code errors you can use Checkstyle Java tool.

Java Interview Question

1. What is immutable object? Can you write immutable object?You need to make class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
 

2. Does all property of immutable object needs to be final?
Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
 

3. What is the difference between creating String as new () and literal?
When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
String s = new String("Test");will put the object in String pool , it it does then why do one need String.intern() method which is used to put Strings into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" it put the String in pool.
 

4. How does substring () inside String works?
Another good question, I think answer is not sufficient but here it is “Substring creates new object out of string by taking a portion of original string”.
The substring() method is used to return a part (or substring) of the String used to invoke the method. The first argument represents the starting location (zero-based) of the substring. If the call has only one argument, the substring returned will include the characters to the end of the original String. If the call has two arguments, the substring returned will end with the character located in the nth position of the original String where n is the second argument. Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last character in the returned String will be in the original String’s 7 position, which is index 6. Let’s look at an example:String x = "0123456789";
System.out.println( x.substring(5) ); // output is "56789"System.out.println( x.substring(5, 8)); // output is "567"
The first example should be easy: start at index 5 and return the rest of the String. The second example should be read as follows: start at index 5 and return the characters up to and including the 8th position (index 7).
and @Anonymous pointed out some interesting fact:something important about String.substring() method, its implementation calls the following String(...) constructor :
// Package private constructor which shares value array for speed.String(int offset, int count, char value[]) {this.value = value;this.offset = offset;this.count = count;}
That means the new String() object returned by substring(...) shares the same backing array (this.value) as the original string object.
Thus if your original string object is 1GB long, the substring object will always be 1GB long too!
You will probably want to trim the new array size to the substring range, this should do the job:
String veryLongString = readFromFile(file);String tinyString = new String(veryLongString.substring(1,10));
The String(String) constructor is implemented that way:
public String(String original) {...if (originalValue.length > size) {// The array representing the String is bigger than the new// String itself. Perhaps this constructor is being called// in order to trim the baggage, so make a copy of the array.int off = original.offset;v = Arrays.copyOfRange(originalValue, off, off+size);}...}
 

5. Which two method you need to implement for key in hashMap ?
(equals and hashcode) read How HashMap works in Java for detailed explanation.
 

6. Where does these two method comes in picture during get operation?
See here How HashMap works in Java for detailed explanation.
 

7. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
Open for all, my friend didn't know the answer so he didn't mind telling me.
 

8. What is difference between Executor.submit() and Executer.execute() method ?
(Former returns an object of Future which can be used to find result from worker thread)
@vinit Saini suggesed a very good point related to this core java interview question
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will rethrow this exception, wrapped in an ExecutionException.


9. What is the difference between factory and abstract factory pattern?
Open for all, he explains about factory pattern and how factory pattern saves maintenance time by encapsulating logic of object creation but didn't know exact answer
@Raj suggestedAbstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
 

10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
see my article 10 Interview questions on Singleton Pattern in Java
 

11. Can you write Critical section code for singleton?

check here 10 Interview questions on Singleton Pattern in Java
 

12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?Tricky one but he managed to write using while and for loop.
 

13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java
 

14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap. See here How HashMap works in Java for detailed explanation.
 

15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)
 

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
 

18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.
 

19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @MohitRead the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code…
long start = System.currentTimeMillis ();method ();long end = System.currentTimeMillis ();
System.out.println (“Time taken for execution is ” + (end – start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing

20. Why main method is static in Java?
Now come to the main point "Why main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:
  • Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
  • Since C and C++ also has similar main method which serves as entry point for program execution, following that convention will only help Java.
  • If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
  • Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
    Why main mehtod is public in Java.Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public inJava, JVM can easily access and execute it.
    Why main method is void in Java. Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.
    Summary:
  • Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
  • JVM throws NoSuchMethodException:main if it doesn't find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.
  • Main method is entry point for any Core Java program. Execution starts from main method.
  • Main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.
  • When you see "Exception in Thread main” e.g. Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.
  • You can declare main method using varargs syntax from Java 1.5 onwards e.g.public static void main(String... args)
  • Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.
  • Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified above.
  • You can use throws clause in signature of main method and can throw any checked or unchecked Exception.
  • Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.


Multithreading

If you are going for java interview on any Investment bank expect lots of muti-threading interview questions on your way. Multi-threading is a favorite topics on Investment banking specially on electronic trading development and they grill candidate on many confusing java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in java because most of them are in business of performance. High volume low latency Electronic trading System which is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview questions on java asked on different on different time. I am not providing answer of these thread interview questions but I will give you hint whenever possible. Answer of these java thread interview questions can be found by doing Google. More important is to understand the concept behind these multi-threading questions simply mugging the answers of thread interview questions is not going to help because there would be a lot of follow-up questions based upon your answer and if you haven't master the particular thread topic it would be difficult. Threading in Java is very interesting topic even more after Java 5 which has added lot of concurrency classes and now days interview on java thread are mostly focus around this new concurrent utilities like Executor framework, Countdown Latch, Atomic classes, Re-entrant and ReadWriteLock and Concurrent Collection classes.
15 Java Thread Interview Questions and answers
1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?

This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.
2) What is the advantage of new Lock interface over synchronized block in Java?

You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like concurrenthashmp and conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any java multi-threading interview because now days Its heavily used to build cache for electronic trading system on client and exchange connectivity space.

3) What are differences between wait and sleep method in java?

Another classic interview question on java thread mostly asked in phone interview. Only major difference is wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.
4) Write code to implement blocking queue in Java?

This java multi-threading interview question servers many purpose , it checks whether candidate can actually write java code using thread or not, it sees how good interviewee is on understanding scenarios of multi-threading and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it you can ask him to write it again using new java 5 concurrent classes.

5) Write code to solve the Produce consumer problem in Java?

Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions as what happen if you have multiple Producer and single consumer or vice-versa , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well.
6) Write a program which will result in deadlock? How will you fix deadlock in Java?

This is my favorite java thread interview question because even though deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. To read more about deadlock in java see the link.
7) What is atomic operation? What are atomic operations in Java?

Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You can read more about java synchronization here.
8) What is volatile keyword in Java? How to use it?

How is it different from synchronized method in Java?Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5 and Java memory model. It’s good to prepare well about how volatility ensures visibility, ordering and consistency.
9) What is race condition?

How will you find and solve race condition?Another classic java threading interview questions and mostly interviewer grill on recent race condition you have faced and how did you solve it and some time they will write sample code and ask you detect race condition. In my opinion this is one of the best java thread interview question and can really test the candidate's experience on solving race condition or writing code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency practices in Java'".
10) How will you take thread dump in Java?

How will you analyze Thread dump?In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it.
11) Why we call start() method which in turns calls run method, why not we directly call run method ?

Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews.
12) How will you awake a blocked thread in java?

This is tricky question blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing Interrupted Exception.
13) What is difference between CyclicBarriar and Countdown Latch in Java ?

New java thread interview questions mostly to check familiarity with JDK 5 concurrent packages.
14) What is immutable object?

How does it help on writing concurrent application?Another classic interview questions on multi-threading, not directly related to thread but indirectly helps a lot. This java interview question can become more tricky if ask you to write an immutable class or ask you Why String is immutable in Java as follow-up.
15) What are some common problems you have faced in multi-threading environment?
How did you resolve it?

Memory-interference, race conditions, deadlock, live lock and starvation are example of some problems comes in multi-threading and concurrent programming. There is no end of problem if you get it wrong and they will be hard to detect and debug. This is mostly experienced based interview question on java thread instead of fact based.
These were my favorite java thread interview questions and mostly asked on java interview s on Investment banks. This list is by no means complete so please contribute some of interesting java thread questions you have faced during interview. Purpose of this article is to collect and share great interview questions on multi-threading concept which not only helps on interview but opens door for learning new threading concept.