Sunday, June 02, 2013

Java Basics: Enum Types

JDK 1.5 a.k.a Tiger release marked the addition of two new reference types into the language. A special Kind Class called Enum Types and a new kind of interface called an annotation Types.
In this blog post we will discuss about the Enum Types and how it is better than the existing approach int and String Enum pattern that many of us used or may still be using in (pity on programmers as they are missing out better approach to handle things and making the project fragile in long run) there projects.

Note: Enum has been made a reserved keyword in 1.5 migrating your existing project on JDK 1.5 might break your existing code if anywhere you have used enum as a variable name.

An Enum allows a programmer to define fixed set of named constants such as the planets in the Solar System, Suits in the deck of playing cards or Days in a Week.

Points to Remember:

1. Enum Types over a period of time can evolve into a full-fledged abstraction.
2. Enum Types are by nature immutable, so all fields should be marked final they can be public but it’s better to make them private and provide them public accessors. 
3. Before Enum Types a common int and String Enum pattern was used by the programmer which has many shortcomings.

Before JDK 1.5 – Existing int Enum Pattern

public static final int Day_SUNDAY  = 0;
public static final int Day_MONDAY = 1;
public static final int Day_TUESDAY = 2;
…..

 Shortcomings in above approach:

     No Type Safety: Your compiler without warning you will compile even if you pass any int value instead of the predefined set of values.

       No Namespace: You must prefix constants (in this case Day_) to avoid any confusion/collisions in case you introduce a new pattern in your project in future.

      Fragile: As int Enum pattern are compile-time constants, they are compiled in the files those uses them. It requires recompilation of all those files that uses them if any changes made to them else it will result in unexpected behavior.

      Uninformative: These patterns won’t allow you to carry any addition details printing them will not tell you more than what value each of them are assigned even the type is not known whether it’s a int or a String. Even the iteration over all the declared values is not possible and there is no way to find out the exact no. of declared constants.

Enum Types not only overcomes the above mentioned shortcomings in the existing approach but adds much more functionality that one can expect from it. Many programmers are aware of Enum Types even before they were introduced in JDK 1.5 due to its presence in languages like C/C++. They look similar to their counterparts in other languages (i.e., in C/C++ or C#) where they are just fancy int values whereas Java Enum Types are Real Java Classes and are much more powerful thanks to the Compiler which makes it possible under the hoods with no burden on programmers.

Enum in its Simplest Form:

enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

Enum Types are final by virtue, having no accessible Constructor and hence are purely instance-controlled. Enum Types cannot be extended, and an Enum Type cannot extend other class or enum as all Enum Types are subclasses of java.lang.Enum maintaining the single level inheritance but all Enum Types can implement interfaces.

Enum Types can either defined as Top-Level full-fledged class or it can be nested static member in another reference types.

Enum Provides Type Safety: You can assign an Enum one of the defined constant otherwise Complier Error is thrown.

Comparison: Comparing Enum Types using == or equals() will be same.

Informative: Each Enum Constant can override if required the toString() to provide any information they want.

Namespaces: Constants with same name can exist as all constants can be accessed using the Enum name which cannot be same.

No Need to Recompile: As Enum Types are not compiled into the classes which use them, so we can add/remove or reorder any enum constant without compiling all the files that uses it.

You can define fields or methods in an Enum Types as you do in a Regular Java Class.
With Enum Types the order in which you define the fixed set of named constants matter a lot.
Java.lang.Enum overrides methods from Object class and made a few of them final and it also implements interfaces like Comparable and Serializable that handles Comparison and Serialization for you automatically.

Enum can be a Top-Level Class or if it’s defined inside a Top-Level Class then it acts as a static member class of that Top-Level Class.

Inside an Enum Type you can declare an abstract method in that case we have to @Override the abstract method with a concrete one for each named constant using Constant-Specific Class Body. Such methods are known as Constant-Specific Method Implementations.

The toString() method in its default form will return the Constant Name which is same as calling the name() method but as toString() method is not final it can be Overridden either for whole Enum in which case every Constant will share the same value or it can be Overridden for a few if not all as well that way an Enum Types achieves Polymorphism like any Regular Java Class.

Iteration and Size of Enum can be known using the values() method. The values() method return an Array which you can use to iterate and using the length variable its size can be easily known.

As mentioned before Order in which the Constants are defined is very important as whenever the constants are iterated it can be iterated in the order it’s defined in the Enum.
ordinal() method returns an integer indicating the index at which the constant is placed.



I will update this post with more information and examples. EnumSet and EnumMap later. 

Hope this Helps!
Please leave your comments.

Saturday, June 01, 2013

Groovy Basics: Hello World Example

In Dynamic Language, always remember one Rule of Thumb.

* When you're unsure what type you want your Object, always use the 'dynamically typed' keyword.

In Groovy, def simply means 'dynamically typed'.

As the Groovy Site says a dynamic language for the VM you must always remember Groovy Syntax feels Dynamic whereas once it's compiled it's the same Class File that Java Compiler (javac) Generates as Groovy runs on the VM and VM doesn't have a support for dynamic language. You will find Groovy Syntax Much Clear and More Readable as you write less code.

A Groovy File can either Contain Scripts, Class Definition or both. I usually don't prefer mixing Scripts and Class Definitions in a same file. I will come to this later.

You can check one-liner on the Groovy Shell instead of writing a Script file.

On Console/Prompt Type:

groovysh // It will open a Groovy Shell.

groovy:000> println "Hello, World."
Hello, World.
===> null
groovy:000>

OR Simply,

groovy:000> "Hello, World."
===> Hello, World.
groovy:000>

You will see the shell doesn't exit after the execution instead it's asking for your input again. This is called REPL - Read Evaluate Print Loop. You can type exit, quit, \q or \x to exit the shell.

You can also use the groovy command instead of going into the shell.

groovy -e "println 'Hello, World.'"

Here, -e <script> specify a command line script.

You can write that line in a new file and save it as HelloWorldScript.groovy try to run it,

groovy HelloWorldScript.groovy

OR

groovy HelloWorldScript

A Groovy File can have any of the below mentioned extension. You can run the groovy command without extension in which case groovy will look for all the files in your CLASSPATH with one of the below mentioned extention and .class extention as well once it's found, it will execute that or will throw an error in case file with the same name doesn't exist in the CLASSPATH.

.groovy
.gvy
.gy
.gsh

The groovy command runs your code without generating .class files. If you use groovyc compiler to explicitly compile your files first and then run them using the groovy command. You can do it. What if you made changes to your groovy source file and forgot to compile them? What will happen? No Worries! The groovy command is smart enough to load and run the right files for you that means suppose you make any changes to your source file but forgot to generate the .class file using the groovyc command (groovyc). the groovy command will ignore the .class file present in the path and will run the source file instead.

Now, Lets write a first HelloWorld.groovy program using the class definition,

You might notice that there are no import statements, parentheses, package prefix or a semi-colon.
Point to Remember: Like Java imports java.lang.* package by default Groovy imports the following packages by default. groovy.lang.*, groovy.util.*, java.lang.*, java.util.*, java.net.*, java.io.* and classes java.math.BigInteger and java.math.BigDecimal.

Another Point to remember here that Script files don't have a main method but they are still executed, As Each Script file turned into a Java class with the same name as filename that extends the groovy.lang.Script which contains the main method so the runtime can execute it.

As, I discussed earlier not to mix Scripts and Class Definitions in a Single file. Here is why,

Let me explain if the above error is still not clear. What Groovy does here is when it sees a Script inside a source file, it tries to create a class with the same name as source filename which in this case is HelloWorld. Their is a class definition inside the source file which has a same name i.e., HelloWorld for which a class will be created but when it comes to the Script it will fail to create as the class HelloWorld already exist.

How to fix?

You can fix this either by changing the Source Filename or Change the Class Name to make it run. Always try not to mix the Class Definition and Script in a same file.

As, I mentioned above that you need a Java VM to run the Groovy code you can run them directly using the Java Command. All you require is a single Groovy Jar in your classpath.

Compile and Run

First you have to generate a .class file using the Groovy Compiler.

Window Users:

C:\GROOVY-DEMOS>groovyc HelloWorld.groovy

Linux Users:

$ groovyc HelloWorld.groovy

To Run,

Window Users:

C:\GROOVY-DEMOS>java -classpath %CLASSPATH%;%GROOVY_HOME%\embeddable\groovy-all-2.1.3.jar HelloWorld

Linux Users:

$ java -classpath %CLASSPATH%:%GROOVY_HOME%/embeddable/groovy-all-2.1.3.jar HelloWorld


Note: Never put the groovy-all-<VERSION>.jar in your classpath, it will effect the groovysh command. If you get an error while running the groovysh command make sure you don't have groovy-all-<VERSION>.jar in your classpath.

If you are looking for editors/IDE with Groovy Support try Sublime Text 2 or IntelliJ Idea.

Hope this Helps!
Please leave your comments

Running Java And Groovy on Windows And Linux

Groovy, Another Language that runs on Java Virtual Machine. It supports both Static and Dynamic Typing. If you haven't heard about this language till now. No Problems!

As, Groovy runs on VM so you must install Java first. Groovy doesn't require you to be a Java Programmer but some hands-on will help you learn it fast. Those who already have installed Java must set the JAVA_HOME Environment Variable. Here is how you do.

On Windows Machine:

Right-Click My Computer -> Properties -> In Windows XP (Advanced) | In Windows 7 (Advanced System Settings) ->  Environment Variable -> New

Here You will see Two Panes. If you select the New on the First One it will set User-Specific Setting i.e., Only the Currently Logged In User can use Java and Groovy.

If you Choose the New from the System Variables, It will be available to all the existing users as well all users that you create later. Choose what you prefer.

Note: System Variables already Contains PATH Key/value pair. Never remove the existing value instead append to it or you end you with an unstable machine. If you are unsure always create the NEW PATH Key/value in the First Pane that way you are sure that your System Settings remains untouched.

Create a New Variable anywhere you prefer.

Variable Name:  JAVA_HOME
Variable Value:  PATH\TO\JAVA\FOLDER\WITHOUT\SEMI-COLON\AT\THE\END

For Example: I have installed Java in C:\jdk1.6

Variable Name:  JAVA_HOME
Variable Value:  c:\jdk1.6 \\ Never put a Semi-Colon at the end.

Once Done Press OK.

Now Create one more Environment Variable. Again by Clicking New any place you prefer:

Variable Name:  CLASSPATH
Variable Value:  .;%JAVA_HOME%\lib;

Note: You must put a Semi-Colon at the End. Press OK. The Reason to put a Semi-Colon here is a good practice as you might in near future append a new library to your CLASSPATH just to separate one from another you put a Windows PATH Separator.

Again, If you are unsure which pane to choose for this one always prefer the first one and add the below Key instead of updating your existing System Variable PATH key in global/system settings that way it will remain untouched.

Variable Name:  PATH
Variable Value:  %JAVA_HOME%\bin;

Note: Never Override a Key's Value always append to it.

On Linux Machine:

There is a ~/.bash_profile that is a start-up script which generally runs once. People find it common place to add environment variables such as PATH, JAVA_HOME, create aliases, etc.

Please remember the file ~/.bashrc is similar but ~/.bash_profile runs for Bash Shell whereas, ~/.bashrc runs for every Bash Shell.

Similarly, You can setup for all users i.e., Global Settings to do so you need to add the following entries mentioned below in /etc/profile.

Fire your Terminal or Console: I'm using ~/.bash_profile you can choose what you prefer.

Type: $ vi ~/.bash_profile

export JAVA_HOME=/PATH//TO/JAVA/FOLDER/WITHOUT/COLON/AT/THE/END
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=.:$JAVA_HOME/lib

You have to logout and login back to see the new changes in effect. Alternatively you can type the below command to see the changes immediately.

$ source ~/.bash_profile

OR

$ . ~/.bash_profile

Always Remember always place Binary files i.e., files that are executable in the PATH variable irrespective you are working on Windows or Linux OS. CLASSPATH is for libraries.

Now it's time to download Groovy. Please head over to their Site to download it and all we need is to extract it and add/update some Environment Variables. The same way we did for Java.

Groovy Site: http://groovy.codehaus.org/

You need to Add a New Environment Variable.

Variable Name:  GROOVY_HOME
Variable Value:  PATH//TO/GROOVY/FOLDER/(IN WINDOWS WITHOUT SEMI-COLON OR IN LINUX WITHOUT COLON)/AT/THE/END

Append to PATH Variable,

Windows Users: %GROOVY_HOME%\bin;
Linux Users: $GROOVY_HOME/bin

Make sure that there is a Semi-Colon (Windows), Colon (Linux Users) at the end before you append these values to it. You can confirm this using the echo command which works on both windows and Linux.

Windows Users: echo %PATH%
Linux Users: echo $PATH

If it's not present you must provide it otherwise it will not work. For Example: Instead of doing $GROOVY_HOME/bin
you do :$GROOVY_HOME/bin.

Remember Colon is a Linux Path Separator whereas, Semi-Colon is Windows.

Now As all the installations are done now we head over to test if everything is working fine or not.

Windows Users, Please open Command Prompt close any if already Opened. Linux Users either use the source command to make the settings available to existing Console or login again.

Now, Before we proceed any further we must check our installation.

At prompt or Terminal or Console,

Type:

javac -version // To See if the Java Compiler is Working or not.
java -version // To See if the java execution environment is ready to run anything you throw at it.

groovyc -version // To See if the Groovy Compiler is Working or not.
groovy -version // To See if the Groovy execution environment is ready to run anything you throw at it.

groovysh -version // It's something that only Groovy had not Java. It can execute commands you throw at it. It's a REPL - Read Evaluate Print Loop.

groovyConsole // It's a GUI Version.

I hope you don't ran into any problem. Next Article is coming up on Groovy.

Hope this Helps!
Please leave your comments.

Thursday, April 18, 2013

Howto Use Java Comparator and Comparable by Example

In Java, there are some built-in methods that provides basic sorting of Primitive types array or Wrapper classes but what If we wanted to sort a custom class that we have written for use in one of our Projects? Well the answer is to write a sorting algorithm of our own and use it wherever it's required.

In Java, there are two interfaces that can help us achieve our goal. The reason the language provides two interfaces instead of one giving code developers enough flexibility to choose the one that they find suitable to their requirement.

The first Interface which I prefer to call is the Simple Handy Internal Sorter is available in java.lang.Comparable  . The Second Interface which I prefer to call is the Highly Flexible External Sorter is available in java.util.Comparator.

The former one is Simple and Internal as it needs to be implemented on the class itself and it's simple as it allows the code developers to write only single sorting implementation. The latter one is Highly Flexible and External that means it allows the code developer the flexibility to write as many as required sorting implementation for their custom class as it's declaration and implementation is in a separate class.

Let's start with the Below Example where Custom Class CarMake have both Simple Handy Internal Sorter and Highly Flexible External Sorter.

CarMake.java

As you can see below the Simple Handy Internal Sorter is already implemented on the Custom Class.


CarMakeComparatorAsc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.




CarMakeComparatorDesc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.


And, Finally the only thing required is to test both the implementation using a CarMakeSortTest.java.

CarMakeSortTest.java


I Hope this post helps you learn basics of Custom Class Sorting. Please do write your feedback...

You can download the complete code from Github