Tuesday, September 16, 2014

Java Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Example:

Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:
  • A Deer IS-A Animal
  • A Deer IS-A Vegetarian
  • A Deer IS-A Deer
  • A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap.

Virtual Methods:

In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.
/* File name : Employee.java */
public class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
   {
      address = newAddress;
   }
   public int getNumber()
   {
     return number;
   }
}
Now suppose we extend Employee class as follows:
/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}
Now, you study the following program carefully and try to determine its output:
/* File name : VirtualDemo.java */
public class VirtualDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
      System.out.println("Call mailCheck using Salary reference --");
      s.mailCheck();
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}
This would produce the following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Here, we instantiate two Salary objects . one using a Salary reference s, and the other using an Employee reference e.
While invoking s.mailCheck() the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.
Invoking mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and the methods are referred to as virtual methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

Priority Queue

Java PriorityQueue

PriorityQueue belongs to the Java Collections Framework. PriorityQueue is based on  priority heap and it is an implementation of Queue interface. This data structure can be used when we need a Queue implementation and we have a requirement to maintain the elements of that collection in a specific sorted order based on each element’s priority. It was introduced in JDK 1.5
Java PriorityQueue

Java PriorityQueue Key points

  • A Comparator can be provided in the constructor when instantiating a PriorityQueue. Then the order of the items in the Queue will be decided based on the Comparator provided.
  • If a Comparator is not provided, then the natural order (Comparable) of the Collection will be used to order the elements.
  • null is not allowed in this Collection.
  • Head of the Queue is the least item in the order.
  • Ordering ties between the PriorityQueue elements are decided arbitrarily.
  • PriorityQueue is not synchronized. PriorityBlockingQueue is the thread-safe counterpart of PriorityQueue.
  • PriorityQueue is unbounded and it grows dynamically based on the number of elements in the Queue. It has internal capacity at any given time and it is increased as the elements are added. The policy for this internal capacity and increment is not specified or standardized.
  • The iterator() of this PriorityQueue does not guarantee for traversal of the Queue elements in any particular order.
  • Performance wise; remove() and contains() methods take linear time. peek(), element() and size() takes fixed time. offer(), poll() and remove() takes O(log n) time.
  • offer() and add() are methods of the Queue interface and implemented by the PriorityQueue. These are used of element insertion in the queue. They behave the same with respect to PriorityQueue and no difference between them.

PriorityQueue Example

Following example explains how we can use a Java PriorityQueue collection.

PriorityQueueExample.java

package com.javapapers.java;

import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueExample {
 public static void main(String[] args) {
  Comparator<String> queueComparator = new VowelComparator();
  PriorityQueue<String> priorityQueue = new PriorityQueue<String>(10,
    queueComparator);
  priorityQueue.add("orange");
  priorityQueue.add("fig");
  priorityQueue.add("watermelon");
  priorityQueue.add("lemon");
  while (priorityQueue.size() != 0) {
   System.out.println(priorityQueue.remove());
  }
 }
}

VowelComparator.java

This Comparator class is used to determine the sort order of the above PriorityQueue.
package com.javapapers.java;

import java.util.Comparator;

class VowelComparator implements Comparator<String> {

 @Override
 public int compare(String x, String y) {
  if (getVowelCount(x) < getVowelCount(y)) {
   return -1;
  } else if (getVowelCount(x) > getVowelCount(y)) {
   return 1;
  }
  return 0;
 }

 public int getVowelCount(String word) {
  int vowel = 0;
  for (int i = 0; i < word.length(); i++) {
   char chr = word.charAt(i);
   if (chr == 'a' || chr == 'A' || chr == 'e' || chr == 'E'
     || chr == 'i' || chr == 'I' || chr == 'o' || chr == 'O'
     || chr == 'u' || chr == 'U')
    vowel++;
  }
  return vowel;
 }
}

PriorityQueue Example Output

fig
lemon
orange
watermelon

Monday, September 15, 2014

Java Collections Interview Questions – Part I

Java Collections Interview Questions – Part I

Following are the Java collections interview questions most frequently asked in interviews. I have attempted to keep the answers short and simple, as the objective is to help you prepare and revise topics for interviews quickly.
interview

Java Collections Interview Questions

  1. How to filter a Java collection?
  2. How to sort a Java Collection?
  3. Best way to convert a List to a Set.
  4. When to use LinkedList over ArrayList?
  5. Difference between HashMap and Hashtable.
  6. Explain Java hashCode() and equals() method.
  7. What is Java Priority Queue?
  8. Difference between ArrayList and Vector.
  9. What are Java concurrent Collection classes?
  10. Explain about Comparable and Comparator.

Java Collections Interview Questions and Answers

  1. How to filter a Java collection?

    The best way to filter a Java collection is to use Java 8. Java streams and lambdas can be used to filter a collection as below,
    List<Person> passedStudents = students.stream()
        .filter(p -> p.getMark() > 50).collect(Collectors.toList());
    If for some reason you are not in a position to use Java 8 or the interviewer insists on pre Java 8 solution, following is the best way to filter a Java collection.
  2. How to Sort a Java Collection?

    Use a Comparator to sort a Java Collection.
      
    List<Animal> animals = new ArrayList<Animal>();
    Comparator<Animal> comparator = new Comparator<Animal>() {
        public int compare(Animal c1, Animal c2) {
            //sort logic here
      return c2.getHeight() - c1.getHeight();  
        }
    };
    
    Collections.sort(animals, comparator);
    If Animal implements Comparable, then following is just enough.
    Collections.sort(animals);
  3. Best way to convert a List to a Set.

    Instantiate Set using the HashSet.
    Set<Animal> animalSet = new HashSet<Animal>(animalList);
  4. When to use LinkedList over ArrayList?

    Java’s LinkedList implementation is a doubly linked list. ArrayList is a dynamically resizing array implementation. So to compare between LinkedList and ArrayList is almost similar to comparing a doubly linked list and a dynamically resizing array.
    LinkedList is convenient for back and forth traversal sequentially, but random access to an element is proportionally costlier to the size of the LinkedList. At the same time, ArrayList is best suited for random access using a position.
    LinkedList is best for inserting and deleting an element at any place of the LinkedList. An ArrayList is not suited for inserting or deleting elements in the mid of the ArrayList. Since everytime a new element is inserted, all the elements should be shifted down and dynamic resizing should be done.
    With respect to memory usage of LinkedList and ArrayList, LinkedList collection uses more memory as it needs to keep pointers to the adjacent elements. This overhead is not present for the ArrayList, just the memory required for the data is sufficient. Consider these factors and decide between LinkedList or ArrayList depending on the use case.
  5. Difference between HashMap and Hashtable.

    • HashMap is not synchronized but Hashtable is synchronized.
    • HashMap allows null as key and value. Since the key is unique, only one null is allowed as key. Hashtable does not allows null in key or value.
    • LinkedHashMap extends HashMap and so can be converted. It helps to have a fixed iteration order. It is not possible with Hashtable.
    • In essense, there is almost no reason to use a Java Hashtable.
  6. Explain Java hashCode() and equals() method.

    equals() method is used to determine the equality of two Java objects. When we have a custom class we need to override the equals() method and provide an implementation so that it can be used to find the equality between two instance of it. By Java specification there is a contract between equals() and hashCode(). It says,
    "if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer"
    Whenever we choose to override equals(), then we must override the hashCode() method. hashCode() is used to calculate the position bucket and keys.
  7. What is Java Priority Queue?

    Java PriorityQueue is a data structure that is part of Java collections framework. It is an implementation of a Queue wherein the order of elements will be decided based on priority of each elements. A comparator can be provided in the constructor when a PriorityQueue is instantiated. That comparator will decide the sort order of elements in the PriorityQueue collection instance.
  8. Difference between ArrayList and Vector.

    We have beaten this enough in a old article difference between Vector and ArrayList in Java.
    • Vector is synchronized and ArrayList is not.
    • Vector doubles its internal size when its increased. But, ArrayList increases by half of its size when its increased.
    • ArrayList gives better performance over Vector as its not synchronized.
    • ArrayList’s Iterators are fail-fast but Vector’s Enumeration is not fail-fast.
    • ArrayList was introduced in Java 1.2 and Vector even before that. But initially Vector was not part of Java collections framework and later made part of collections framework.
    • As of now, there is no need to use Vector and it can be considered legacy and to be deprecated. If you need synchronized collection an ArrayList can be synchronized and used.
  9. What are Java Concurrent Collection Classes?

    Concurrent Collections were introduced in Java 5 along with annotations and generics. These classes are in java.util.concurrent package and they help solve common concurrency problems. They are efficient and helps us to reduce common boilerplate concurrency code. Important concurrent collection classes are BlockingQueue, ConcurrentMap, ConcurrentNavigableMap and ExecutorService.
  10. Explain about Comparable and Comparator

    A class can implement the Comparable interface to define the natural ordering of the objects. If you take a list of Strings, generally it is ordered by alphabetical comparisons. So when a String class is created, it can be made to implement Comparable interface and override the compareTo method to provide the comparison definition. We can use them as,
    str1.compareTo(str2);
    Now, what will you do if you want to compare two strings based on it length. We go for the Comparator. We create a class and let it implement the Comparator interface and override compare method. We can use them as,
    Collections.sort(listOfStrings, comparatorObj);
    The natural ordering is up to the person designing the classes. Comparator can be used in that scenario also and it can be used when we need multiple sorting options. Imagine a situation where a class is already available and we cannot modify it. In that case also, Comparator is the choice.

Why Object is Super Class in Java?

Why Object is Super Class in Java?

java.lang.Object class is the super base class of all Java classes. Every other Java classes descends from Object. Should we say the God class? Why is that so? This Java article is to discuss around it.
In Mathematics, an axiom is a starting point of reasoning using which other statement can be logically derived. The concept of Object class as super class of all classes in Java looks similar to it.
super-class
It is not a explicit requirement forced on the developer. If a class is declared without extending another class then it will implicitly extend Object class. This is taken care of by the JVM. This is not applicable for the interfaces. A Java interface does not extends the Object.
Following could be the reasons for this design decision,
  • By having the Object as the super class of all Java classes, without knowing the type we can pass around objects using the Object declaration.
  • Before generics was introduced, imagine the state of heterogeneous Java collections. A collection class like ArrayList allows to store any type of classes. It was made possible only by Object class hierarchy.
  • The other reason would be to bring a common blueprint for all classes and have some list of functions same among them. I am referring to methods likehashCode(), clone(), toString() and methods for threading which is defined in Object class.
This concept cannot be generalized to all object oriented programming (OOPS) languages. For instance, in C++ there is no such super class of all classes.

Super class of String, Object, Class

Following program shows
  1. the super class of String class.
  2. the super class of Object class
  3. the super class of Class class
package com.javapapers.java;

public class SuperClass {

 public static void main(String... args) {
  String str = new String("Hi");
  Class strClass = str.getClass();
  System.out
    .println("Super class of String: " + strClass.getSuperclass());

  Object obj = new Object();
  Class objClass = obj.getClass();
  System.out
    .println("Super class of Object: " + objClass.getSuperclass());

  Class classClass = objClass.getClass();
  System.out.println("Super class of Class: "
    + classClass.getSuperclass());
 }
}

Output

Super class of String: class java.lang.Object
Super class of Object: null
Super class of Class: class java.lang.Object