Monday, October 22, 2012

Java Collections Important Questions & Concepts

1) What is a Collection Framework ?

A) Collection framework is a class library to handle group of objects. Collection framework is implemented in java.util package.

2) Does a Collection object store copies of other objects or their references ?

A) collection object stores references of other objects.

3) Can you store primitive data type into a collection ?

A) No, Collections store only objects.

4) What is the difference between Iterator and ListIterator ?

A) Both are useful to retrieve elements from a collection. Iterator can retrieve the elements only in forward direction. But ListIterator can retrieve the elements in forward and backward direction also. So ListIterator is preferred to Iterator.

5) What is the difference between Iterator and Enumeration ?

A) Both are useful to retrieve elements from a collection. Iterator has methods whose names are easy to follow and Enumeration methods are difficult to remember. Also Iterator has an option to remove elements from the collection which is not available in Enumeration. So, Iterator is preferred to Enumeration.

6) What is auto boxing ?

A) Converting a primitive data type into an object form automatically is called 'auto boxing'. Auto boxing is done in generic types.

7) What is difference between an ArrayList and a Vector?

A)       There are two important differences between an ArrayList and Vector
           a) 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.
            b) 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.

8) How can Arraylist be synchronized without using Vector?

A)  Arraylist can be synchronized using :-
                
                 Collection.synchronizedList(List list)

      Map can be synchronized using :-
 
                 Collection.synchronizedMap(Map map)

      Other collections can be synchronized using :-

                 Collection.synchronizedCollection(Collection c)

9) What is difference between HashMap and HashTable?

A)  Both Collections implements Map. Both Collections store values as key-value pairs. The key differences between the two are :-
                a. Hashmap is not Synchronized in nature where as HashTable is Synchronized.

                b. 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.

               c. HashMap permits null values and only one null key, while Hashtable doesn't allow any of its key or value as null.

  •  If you want to learn more about FailFast and FailSafe please refer to the below link
http://javarevisited.blogspot.in/2012/02/fail-safe-vs-fail-fast-iterator-in-java.html


10) What all classes implement List Interface ?

A) There are three classes that implement the List Interface they are :-
 
            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.

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

            LinkedList: The LinkedList also implements Queue interface and provides 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.


11) Which all classes implement Set interface ?

A) 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.


 12) What is difference between List and a Set?

A) List can contain duplicate values but Set doesnt allow. Set allows only unique elements. 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)

13) What is difference between Arrays and ArrayList ?

A) Arrays are of fixed size whereas ArrayList is is not of fixed size.

Some of the advantages ArrayList has over arrays are :-

  • ArrayList can grow dynamically.
  • It provides more powerful insertion and search mechanisms than arrays.
It means that once array is declared as :

Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
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.

          ArrayList is one dimensional but Array can be multidimensional.

To create an array the size should be known or initalized to some value. If not it should be initialized carefully such that there could me no memory wastage. But arrayList is all about dynamic memory creation and there is no wastage of memory.







Sunday, October 21, 2012

The Java Virtual Machine

Components in JVM architecture





Core Java Interview Questions

Dynamic Method Dispatch or RunTime Polymorphism

Dynamic Method Dispatch is a process in which a call to an overriden method is resolved at runtime rather than compile time. An overriden method is called through the reference variable of a super class.

When reference variable of a parent class refers to the object of a child class, it is known as upcasting.

class India{}
class Mumbai extends class India{}
India ind = new Mumbai() // This is called upcasting

Example :-

class Vehicle {
void drive(){
System.out.println("Driving Vehicle");
     }
}

class Bentley extends Vehicle {
void drive() {
System.out.println("Driving Bentley");
}

public static void main(String ar[]){
Vehicle v = new Bentley();
v.drive();
   }
}

OUTPUT: Driving Bentley

  • Runtime polymorphism cannot be achieved by data members.
  • Runtime polymorphism can be achieved through multilevel inheritance.


1. What is the difference between an executable file and a .class file ?
   A) ".exe" file contains machine language instructions for the microprocessor and is system dependent. ".class" file contains byte code instructions for the JVM and is system independent.

2. Why Java is suitable for Internet ?
    A) Java is suitable for Internet because of two main reasons.
         1) It is system independent and hence its programs can run on any type of computer system available on internet.
          2) It eliminates a lot of security problems for data on internet.

3. Why Pointers are eliminated in Java ?
     A)  1) Pointers lead to confusion for a programmer.
           2) Pointers may crash a program easily, for example, when we add two pointers, the program crashes immediately. The same thing could also happen when we forget to free the memory allotted to a variable and reallocate it to some other variable.
           3) Pointers break security. Using pointers, harmful programs like Virus and other hacking programs can be developed.
Because of the above reasons pointers have been eliminated from Java.

4. What is the difference between a function and a method ?

A)  A method is a function that is written in a class. We do not have functions in Java; instead we have methods. This means whenever a function is written in Java, it should be written inside the class only. But if we take C++, we can write the functions inside as well as outside the class. So in C++, they are called member functions and not methods.

5. Is Java a purely object oriented language or not ?

A) The following reasons are put forward by many people to say Java is not a purely object oriented programming language.

      1. 'Purely object oriented' means it should contain only classes and objects. It should not contain primitive datatypes like int, float, char etc, since they are neither classes nor objects.

      2. In pure object oriented languages, we should access every thing by messages passing (through objects). But, Java contains static variables and methods which can be accessed directly without using objects.

      3.Java does not contain multiple inheritance. It means an important feature of object oriented design is lacking. So how can we say it is purely object oriented ?

No doubt Java is purely object oriented programming language. The preceding points represent lack of in depth understanding of Java.

      1. Even if Java has primitive datatypes, these types are used inside a class and never outside of it. So, they are part of a class. See the API specification on the class. 'Class'.Java specification says that all the arrays and the primitive Java types(boolean,byte,char,short,int,long,float, and double), and the keyword void are also represented as objects of the class 'Class'.

       2. Even static variables and static methods are written inside a class. When accessing them from outside, we should use classname. It means they are part and parcel of class definition and should not be considered as individual elements. For reducing memory utilization, only one copy of them will be created in memory and shared by all objects.

       3. Any purely object oriented language should follow all the 5 features of Object oriented Programming System(OOPS). They are :-
  • Classes and objects.
  • Encapsulation 
  • Abstraction
  • Inheritance 
  • Polymorphism
Remember Java contains all these features and hence it is purely object oriented language. Just because Java does not contain multiple inheritance, we should not say it is not purely object oriented language. Multiple inheritance is not the main feature of OOPS, it is only a sub feature under inheritance.

6. Which part of JVM will allocate the memory for a Java program ?
A) Class loader subsystem of JVM will allocate the necessary memory needed by the Java program.

7. Which algorithm is used by garbage collector to remove the unused variables or objects from memory ?
A) Garbage collector uses many algorithms but the most commonly used algorithms is mark and sweep.

8. How can you call the garbage collector ?
A) Garbage Collector is automatically invoked when the program is being run. It can be also called by calling gc() method of Runtime class or System class in Java.