Myblog's Blog

November 17, 2009

Filed under: Collections — technospider @ 6:45 pm
Q1) What is difference between ArrayList and vector?

Ans: )

1) Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Q2) How can Arraylist be synchronized without using Vector?

Ans) Arraylist can be synchronized using:

Collection.synchronizedList(List list)

Other collections can be synchronized:

Collection.synchronizedMap(Map map)

Collection.synchronizedCollection(Collection c)

Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?

Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID

2) Now call Collections.sort() method and pass list as an argument.

Now consider that Employee class is a jar file.

1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .

2) Call Collections.sort() on the list and pass comparator as an argument.

Q4)What is difference between HashMap and HashTable?

Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are

1. Hashmap is not synchronized in nature but hshtable is.

2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
Fail-safe – “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException”

3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Q5) What are the classes implementing List interface?

Ans)
There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Q6) Which all classes implement Set interface?

Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.

SortedSet – It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.

TreeSet – It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Q7) What is difference between List and a Set?

Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?

Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :

      1. int [] intArray= new int[6];
      2. intArray[7]   // will give ArraysOutOfBoundException.

Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.

  1. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.

List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.

  1. ArrayList is one dimensional but array can be multidimensional.

int[][][] intArray= new int[3][2][1];   // 3 dimensional array

  1. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
Q9) When to use ArrayList or LinkedList ?

Ans)  Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using “get” is fast, but for LinkedList, it’s slow. It’s slow because there’s no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you’re doing random access on the list, and a LinkedList works better if you’re doing a lot of editing in the middle of the list.

Source : Read More – from java.sun

Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?

Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

Q11) Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.

Ans) For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Q12) Which design pattern Iterator follows?

Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.

Example of Iteration design pattern – Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Q13) Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();

Ans) It is preferred because:

  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible
Q14) What is difference between iterator access and index access?

Ans) Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the ‘n’ location and get the element. It doesnot traverse through n-1 elements.

In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the ‘n’th element it need to traverse through n-1 elements.

Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.

Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.

Traversal or search in index based datastructure is faster.

ArrayList is index access and LinkedList is iterator access.

Q15) How to sort list in reverse order?

Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.

List list = new ArrayList();

Comparator comp = Collections.reverseOrder();

Collections.sort(list, comp)

Q16) Can a null element added to a Treeset or HashSet?

Ans) A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

Q17) How to sort list of strings – case insensitive?

Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Q18) How to make a List (ArrayList,Vector,LinkedList) read only?

Ans) A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

Q19) What is ConcurrentHashMap?

Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

Q20) Which is faster to iterate LinkedHashSet or LinkedList?

Ans) LinkedList.

Q21) Which data structure HashSet implements

Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.

Q22) Arrange in the order of speed – HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap

Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.

Q23) What is identityHashMap?

Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

Q24) What is WeakHashMap?

Threads

Filed under: Threads — Tags: , , , , , , — technospider @ 6:43 pm

1. Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
2. What happens when a thread calls notify() but no thread(s) is waiting?
3. How will you declare a timer variable that will be accessed by multiple threads very frequently?
4. How will you synchronize static variables?

5. What happens when threads are waiting, but never being notified?

//
//

ANSWERS:

1. Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
2. Actually…, nothing :) the notify() call simply returns.
3. Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
4. Obtain class level lock. synchronized( obj.getClass()) {……..}
5. Leaving the answer to readers! :)

My interview Questions – Collections

Filed under: Qualified, Uncategorized — technospider @ 6:30 pm

1. You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best pet?
2. What goes wrong if the HashMap key has same hashCode value?
3. If hashCode() method is overridden but equals() is not, for the class ‘A’, then what may go wrong if you use this class as a key in HashMap?
4. How will you remove duplicate element from a List?
5. How will you synchronize a Collection class dynamically?

1. Obviously, LinkedList.
2. It leads to ‘Collision’ wherein all the values are stored in same bucket. Hence, the searching time increases quad radically.
3. Left to Readers.
4. Add the List elements to Set. Duplicates will be removed.
5. Use the utility method java.util.Collections.synchronizedCollection(Collection c)

My interview questions -Design Patterns

Filed under: Qualified — technospider @ 6:16 pm

Question: You have to write a java program that can read files of varying sizes, ranging from 100 KB (very small) to few GBs (large size). Can you give me space optimized and memory optimized approach to solve this ?

Question: How will you design your Singleton Patten class to be thread-safe? (a standard interview question!)

Adding synchronized keyword to the getSingleton() method is inefficient solution. Initialize the static private Singleton object within Synchronized block. In this way you can achieve it.

What Design Pattern can be used for classical Producer Consumer problem? (a simple question)

Use observer pattern (publisher subscriber model)

Question: M.S Word can store million lines of text. Each character in the text will have set of properties like font-color, font-size, font-style and etc. So, M.S Word application has to maintain a property structure for each and every character and that may lead to heavy storage. What design pattern will you apply to overcome this problem?

You have to create property group for each possible styles (font-size, font-color, font-face & etc). So, common characters will be part of a property group, there by reducing the storage of each character. This is called FlyWeight Pattern.

Your application uses 1000 classes and they have interaction among each other. This will lead to complex communication across objects, so what design pattern can solve this problem?

Use Mediator pattern to separate the direct communication across objects.

Question: An application reads input from various clients in multiple stages and creates a binary tree structure out of all received inputs. Which design pattern can be used to design such application?

Building an object in multiple set – you call it Builder pattern! The realworld example is XSDBuilder class in Java.

You have to design a budget management application for global users. But, have to provide an option to configure their native tax rules. Which design pattern, do you think, can solve this?

Use Template Pattern. It provides templates of methods and allowing you to override certain portion of logic.

You have a core application class. But, you have to be able assign extra functionalities to the core class on the fly (at runtime). Which patterns deserves this purpose?

Decorator Pattern. This is similar to the pattern designed for java.io.* classes(BufferedReader, DataInputStream and etc.)

Java Performance interview questions

Filed under: JAVA — technospider @ 3:59 pm
  1. You have to write a java program that can read files of varying sizes, ranging from 100 KB (very small) to few GBs (large size).
  2. You have to use JDBC (type 4 driver) to retrieve some values from two different tables in database. As you have to use join operation in this case, will you consider using join in the sql query level or in the program level?
  3. How will you plan your optimization strategy for a given J2EE (or Java) application?
  4. Give some strategy to optimize web tier (JSP/Servlets)?
  5. How will you tune the Data base tier?
  6. Answers

  1. The for loop iterates only once, not 100 times. So the running time is 10 millisecond. Because, the loop evaluates to a constant result ( that is, k = 20 * 100 will yield same result for 100 times) . So, jvm is smart enough, runs the for() loop once and saves time. I just mention this, because the developer should not worry about expression level optimization, which is taken care by the jvm itself.
  2. You can write an intelligent program in this case :) . If the file size is smaller, then read the whole file content in one-go. Read an example program given here. But, what if the file size is big? In this case, the program can’t read the whole file in one shot, as it would run out of memory. So, you can write the program in such a way that it reads the file content in byte arrays for several iterations. In this case, the running time of the program will depend on the size of byte array. So, how will you smartly determine the size of byte array?You can use Runtime.getRuntime().freeMemory() to find the freely available heap size. Based on this available memory, your program can create smaller or larger byte arrays at runtime. The larger the byte arrays, the lesser the response time.
  3. You have to move the join operation to query level. Never try to do (joining, sorting, aggregating, grouping and etc) such things application level, unless otherwise it is required. Because, SQL processor may optimize the join and prepare the better execution plan than you!
  4. It is too vast topic for discussion. In short,
    • Use profiler tools (there are so many.. example is JProfiler), monitoring tools and generate reports. From the report, analyze the response time of each component.
    • First, you have to analyze the response time of read/write tasks such as: I/O, Database access. Because, that is where most of the time spent.
    • Look for poor code that doesn’t release database connection or doesn’t close files and etc.
    • Minimize the repeated interaction with components as much as possible.
  5. Again, a vast topic!
    • Clearly identify static and dynamic portion of the web components. Enable client browser-level-cache for static web resource to save the network roundtrip.
    • Don’t dump all the data in session object, because that may lead your server running out of space at sometime.
    • Enable <load-on-startup> for all sticky servlet (servlets that are accessed many times).
    • Analyze whether you can zip and transfer some of the content.
  6. It is really really a big topic and hence, leaving it to the readers end! :)

Java servlet interview questions

Filed under: JAVA — technospider @ 3:57 pm
  1. After hitting submit button, a JSP page processes a database transaction. You have accidentally closed the browser window. Will the database transaction continue or will get over?
  2. What is the difference between http GET and POST methods ?
  3. There are 10 servlets in your web application, and they are frequently used (sticky Servlet). How will you optimize their loading?
  4. How will you communicate across Servlets? (or, how will you achieve Inter Servlet communication?)
  5. Hope, you know the difference between RequestDispatcher.forward() and RequestDispatcher.sendRedirect(). So, which one is desirable to use?
  6. What is the class path hierarchy for a Servlet?
  7. You can’t read files (located out of tomcat directory) from JSP and Servlets for security purpose. But, how will you access those files from JSP or Servlets, in case if you need them?

Javascript interview questions

Filed under: JAVA — technospider @ 3:49 pm

1. cssfloat property

2. what are the different ways to hide content on a page (style.display = “none”, style.visibility = “hidden”, table with height = 0)

3. setTimeout

4. setInterval and how to clear the interval

5. window object

6. prototype

Java-Trick interview Questions

Filed under: JAVA — technospider @ 3:45 pm
  1. Give the use and an example of the scenario where you would use serialVersionUID in a your Java class?
  2. Design a Employee class with name, empId, age and address fields.
    • Any two Employee objects are compared based on their age.
    • The empId is the unique id for Employee class. The Employee class can be used in Collections and HashMap.
  3. Explain what goes in a HashMap or Hashtable, when you store the objects with same hashcode values. Explain your answer in very depth.
  4. In JVM Memory, where the private, public, protected, static, String literal and object references are stored?
  5. How will you store your exception stack trace in a file? (you should not redirect the console output)
  6. What is the use of Weak, Soft, Phantom references in Garbage Collection of java? Give scenarios.
  7. How will you keep an object alive for ever in the JVM memory? (trick: use finalize() method)

Google -Algorithm Interview questions

Filed under: JAVA — technospider @ 3:44 pm

1. Anagram (GOD <-> DOG) : algorithm to identify if two given strings are anagrams

2. Given a source array of integers with possible duplicates and a target integer, write algorithm to find out 2 numbers in source array whose sum is equal to target integer.

3. If pre-processing of source in the above is allowed, what pre-processing will you do to reduce the complexity of algorithm written above ?

4. If you are given a random number generator which gives float value between 0 and 1 & if an array is given, write algorithm to randomize the array values.

5. Given an array of strings, write algorithm to find out if there are duplicates and also print the duplicate strings once.

6. For all the above questions, they will ask you to determine big o complexity and check for ways to optimize.

Google Java interview Questions

Filed under: JAVA — technospider @ 3:41 pm

2. Differences between final, finally and finalize

3. Where can I initialize a final variable other than the place it is declared (constructor).

4. If I want to use a custom object as a key in hashmap, what methods do I need to override ? (equals and hashcode)

« Newer PostsOlder Posts »

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.