Wednesday, July 25, 2012

Interview Questions - Java

1. What is the difference between Comparator and Comparable Interface?


it has a method compareTo
this should be implemented by the types that are to be compared
to compare using comparable the object to be compared has to define the rule for comparison
the collection uses the logic mentioned in this to sort its elements automatically
public static <T extends Comparable<? super T>> void sort(List<T> list)
this reference is compared eith the specified object
used to provide default ordering behavior.
used to provide natural ordering for the object


it has 2 methods:  compare and equals
this should be implemented by the classes that compare other two objects.
while using comparator the object to be compared need not provide the rule for comparison
this should be  to a sort method explicitely for the sort to use this logic to sort the collection.
public static <T> void sort(List<T> list, Comparator<? super T> c)
two provided objects are compared against each other.
used when we need more that one ordering logic for the same object
used to provide any ordering apart form the natural ordering

2. What is Serializable interface?

This is also known as Tagging interface. They are used to denote that a particular class that implements this interface has a special feature based on the interface it implements. Clonable, Serializable, EventListener, SingleThreadModel are all Serializable interfaces. They do not have any member declaration so the class that implements it need not implement any method and hence the name.

3. Split the below string to get the individual numbers as an array?
// String to split "1|2|3|4|5;"
public class Test {
 public static void main(String[] args) {
  // input value
  String s1 = "1|2|3|4|5;";
  //logic to split
  String[] s2 = s1.split(";");
  String[] s3 = s2[0].split("\\|");
  // print output
  for(String s: s3){
4. Difference between hashmap and hashtable?


Permits null value
it is unynchronized
it is faster that hashtable
uses iterator which is fail fast


Permits only non-null values
it is synchronized
uses enumeration which throws ConcurrentModificationException
Related Posts Plugin for WordPress, Blogger...