Wednesday, September 3, 2014

Collection QA

Q1) Difference between Iterator and listIterator?


Answer

Iterator: can traverse only in forward direction.

ListIterator: can traverse in forward as well as backward direction.

It is an interface which provide the capability to traverse the list in both direction.
This interface also provide the facility to insert the element in a list that means we can perform removal as well as insertion.
Since List is ordered and it is indexed so we can travel it forward direction as well as backward direction , on the other hand Set is unordered that is why the listIterator() method is available only for List interface not for Set.

Example:

ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");

/*ListIterator*/
ListIterator itr=al.listIterator();
// start from 0th position and goes one by one till the end
while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
// start from last position and goes one by one to the beginning
while(itr.hasPrevious()) 
      {
          System.out.println(itr.previous());
      }


Q2) Difference between fail-fast and fail-safe Iterator

Java provides the iterator to iterate the objects in the Collection. The rule is that the Collection should not be altered when iterating, if modified you will get the ConcurrentModificationException.

Fail-Fast Iterator

Iterator will fail if change in the collection. What ever the change it may be adding, update or removal of any object in the collection will throw the ConcurrentModificationException. Lets look it in the below example.

List al = new ArrayList();
al.add("1");
al.add("2");
al.add("3");
Iterator it = al.iterator();
int indexFlag = 1;
while(it.hasNext())
{
indexFlag++;
if(indexFlag==2)
{

al.remove(indexFlag);
}
}
O/P
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at FailIterator.main(FailIterator.java:20)

Fail-Safe Iterator

Whereas the fail-safe iterator will not throw any exception when the collection such asCopyOnWriteArrayList and ConcurrentHashMap  is modified. As it iterates on the copy of the collection
CopyOnWriteArrayList ca = new CopyOnWriteArrayList();
ca.add("1");
ca.add("2");
ca.add("3");
int indexFlag = 1;
Iterator it = ca.iterator();
while(it.hasNext())
{
indexFlag++;
if(indexFlag==2)
{
ca.remove(indexFlag);
}
}

How to Safely remove object from the collection while Iterating?

To remove the Object from the collection , instead of directly removing from the collection , you can use the remove() provided by the iterator.
List al = new ArrayList();
al.add("1");
al.add("2");
al.add("3");
int indexFlag = 2;
Iterator it = al.iterator();
while(it.hasNext()) {
it.remove();
}



Java

Q1) What are different types of access modifiers in Java?
Ans) There are four different types of modifiers:
Modifer
Accessible in the same package
Accessible in different package
Private
No
No
Protected
Yes
Yes, only if the class extends the main class
Default
Yes
No
Public
Yes
Yes
Q2) What is the use of final keyword?
Ans) The final keyword can be assigned to
  1. Class level variable
  2. method
  3. class
  4. Objects
If a final is assigned to a variable, the variable behaves as a constant. It means that the value of variable once set cannot be changed.
final int i=1;
i =5; // error
If a final is assigned to a method then it cannot be overridden in its child class.
class Parent {
final void print(){
            System.out.println(“Inside”);
}
}
class Child extends Parent{
public final void print(){             // error cannot override final method
            System.out.println(“Inside”);
}
}
If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class.
Final objects are instantiated only once. i.e
final Map map = new HashMap();
map.put(“key”,”value”);
map = new HashMap();  // error
Q3) What is use of synchronized keyword?
Ans) This keyword is used to prevent concurrency. Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
            synchronized (this){             // synchronized keyword on block of  code
            }
}
Q4) What is volatile keyword?
Ans) Essentially, volatile is used to indicate that a variable's value will be modified by different threads.
Declaring a volatile Java variable means:
  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
Q5) What is a transient variable?
Ans) If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.
Q6) What is a strictfp modifier?
Ans) Strictfp is used with variable only . It is used to restrict floating point calculations ( fp ) to ensure portability ( platform Independent ). When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the consistent value independent of the platform. That is, if you want the answers from your code (which uses floating point values) to be consistent in all platforms, then you need to specify the strictfp modifier.
Q7) Why static methods cannot access non static variables or methods?
Ans) A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.
Q8) What is static class ?
Ans) A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only
Q9) What is throw keyword?
Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.
  public void parent(){
  try{
   child();
  }catch(MyCustomException e){ }
  }


  public void child{
  String iAmMandatory=null;
   if(iAmMandatory == null){
    throw (new MyCustomException("Throwing exception using throw keyword");
   }
  }
Q10) What is use of throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration.
  public void parent(){
  try{
   child();
  }catch(MyCustomException e){ }
  }


  public void child throws MyCustomException{
   //put some logic so that the exception occurs.
  }