Monday, 20 May 2013

Stack Based Execution and Exception Propagation

Exceptions in Java signal the occurrence of some unexpected error situation during execution. The exception handling mechanism is built around throw-catch paradigm. To throw an exception is to signal that an unexpected condition has occurred. To catch an exception is to take appropriate action to deal with the exception.

Several threads are executing in the JVM. Each thread has its own run time stack that is used to handle the execution of methods. Each element on the stack is called the activation record corresponds to a method call. The method with the activation record on the top of the stack is the one currently executing. When this method finishes execution, its record popped from the stack. The methods on the stack are said to be active as their execution has not completed. At any given time the active methods on the run time stack comprise what is called the stack trace of the thread's execution.

If the exception is not caught by any active methods, it is dealt with the main threads default exception handler. The default exception handler usually prints the name of the exception with an explanatory message followed by a printout of the stack trace at the time the exception was thrown. Remember, if an exception is thrown while evaluating the left hand side operand of a binary expression then the right hand operand will not be evaluated.

Saturday, 11 May 2013

Comparable Vs Comparator

Comparable interface contains a method called compareTo(Obj) which takes only one argument and it compares itself with another instance or objects of the same class.

Comparator interface contains a method called compare(Obj1, Obj2) which takes two arguments and it compares the value of two objects from the same or different classes.
Number of times I read this definition but this time I wrote a small program to understand how can I implement these two interfaces. Lets take comparable first.
In this example I have sorted the list of employees according to their names.

// Employee Class - Implements Comparable
public class Employee implements Comparable<Employee>
{
 private int empId;
 private String name;
 private int age;
 public Employee(int empId, String name, int age)
 {
  this.empId = empId;
  this.name = name;
  this.age = age;
 }
compareTo method takes second object and compare it with the first object(this here). Returns 1,0,-1 based on comparison if value is greater, equals and smaller respectively and swap  the values if necessary.Doing (this - o) will sort in ascending order and reverse will sort in descending order.
  public int compareTo(Employee o)
  {
  return this.name.compareTo(o.name);
  }
  public int getAge()
  {
   return this.age;
  }
  public int getEmpId()
  {
   return this.empId;
  }
  public String getName()
  {
   return this.name;
  }
}

// Another Class Util - Contains a list of employees

public class Util
{
 public static List<Employee> getEmployees()
 {
  List<Employee> col = new ArrayList<Employee>();

  col.add(new Employee(1, "Ankit", 25));
  col.add(new Employee(2, "Vijay", 82));
  col.add(new Employee(3, "Deepak", 30));
  col.add(new Employee(4, "Ajay", 12));
  col.add(new Employee(5, "Seema", 23));
  return col;
 }
}

// Another class TestEmployeeSort

public class TestEmployeeSort
{
 public static void main(String[] args)
 {
  List coll = Util.getEmployees();
  Collections.sort(coll); // sort method
  printList(coll);
 }

 private static void printList(List<Employee> list)
 {
  System.out.println("EmpId\tName\tAge");
  for (Employee e : list)
  {
   System.out.println(e.getEmpId() + "\t" + e.getName() + "\t"
     + e.getAge());
  }
 }
}

Lets do this by using Comparator

// Class Employee and Util will remain the same but this time Employee class will not implement the comparable interface. 

// Create a class SortByName - implements Comparator Interface

public class SortByName implements Comparator<Employee>
{
 public int compare(Employee o1, Employee o2)
 {
  return o1.getName().compareTo(o2.getName());
 }
}

Now there is a slight change in TestEmployeeSort class which is highlighted below:

public static void main(String[] args)
{
 List coll = Util.getEmployees();
 Collections.sort(coll, new SortByName()); // sort method
 printList(coll);
}

private static void printList(List<Employee> list)
{
 System.out.println("EmpId\tName\tAge");
 for (Employee e : list)
 {
  System.out.println(e.getEmpId() + "\t" + e.getName() + "\t"
    + e.getAge());
 }
}
        
The output for both the programs will be same i.e.
EmpId Name       Age
4         Ajay        12
1         Ankit        25
3         Deepak        30
5         Seema        23
2         Vijay        82

Key Points to be noted:

1. Collections.sort(coll) - Here sort is a static method of class Collections.
    public static <T extends Comparable<? super T>> void sort(List<T> list)
   Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface

2. Collections.sort(coll, new SortByName()) - This is again a static method of class Collections.
     public static <T> void sort(List<T> list, Comparator<? super T> c)
     Sorts the specified list according to the order induced by the specified comparator. 

3. Here return obj1.compareTo(obj1) or return obj1.compareTo(obj) statement only take    Object, primitive is not allowed. 

Thursday, 2 May 2013

Enums (Enumeration) in Java

Enums, whenever I come across this term, I don't know the practical use and power of  Enums. I have tried explaining it in this post. 

Definition - Finite set of symbolic names and their values. These symbolic names are called as enum constants. 
In more technical way, An enum is used as any other reference type. Enum constants are infact final, static variables of the enum type and they are implicitly initialized with objects of the enum type when the enum type is loaded at the run time. 

I know it went over your head, same happened to me when I first read above lines. Below mentioned statement will describe it.

enum test {A, B,C}
public static final A = new test()

About the use of enums:

1. We can pass enum constants as an arguments.
2. We can declare reference whose type is an enum type.
3. We cannot pass a type of value other than the enum type.
4. We cannot create a new constant of enum type.

Lets take an example which will cover these points


// File name - MachineState.java

public enum MachineState  {BUSY, IDLE, BLOCKED}

// File name - Machine.java

public class Machine
{
     private MachineState state; // 2nd Point Justified
     public void setState(MachineState state)
     {
      this.state = state;
  }
  public MachineState getState()
  {
   return this.state;
  }
}

public class MachineClient
{
 public static void main(String args[])
 {
  Machine machine = new Machine();
  machine.setState(MachineState.IDLE); //1st Point Justified
  // machine.setState(1); compile time error // 3rd Point Justified
  MachineState state = machine.getState();
  system.out.println(state);
  //MachineState newState = new MachineState(); compile time error // 4th Point Justified
 }
}

Declaring Enum constructors and Members:

An Enum declaration is a special kind of reference type declaration. It can declare constructors and other members as in an ordinary class but the enum constants must be declared before any other declarations. Lets take an example:

enum abc
{
 HI("hi"), BYE("bye");
 abc(String s)
 {
  this.wish = s;
 }
 private String wish;
 public String getWish()
 {
  return wish;
 }
 public void setWish(String wish)
 {
  this.wish = wish;
 }
 public class Greet
 {
  public static void main(String args[])
  {
   String e;
   e = abc.Bye.getWish();
   system.out.println(e);
  }
 }
} 

Implicit Static methods for Enum Types:

1. Static EnumTypeName[] values()
e.g. abc a[] = abc.values(); --> HI , BYE

2. Static EnumTypeName valueOf(String name)
e.g. abc o = abc.valueOf("HI")  --> hi

Enum as a Map:

Making enum a reference type that can contain fixed set of constants has led to efficient Map implementation like EnumMap and Set implementation like EnumSet (JDK classes).
From javadoc of EnumMap :
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.
EnumMap combines richness and type safety of Map with the speed of an array.
Having said that, I tried to solve a problem using enums instead of Map. Problem was  - Print a number in word say if user inputs a number we have to display that in word. Below mentioned is the solution:


public class example
{
 public static void main(String args[])
 {
  String convertDigitToWord = word.lookup(5);
  System.out.println(convertDigitToWord);
 }

 public enum word
 {
  ZERO(0,"ZERO"),
  ONE(1,"ONE"),
  TWO(2,"TWO"),
  THREE(3,"THREE"),
  FOUR(4,"FOUR"),
  FIVE(5,"FIVE");

  private int digit;
  private String digitWord;

  word(int digit, String digitWord)
  {
   this.digit = digit;
   this.digitWord = digitWord;
  }

  public static String lookup(int digit)
  {
   for(word w : word.values())
   {
    if(w.getDigit() == digit)
    { 
     return w.getDigitWord();
    }
   }
   return null;
  }
  public int getDigit()
  {
   return digit;
  }
  public void setDigit(int digit)
  {
   this.digit = digit;
  }
  public String getDigitWord()
  {
   return digitWord;
  }
  public void setDigitWord(String digitWord)
  {
   this.digitWord = digitWord;
  }
 }
} 

I hope this will help you to understand enums easily. Requesting vistors to share their knowledge about enums so that I can include that also in this post. Good Luck and happy learning !!