Thursday, 27 February 2014

Creating tabs in liferay portlet:-
basic steps:-
1) Create a liferay prject
2) Add  the following jar files in liferay-plugin-packages.properties :-

  1. Jstl-api.jar and 
  2. jstl-impl.jar files, and 
  3. add c.tld file

3) In your Project ,create the following files under the following path
/docroot/jsps by creating a new folder called jsps

view.jsp
sunday.jsp
monday.jsp
tuesday.jsp
admin.jsp

4)code for view.jsp

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@page import="com.liferay.portal.kernel.util.ParamUtil" %>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<liferay-theme:defineObjects />


<liferay-portlet:renderURL var="portletURL"/>

<%

String tabValue = ParamUtil.getString(request, "tab", "sunday");
String tabsURL = "/jsps/" + tabValue.trim() + ".jsp";
String tabNames="Sunday,Monday,Tuesday" ;
String tabVal="sunday,monday,tuesday" ;
if(permissionChecker.isCompanyAdmin(themeDisplay.getCompanyId())){
tabNames+=",admin" ;
tabVal+=",admin" ;
}
%>

<liferay-ui:tabs
names="<%=tabNames%>"
tabsValues="<%=tabVal%>"
param="tab"
url="<%= portletURL %>"
/>

<c:import url="<%= tabsURL %>"></c:import>

Screen Shot...


Friday, 14 February 2014

process Vs Thread


  1. A process is a collection of virtual memory space, code, data, and system resources. And
  2. A thread is code that is to be serially executed within a process. 

                A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread.

Synchronization is for threads only it won't work for processes in Java. There is no utility in them working across processes, since the processes do not share any state that would need to be synchronized. A variable in one process will not have the same data as a variable in the other process


differences between threads and processes:
1. Threads are easier to create than processes since they don't require a separate address space.

2. difference between a thread and a process is that threads within the same process share the same address space, whereas different processes do not.i.e.Processes are independent of each other.  Threads, since they share the same address space are interdependent, so caution ust be taken so that different threads don't step on each other.

3.  A process can consist of multiple threads.


In Short Description :-
Process:
An instance of a program;
Executed in own address space
Independent entity to which system assigns resources  CPU time, memory Cannot access variables or other data structure in another process Process communicate using inter-process mechanisms like files, pipes, sockets

Thread
Is a particular execution path thru a process.
Multiple threads can share state info of a single process.
Thread share memory and system resources.
Can communicate thru shared variables and other memory structures
Context switching is faster than process.



Thread life cycle in java

Thread can have one of the following state at a time:
  1. New
  2. Runnable
  3. Running
  4. Waiting / Blocking
  5. Dead

Transition between thread states

Following image represents the thread trasition from one state to other:

Thread state : New

  • This is the state the thread is in after the Thread instance has been created, but the start() method has not been invoked on the thread.
  • It is a live Thread object, but not yet a thread of execution. At this point, the thread is considered not alive.
  • For example,
Thread myThread = new Thread(); // currently thread is in New state only

Thread state : Runnable

  • This is the state a thread is in when it's eligible to run, but the scheduler has not selected it to be the running thread.
  • A thread first enters the runnable state when the start() method is invoked, but a thread can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state.
  • When the thread is in the runnable state, it is considered alive.
  • For example,
myThread.start(); // after invokation of this line myThread is now in Runnable state

Thread state : Running

  • This is it. The "big time." Where the action is. This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process.
  • A thread can transition out of a running state for several reasons, including because "the thread scheduler felt like it." 
  • As per shown in above figure, There are several ways to get to the runnable state, but only one way to get to the running state: the scheduler chooses a thread from the runnable pool.

Thread state : Waiting or Blocking

  • This is the state a thread is in when it's not eligible to run.
  • So this is really three states combined into one, but they all have one thing in common: the thread is still alive, but is currently not eligible to run.
  • In other words, it is not runnable, but it might return to a runnable state later if a particular event occurs.
  • A thread may be blocked waiting for a resource (like I/O or an object's lock), in which case the event that sends it back to runnable is the availability of the resource.
  • For example, if data comes in through the input stream the thread code is reading from, or if the object's lock suddenly becomes available. A thread may be sleeping because the thread's run code tells it to sleep for some period of time, in which case the event that sends it back to runnable is that it wakes up because its sleep time has expired.
  • Or the thread may be waiting, because the thread's run code causes it to wait, in which case the event that sends it back to runnable is that another thread sends a notification that it may no longer be necessary for the thread to wait. The important point is that one thread does not tell another thread to block.
  • Some methods may look like they tell another thread to block, but they don't. If you have a reference t to another thread, you can write something like this:
 myThread.sleep();   or     myThread.yield();
  • But those are actually static methods of the Thread class—they don't affect the instance myThread; instead they are defined to always affect the thread that's currently executing.
  • There is a method, suspend(), in the Thread class, that lets one thread tell another to suspend, but the suspend() method has been deprecated.
  • There is also a stop() method, but it too has been deprecated and we won't even go there.
  • Both suspend() and stop() turned out to be very dangerous, so you shouldn't use them and again, because they're deprecated.
  • Note also that a thread in a blocked state is still considered to be alive.

Thread state : Dead

  • A thread is considered dead when its run() method completes.
  • It may still be a viable Thread object, but it is no longer a separate thread of execution.
  • Once a thread is dead, it can never be brought back to life!
  • If you invoke start() on a dead Thread instance, you'll get a runtime (not compiler) exception. And it probably doesn't take a rocket scientist to tell you that if a thread is dead, it is no longer considered to be alive.

Thursday, 13 February 2014

Method In Object class

 o  getClass
 public final native Class getClass()
Returns the runtime class of an object.
Returns:
the object of type Class that represents the runtime class of the object.

 o  hashCode
 public native int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
The general contract of hashCode is:


  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer. This integer need not remain consistent from one execution of an application to another execution of the same application.
  2. If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.

Returns:
a hash code value for this object.

 o  equals
 public boolean equals(Object obj)
Compares two Objects for equality.
The equals method implements an equivalence relation:


  1. It is reflexive: for any reference value x, x.equals(x) should return true.
  2. It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  3. It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  4. It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false.
  5. For any reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

Returns:
true if this object is the same as the obj argument; false otherwise.

 o  clone
 protected native Object clone() throws CloneNotSupportedException
Creates a new object of the same class as this object. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. No constructor is called.
The clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface.
Returns:
a clone of this instance.
Throws: CloneNotSupportedException
if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.
Throws: OutOfMemoryError
if there is not enough memory.

 o  toString
 public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommendedthat all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.
Returns:
a string representation of the object.

 o  notify
 public final native void notify()
Wakes up a single thread that is waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:


  1. By executing a synchronized instance method of that object.
  2. By executing the body of a synchronized statement that synchronizes on the object.
  3. For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws: IllegalMonitorStateException
if the current thread is not the owner of this object's monitor.

 o  notifyAll
 public final native void notifyAll()
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws: IllegalMonitorStateException
if the current thread is not the owner of this object's monitor.

 o  wait
 public final native void wait(long timeout) throws InterruptedException
Waits to be notified by another thread of a change in this object.
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
The timeout period, specified by the timeout argument in milliseconds, has elapsed.
The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters:
timeout - the maximum time to wait in milliseconds.
Throws: IllegalArgumentException
if the value of timeout is negative.
Throws: IllegalMonitorStateException
if the current thread is not the owner of the object's monitor.
Throws: InterruptedException
if another thread has interrupted this thread.

 o  wait
 public final void wait(long timeout,
                        int nanos) throws InterruptedException
Waits to be notified by another thread of a change in this object.
This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up.

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.
The thread then waits until it can re-obtain ownership of the monitor and resumes execution

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters:
timeout - the maximum time to wait in milliseconds.
nano - additional time, in nanoseconds range 0-999999.
Throws: IllegalArgumentException
if the value of timeout is negative or the value of nanos is not in the range 0-999999.
Throws: IllegalMonitorStateException
if the current thread is not the owner of this object's monitor.
Throws: InterruptedException
if another thread has interrupted this thread.

 o  wait
 public final void wait() throws InterruptedException
Waits to be notified by another thread of a change in this object.
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws: IllegalMonitorStateException
if the current thread is not the owner of the object's monitor.
Throws: InterruptedException
if another thread has interrupted this thread.

 o  finalize
 protected void finalize() throws Throwable
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

The finalize method in Object does nothing.

Throws: Throwable

Abstract Class Vs Interface

1) Abstract classes are used for Modelling a class hierarchy of similar looking classes
For example :- Animal can be abstract class and Human , Lion, Tiger can be concrete derived classes.

Interface is used for Communication between 2 similar / non similar classes which does not care about type of the class implementing Interface
For example:- Height can be interface property and it can be implemented by Human , Building , Tree. It does not matter they are living things or not.it matters only a thing that you need to have Height (implementation in you class).


2) By implementing interfaces you are achieving composition ("has-a" relationships) where as by abstract class you are achieving inheritance ("is-a" relationships).

3) methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. i.e.abstract class may contain both abstract and concrete methods but You can not declare any concrete methods inside interface.

4) Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.

5) Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.

6) Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.

7) A Java class can implement multiple interfaces but it can extend only one abstract class.

Which should you use, abstract classes or interfaces?

Consider using abstract classes if any of these statements apply to your situation


  1. You want to share code among several closely related classes.
  2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  3. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.


Consider using interfaces if any of these statements apply to your situation:


  1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  2. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  3. You want to take advantage of multiple inheritance of type.

Wednesday, 12 February 2014

Java 8 new features :
Lambda expressions , optional class , Defender methods with examples

In JavaOne 2013 , Oracle  reveals the details about the Java 8 .  Java 8 is the upcoming version of java from Oracle . It is the most feature rich update then the previous version 6 and 7 , which both were somehow minor updates .

The major features of the java 8 are as follows :

 Introduction of Optional
 Defender Methods
 Lambda Expressions


1. Introduction Of Optional :

The main benefit of Optional is to Avoid null pointer exception : There is another class named Optional in the util package , as it is used to avoid the null pointer exception , If the value is present then it will return the true value otherwise it will show the false value  As it is boolean the value must be between false and true .


In java language , to access an object we use reference type .And when we are unable  to have a specific object to point to , then we set the value of the reference null , indicating it is not pointing to any object .
Null is a literal (also known as constant ) in java .

public static Cat  find(String name, List;Cat; cats) {
   for(Cat cat : cats) {
      if(cat.getName().equals(name)) {
         return cat;
      }
   }
   return null;
}

Method signature shows that  this method may not return a value but a null reference .





Cat;Cat; cats = asList(new Cat("lion"),
                            new Cat("snow leopard"),
                            new Cat("tiger"));

Cat found = find("mountain lion", cats);
//some code in between and much later on (or possibly somewhere else)...
String name = found.getName(); //uh oh!


2. Defender Methods :

Till java 7 , every interface only has method declaration and no implementations  , and any non abstract class which implements the  interface has to implement every method in interface

public interface MyInterface  {
   public void doAnyWork();
}

class MyInterfaceImpl  implements   MyInterface {
  @Override
 public  void doAnyWork(){
 System.out.println("Do Any work in the class " );
}

public static void main (String args[])
 MyInterfaceImpl  myobject= new MyInterfaceImpl();
 myobject.doAnyWork();
 }
}

Now suppose if i add some method doMoreWork()  abstract method in MyInterface  interface , then , if we try to compile the code , we will get compiler error

$javac .\MyInterface.java .\MyInterface.java:18: error: MyInterfaceImpl is not abstract and does not override abstract method doMoreWork() in MyInterface
class MyInterfaceImpl implements MyInterface{
^ 1 error


 And this limitation makes the situation almost impossible to change the interface or APIs . To overcome this challenge  , java 8 introduces default method also known as defender method .



public interface MyInterface  {
   public void doAnyWork();
// A default  method in the interface  created using "default"  keyword

   default public void doMoreWork(){
    System.out.println ("Do More Work implementation in the interface ") ;
  }
}

class MyInterfaceImpl  implements   MyInterface {
  @Override
 public  void doAnyWork(){
 System.out.println("Do Any work implementation in the class " );
}
/*
 * Not required to override to provide an implementation
 * for doMoreWork
 */
public static void main (String args[])
 MyInterfaceImpl  myobject= new MyInterfaceImpl();
 myobject.doAnyWork();
 myobject.doMoreWork();
 }
}

And the output of the code will be : Do Any Work implementation in the class Do More Work implementation in the interface


  3. Lambda Expressions :

Lambda -> (also called Closures), is an expression that reduces vertical boilerplate code.
•Concise and Clear code development practice

•Interfaces that consist of one more than abstract method, cannot be counterpart of any Lambda expressions.


Enum in Java 

Enum (Java keyword) feature which is used to represent fixed number of well known values in Java. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically.

Java Enum Concepts

1) Enum in Java are not integer constant, they are classes, similar to any interface or class. Because of this reason Enum in Java provides type-safety and compile time checking which was not possible with enum int pattern.

2) Every Enum in Java extends from java.lang.Enum implicitly and because of this Enum can not extend any other class in Java.

3) Enum in Java doesn't have public constructor. This means you can not create additional instance of Enum instances other than what is created from Enum class itself and available at compile time. Enum can have private constructor though.

4) Enum values or Enum instances are public, static and final in Java. They are compile time constant, which means you can not changes values of Enum instances and further assignment will result in compile time error.

5) Enum in Java can implement interface and override methods. In fact Java Enum implements Comparable interface and override compareTo() method.

6) Enum instance in Java can be compared using == equality operator or equals() method in Java. Enum provide high quality implement for equals() and hashCode and can be used in Set and Map. But for performance reason its best to use EnumMap and EnumSet while storing enum in Collection.

7) When you compare different instances of same Enum type, they are compared in the order on which they are declared in Enum. You can get this order by calling ordinal() method of Enum.

8) Enum provides implicit method like values(), ordinal() and name() which can be used to get all Enum instances as array, order of enum as declared in class and String name of Enum instances in Java.

9) Enum values() method can be used to iterate over enum. It return an array which can be traverse using for-each loop.

10) You can declare methods in Java Enum and you can even override and overload them.


How to represent enumerable value without Java enum

I use public static final constant to replicate enum like behavior.

Let’s see an Enum example in Java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

public class CurrencyDenom {
   public static final int PENNY = 1;
   public static final int NICKLE = 5;
   public static final int DIME = 10;
   public static final int QUARTER = 25;
}

public class Currency {
   private int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                         // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can server our purpose it has some serious limitations:

 1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

 2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.


What is Enum in Java

Now back to primary questions “What is Enum in java” simple answer Enum is a keyword in java and on more detail term Java Enum is type like class and interface and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you can not change there value once created. Enum in Java provides type-safety and can be used inside switch statment like int variables. Since enum is a keyword you can not use as variable name and since its only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.

Benefits of Enums in Java:

1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is compiler error to assign something else unlike the public static final variables used in Enum int pattern and Enum String pattern.

2) Enum has its own name-space.

3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.


Important points about Enum in Java

1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error


2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.


3) You can specify values of enum constants at the creation time as shown in below example:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
 
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
};
Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.


4) Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be re assigned.



5) Enum in java can be used as an argument on switch statment and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:

   Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;
            case DIME:
                    System.out.println("Dime coin");
                    break;
            case QUARTER:
                    System.out.println("Quarter coin");
    }

from JDK 7 onwards you can also String in Switch case in Java code.

6) Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator as shown in following example of  Java Enum:

Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
  System.out.println("enum in java can be compared using ==");
}

By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

7) Java compiler automatically generates static values() method for every enum in java. Values() method returns array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum  in Java as shown in below example:

for(Currency coin: Currency.values()){
        System.out.println("coin: " + coin);
}

And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTER
             
Notice the order its exactly same with defined order in enums.



8) In Java Enum can override methods also. Let’s see an example of overriding toString() method inside Enum in Java to provide meaningful description for enums constants.

public enum Currency {
  ........
   
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         case NICKLE:
              System.out.println("Nickle: " + value);
              break;
         case DIME:
              System.out.println("Dime: " + value);
              break;
         case QUARTER:
              System.out.println("Quarter: " + value);
        }
  return super.toString();
 }
};      
And here is how it looks like when displayed:
Currency usCoin = Currency.DIME;
System.out.println(usCoin);

output:
Dime: 10


   
9) Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum. These classes are high performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.



10) You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.


11) Instance of Enum in Java is created when any Enum constants are first called or referenced in code.


12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface. Let's see and example of how to implement interface using Java Enum:

public enum Currency implements Runnable{
  PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
  private int value;
  ............
     
  @Override
  public void run() {
  System.out.println("Enum in Java implement interfaces");
             
   }
}



13) You can define abstract methods inside Enum in Java and can also provide different implementation for different instances of enum in java.  Let’s see an example of using abstract method inside enum in java

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
     
          private Currency(int value) {
                  this.value = value;
          }
          ..............
  }    
In this example since every coin will have different color we made the color() method abstract and let each instance of Enum to define   there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:

System.out.println("Color: " + Currency.DIME.color());


Enum Java valueOf example
One of my reader pointed out that I have not mention about valueOf method of enum in Java, which is used to convert String to enum in java.  Here is what he has suggested, thanks @ Anonymous
“You could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. Enum valueOf() is a static method which takes a string argument and can be used to convert a String into enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.

Another of my reader suggested about ordinal() and name() utility method of java enum Ordinal method of Java Enum returns position of a Enum constant as they declared in enum while name()of Enum returns the exact string which is used to create that particular Enum constant.” name() method can also be used for converting Enum to String in Java.