Welcome to my blog, hope you enjoy reading
RSS

Thursday 24 January 2013

How To Calculate Exact Values In Java Using Double Vs BigDecimal


How To Calculate Exact Values In Java Using Double Vs BigDecimal

Here is an example to use double to represent the values in Java.

public class ProblemWithDouble {

public static void main(String[] args)
{
                  System.out.println("--- Normal Print-----");
                  System.out.println(2.00 - 1.1);
                  System.out.println(2.00 - 1.2);
                  System.out.println(2.00 - 1.3);
                  System.out.println(2.00 - 1.4);
                  System.out.println(2.00 - 1.5);
                  System.out.println(2.00 - 1.6);
                  System.out.println(2.00 - 1.7);
                  System.out.println(2.00 - 1.8);
                  System.out.println(2.00 - 1.9);
                  System.out.println(2.00 - 2);
}
}

Share

Tuesday 22 January 2013

MySQL- Counting The Total Occurances Of A Regular Expression In A Table Column


MySQL- Counting The Total Occurances Of A Regular Expression In A Table Column

Ok, so here’s the scenerio- you have a table like this in your DB:

Share

MySQL – SELECT Rows Where First Character Is Not A Letter


MySQL – SELECT Rows Where First Character Is Not A Letter

Here are two methods of SELECTING rows where the first character is not a letter. For example, if you have the following data:

Share

MySQL- Remove Duplicate Rows


MySQL- Remove Duplicate Rows

I’ve been working with meduim sized tables (2.1million rows) in MySQL lately. One particular table had a lot of duplicate rows, which I needed to filter out. I’m quickly going to demonstrate how I did it. I’m sure there are many ways of doing this, but this method proved to be the easiest for me.
Share

MySQL – INSERT SELECT Example

MySQL – INSERT SELECT Example

I’m quickly going to demonstrate how to INSERT rows from one table into another table. I’d just like to clarify, this isn’t the same as completely copying a table, because with a INSERT SELECT query you can use the WHERE clause to INSERT rows with a particular condition (e.g. WHERE name = ‘Bill’). Whereas, copying an entire table will copy every single record.
Share

Monday 21 January 2013

HAVING Clause


SQL: HAVING Clause

The SQL HAVING clause is used in combination with the SQL GROUP BY clause. It can be used in an SQL SELECT statement to filter the records that a SQL GROUP BY returns.
The syntax for the SQL HAVING clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n
HAVING condition1 ... condition_n;
aggregate_function can be a function such as SQL SUM function, SQL COUNT function, SQL MIN function, or SQL MAX function.
Share

GROUP BY Clause


SQL: GROUP BY Clause

The SQL GROUP BY clause can be used in an SQL SELECT statement to collect data across multiple records and group the results by one or more columns.
The syntax for the SQL GROUP BY clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n;
aggregate_function can be a function such as SQL SUM function, SQL COUNT function, SQL MIN function, or SQL MAX function.
Share

Top 25 Most Dangerous Software Errors – 2011


Top 25 Most Dangerous Software Errors – 2011

The Common Weakness Enumeration (CWE) is a community developed dictionary for software weaknesses. It provides a unified, measurable set of software weaknesses that is enabling more effective discussion, description, selection, and use of software security tools and services that can find these weaknesses in source code and operational systems as well as better understanding and management of software weaknesses related to architecture and design.
Share

20 Kick-ass programming quotes


20 Kick-ass programming quotes


This post serves as a compilation of great programming quotes, quotes from famous programmers, computer scientists and savvy entrepreneurs of our time. Some of them are funny, some of them are motivational, some of them are… just awesome!
So, in no particular order, let’s see what we have…
Share

5 Implementations of Singleton Pattern


5 Implementations of Singleton Pattern

This article introduces singleton design pattern and its 5 implementation variations (with C#).
Problem
At most one instance of a class must be created in an application.
Solution
That class (singleton) is defined including its own instance, and the constructor must be private.

Share

20 Database Design Best Practices


20 Database Design Best Practices

  1. Use well defined and consistent names for tables and columns (e.g. School, StudentCourse, CourseID …).
  2. Use singular for table names (i.e. use StudentCourse instead of StudentCourses). Table represents a collection of entities, there is no need for plural names.
Share

Saturday 19 January 2013

SQL ORDER BY


SQL ORDER BY

The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending order. Oracle sorts query results in ascending order by default.
Share

Friday 18 January 2013

Export data into CSV and download using Servlet


Export data into CSV and download using Servlet

Share

How To Export Data To CSV File – Java


How To Export Data To CSV File – Java


CSV is stand for Comma-separated values, CSV is a delimited data format that has fields/columns separated by the comma character and records/rows separated by newlines.
Please take a look at a CSV sample,

Share

Java – Factory Design Pattern

Java – Factory Design Pattern

Introduction
Factory pattern is used in the scenerio where the project contains a super class and ‘n’ number of sub-classes, In which the subclass object is created depending on the data provided. This article touches the basics of Factory Design Pattern using some sample codes that contains an abstract class named “Vechicle”, Two sub classes named “Car” and “Bike” and a factory class named “FactoryVechicle”.

Share

Thursday 17 January 2013

GWT Paging Scroll Table

GWT Paging Scroll Table

Introduction

I've been doing a lot of development lately with the Google Web Toolkit. One of the things I clamored for was a decent grid or table that had good performance, sortable columns, and pagination. Surprisingly, there are few options out there (to date), for GWT developers. There are some standard widgets in GWT like FlexTable and Grid, and these widgets work great for small tasks, but they don't support pagination, scrolling, or large data sets. GWT also has a ScrollPanel, but again that lacks pagination and support for large data sets.

Share

Wednesday 16 January 2013

What is the difference between JDK and JRE?


What is the difference between JDK and JRE?

The JRE is the Java RunTime Environment that is a plug-in needed for running java programs. The JRE is an implementation of the Java Virtual Machine which actually executes Java programs.
The JDK is the Java Development Kit for Java application developers. The JDK is bundle of software which contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc. Share

Friday 11 January 2013

Unexpected Quotients


Unexpected Quotients

2/3 = 0
3/2 = 1
1/0 = ArithmeticException
0/0 = ArithmeticException

Share

Java Operators


Java Operators

An operator is a symbol that operates on one or more arguments to produce a result. The Hello World program is so simple it doesn't use any operators, but almost all other programs you write will.

Share

Keywords in java


Keywords

Keywords are identifiers like publicstatic and class that have a special meaning inside Java source code and outside of comments and Strings. Four keywords are used in Hello World, publicstatic,void and class.

Share

The ? : operator in Java


The ? : operator in Java

The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities. In Java you might write

Share

How to make a gzip file and uncompress a file in the gzip format


How to make a gzip file in Java?

To create a GZIP file, you can use GZIPOutputStream class provided by java.util.zip package.
Here is an example,

Share

How to use Java String.split method to split a string by dot


How to use Java String.split method to split a string by dot?

In java, string.split(".") does not work for splitting a string with dot (e.g.,http://javanotes2all.blogspot.in/) and will give you an array with zero element.

Share

Tuesday 8 January 2013

5 difference between Hashtable and HashMap in Java


5 difference between Hashtable and HashMap in Java

Hashtable vs HashMap in Java
Hashtable and HashMap are two
hash based collection in Java and used to store objects as key value pair. Despite beinghash based and similar in functionality there are significant difference between Hashtable and HashMap and without understanding those difference if you use Hashtable in place of HashMap than you may run into series of subtle programs which is hard to find and debug.Unlike Difference between ArrayList and HashMap, Difference between Hashtable and HashMap are more subtle because both are similar kind of collection. Before seeing difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.

Share

Difference between TreeMap and TreeSet in Java


Difference between TreeMap and TreeSet in Java


Difference between TreeSet and TreeMap in Java
Main Difference between TreeMap and TreeSet is that TreeMap is implementation of Map interface while TreeSet is implementation of Set interface. There are some similarities between both TreeMap and TreeSet and few differences as well. In this Java tutorial we will first see similarities between TreeMap and TreeSet and than we will see differences between TreeMap andTreeSet in Java. Key point to remember about TreeMap and TreeSet is that they use compareTo() or compare() method to compare object, So if uses puts a String object in TreeSet of Integers, add() method will throw ClassCastException at runtime prior to Java 5, with Java 5 you can use Generics to avoid this happening by declaring TreeMap and TreeSet with parametrized version.

Share

TreeMap vs HashMap


TreeMap vs HashMap

Both TreeMap & HashMap are two different implementation of the Map interface. Even though this post is titled “TreeMap vs HashMap” I would like to say how they are connected and how much similar they are.
Both TreeMap & HashMap are not synchronized. To make it synchronized we have to explicitly callCollections.synchronizedMap( mapName ) . Both supports “fail-fast” iterators. Both of them doesn’t support duplicate keys.

Share

Difference between yield and wait method in Java


Difference between yield and wait method in Java

Yield vs wait in Java
Yield and wait method in Java, though both are related to Thread, are completely different to each other. Main difference between wait and yield in Java is that wait is used for flow control and inter thread communication while yield is used just to relinquishCPU to offer an opportunity to another thread for running. In this Java tutorial we will what are differences between wait and yieldmethod in Java and when to use wait() and yield(). What is important for a Java programmer is not only understand difference between wait() and yield() method but also know implications using yield method. If your program is depends upon yield method for performance or correctness than its most likely not work perfectly on all platforms because of platform dependent nature of yield method which we will see in this Java article along with wait vs yield comparison.

Difference between wait and yield in Java

Here is a list of differences between Yield and wait method in Java, good to remember for Java interviews :
1) First difference between wait vs yield method is that, wait() is declared in java.lang.Object class while Yield is declared onjava.lang.Thread class.

2) Second difference between wait and yield in Java is that wait is overloaded method and has two version of wait, normal and timed wait while yield is not overloaded.

3) Third difference between wait and yield is that wait is an instance method while yield is an static method and work on current thread.

4) Another difference on wait and yield is that When a Thread call wait it releases the monitor.

5) Fifth difference between yield vs wait which is quite important as well is that wait() method must be called from either synchronized block or synchronized method, There is no such requirement for Yield method.

6) Another Java best practice which differentiate wait and yield is that, its advised to call wait method inside loop but yield is better to be called outside of loop.

That's all on difference between wait and yield method in Java. In summary wait and yield are completely different and there for different purpose. Use wait for inter thread communication while yield is not just reliable enough even for the mentioned task. preferThread.sleep(1) instead of yield.

Share

Difference between HashMap and LinkedHashMap in Java


Difference between HashMap and LinkedHashMap in Java



Difference between LinkedHashMap and HashMap in Java
HashMap and LinkedHashMap are two most common used Map implementation in Java and main difference between HashMap and LinkedHashMap is that LinkedHashMap maintain insertion order of keys, Order in which keys are inserted in to LinkedHashMap. On the other hand HashMap doesn't maintain any order or keys or values. In terms of Performance there is not much difference betweenHashMap and LinkedHashMap but yes LinkedHashMap has more memory foot print than HashMap to maintain doubly LinkedList which it uses to keep track of insertion order of keys.


LinkedHashMap and HashMap in Java - Similarities
There are lot of similarity between
LinkedHashMap and HashMap in Java, as they both implement Map interface.
let's have a look :
1) Both LinkedHashMap and HashMap are not synchronized and subject to race condition if shared between multiple threads without proper synchronization. Use Collections.synchronizedMap() for making them synchronized.

2) Iterator returned by HashMap and LinkedHashMap are fail-fast in nature.

3) Performance of HashMap and LinkedHashMap are similar also.


Difference between LinkedHashMap and HashMap in Java
Now let's see some differences between
LinkedHashMap and HashMap in Java:

1) First and foremost difference between LinkedHashMap and HashMap is order, HashMap doesn't maintain any order whileLinkedHashMap maintains insertion order of elements in Java.

2) LinkedHashMap also requires more memory than HashMap because of this ordering feature. As I said before LinkedHashMapuses doubly LinkedList to keep order of elements.

3) LinkedHashMap actually extends HashMap and implements Map interface.


Given the insertion order guarantee of LinkedHashMap, Its a good compromise between HashMap and TreeMap in Java because with TreeMap you get increased cost of iteration due to sorting and performance drops on to log(n) level from constant time.

Share

What is String literal pool?


What is String literal pool?

How to create a String

There are two ways to create a String object in Java:
  • Using the new operator. For example,
    String str = new String("Hello");.
  • Using a string literal or constant expression). For example,
    String str="Hello"; (string literal) or
    String str="Hel" + "lo"; (string constant expression).
What is difference between these String's creations? In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns true only if both references point to the same object.
Let's use the following example to see what difference between these creations of string:
public class DemoStringCreation {
  public static void main (String args[]) {
    String str1 = "Hello";  
    String str2 = "Hello"; 
    System.out.println("str1 and str2 are created by using string literal.");    
    System.out.println("    str1 == str2 is " + (str1 == str2));  
    System.out.println("    str1.equals(str2) is " + str1.equals(str2));  
    
    String str3 = new String("Hello");  
    String str4 = new String("Hello"); 
    System.out.println("str3 and str4 are created by using new operator.");    
    System.out.println("    str3 == str4 is " + (str3 == str4));  
    System.out.println("    str3.equals(str4) is " + str3.equals(str4));  
    
    String str5 = "Hel"+ "lo";  
    String str6 = "He" + "llo"; 
    System.out.println("str5 and str6 are created by using string 
constant expression.");    
    System.out.println("    str5 == str6 is " + (str5 == str6));  
    System.out.println("    str5.equals(str6) is " + str5.equals(str6));
    String s = "lo";
    String str7 = "Hel"+ s;  
    String str8 = "He" + "llo"; 
    System.out.println("str7 is computed at runtime.");         
    System.out.println("str8 is created by using string constant 
expression.");    
    System.out.println("    str7 == str8 is " + (str7 == str8));  
    System.out.println("    str7.equals(str8) is " + str7.equals(str8));
    
  }
}
The output result is:
str1 and str2 are created by using string literal.
    str1 == str2 is true
    str1.equals(str2) is true
str3 and str4 are created by using new operator.
    str3 == str4 is false
    str3.equals(str4) is true
str5 and str6 are created by using string constant expression.
    str5 == str6 is true
    str5.equals(str6) is true
str7 is computed at runtime.
str8 is created by using string constant expression.
    str7 == str8 is false
    str7.equals(str8) is true
The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.

String Literal Pool

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example
public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";  
       String str2 = "Hello"; 
       System.out.print(str1 == str2);
    }
}
The result is
true

Unfortunately, when you use
String a=new String("Hello");
a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";  
       String str2 = new String("Hello");
       System.out.print(str1 == str2 + " ");
       System.out.print(str1.equals(str2));
    }
}
The result is
false true

A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added. For example
public class Program
{
    public static void main(String[] args)
    {
        // Create three strings in three different ways.
        String s1 = "Hello";
        String s2 = new StringBuffer("He").append("llo").toString();
        String s3 = s2.intern();
        // Determine which strings are equivalent using the ==
        // operator
        System.out.println("s1 == s2? " + (s1 == s2));
        System.out.println("s1 == s3? " + (s1 == s3));
    }
}
The output is
s1 == s2? false
s1 == s3? true
There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.

String Literals in the Java Language Specification Third Edition


Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern.
Thus, the test program consisting of the compilation unit:
package testPackage;
class Test {
        public static void main(String[] args) {
                String hello = "Hello", lo = "lo";
                System.out.print((hello == "Hello") + " ");
                System.out.print((Other.hello == hello) + " ");
                System.out.print((other.Other.hello == hello) + " ");
                System.out.print((hello == ("Hel"+"lo")) + " ");
                System.out.print((hello == ("Hel"+lo)) + " ");
                System.out.println(hello == ("Hel"+lo).intern());
        }
}
class Other { static String hello = "Hello"; }
and the compilation unit:
package other;
public class Other { static String hello = "Hello"; }
produces the output:
true true true true false true
This example illustrates six points:
  • Literal strings within the same class in the same package represent references to the same String object.
  • Literal strings within different classes in the same package represent references to the same String object.
  • Literal strings within different classes in different packages likewise represent references to the same String object.
  • Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
  • Strings computed by concatenation at run time are newly created and therefore distinct.
The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.




Share

Saturday 5 January 2013

Enum in java with java enum examples


Enum in java with java enum examples


Enum in java

This tutorial consists of introduction to enum in java, java enum example (s), need of enum class in java with enum example. Enum in java or enums in java introduced in J2SE 5 , but what is enum in java? when to use enum in java, how to use enum in java , how to declare enum in java? how to serialize enum in java? how to sort enum in java? how to use java enum constructor ? there are lots of questions isn’t it? Lets look at how we can use enum in java. Enum in java are nothing but set of fields with set of fixed constants.
Before enum introduced in java , there were constants defined in the class as follows :
1
2
3
4
5
public Class ConstantPool{
     public static final int TCP_PORT = 123;
     public static final int DNS_PORT = 139;
     public static final int LDAP_PORT = 922;
}
In above java example we can see that we need to specify the constants using public static final int. These constant replicate enum like behaviour. But above program looks and easy and okay for a requirement, you must be wondering why we need to use enum in java. There is an answer to it and it is indeed need to be understood.
The approach of defining set of constant values are some serious drawbacks, lets see which are those and enum in java comes for help.
1. Missing type-safety :
First and foremost it is not type-safe. You are allowed to assign any port value which is not actual port value. Thus these constant can allow illegal values.
2. Missing Significant printing
Significant printing of the constant is missing from the way of defining constants using static final scheme. Like when we print the constant it will print the value such as 123 not TCP_PORT.
3. I/O on final static Strings not easy.
For converting values from String to I/O operations is not easy.
4. No behaviour of its own
Constant Strings defined by static and final are only values there is no behaviour associated with it.
Enum in java or enums in java helps in overcoming these limitations.

Enum in Java

Now lets see what is enum in java and how it helps in improving programming. Enum is like a class or an interface which keeps fixed set of constants, which we call as enum constants. Lets see how we can define the Enum constants :
// Java enum example 1.
1
2
3
4
5
public  enum  Ports{
    TCP,
               DNS,
    LDAP
};
In above code snippet we can see that out enum is PORTS and TCP, DNS , LDAP are the constants.
Now if we closely look at the code snippet above we can see that curly braces are like classes and interfaces. Also enum word is used like class or an interface. Naming convention is like a Class and and inter face too.
Enum constants are implicitly static and final. That means you cannot change the constant value again.
Another thing to watch for is if you were using java 1.4 and you have used enum as variable name , it will fail in case of java 1.5.
Now lets see benefits of using enum in java :
1. Unlike using array of Strings , we can use enums as case labels.
2. Enum in java are type safe.
3. If you are using lower version than java 7, then you can use enum in Switch statement.
4. We can easily add additional fields to the enum in java.
5. Enum in java uses its own namespace.
6. We can compare enums easily with ==.
7. Enum in java helps in reducing the bugs in our code. Lets see how if you have different ports but you want to restrict some of the ports such as reserved ports. So when you make constants using enum in java, compiler will restrict you from assigning the different ports other than TCP, DNS and LDAP.

Enum in java are typesafe. Enum in java uses its own namespace.

Declaration of enum in java :
Enums can be declared as their own separate class or as a class member. First we will see declaring enum in java outside a class :
// Java enum example 2. Declaration of enum in java
1
2
3
4
5
6
7
8
9
10
enum Ports {  TCP, DNS, LDAP  } // Declaring enum outside the class.
class PortSpec {
    Ports ports;
}
public class testPortSpec {
    public static void main( String[] args ){
        PortSpec portSpec = new PortSpec();
        portSpec.port = Ports.TCP; // Using enum which is outside the class.
}
}
In above code we can see that we have declared enum outside the class , but we can see that enum need to be declared with only the public or default modifier like non-inner class.


Enum in java need to be declared with only the public or default modifier.

Java Enum Example 3 : Declaring enum inside the class
1
2
3
4
5
6
7
8
9
10
class PortSpec {
    enum Ports {  TCP, DNS, LDAP  } // Declaring enum inside the class.
    Ports ports;
}
public class testPortSpec {
    public static void main( String[] args ){
        PortSpec portSpec = new PortSpec();
        portSpec.port = PortSpec. Ports.TCP; // Using enum which is inside the class PortSpec.
}
}
In above code snippet we have seen that we can use enums inside the class. But syntax for accessing an enum’s members depends on where the enum is delared.


Enum constant must not be declared inside a method .

Java Enum Example 4 : Declaring enum inside the class is wrong.
1
2
3
4
5
6
7
public class testPortSpec {
    public static void main( String[] args ){
        enum Ports {  TCP, DNS, LDAP  } // Wrong !
PortSpec portSpec = new PortSpec();
        portSpec.port = Ports.TCP; //
}
}
Above code we can see that we cannot declare the enum constant inside the method.
Convention for enum in java :
Common convention is enum constant to be in all UPPERCASE.
So far we seen how to declare the enum constants, but you must be curious to know what gets created when we make an enum in java. In above code snippet as we can see each of the enum declared in Ports is actually instances of Class Ports i.e. TCP is type of Ports like
public static final Ports TCP = new Ports( “TCP”, 123 );
Here you can see that it has been declared as static and final which we assume it is a constant.
Now lets see some of the key features of enum in java .
1. Declaring a constructor in enum in java
We can specify value to the enum constant at the time of creation. We can create the constructor to specify the value as shown below :
Java Enum Example 5 : Constructor of enum in java is declared as private

1
2
3
4
5
6
7
public class Ports{
TCP(123), UDP(345), LDAP(555);
public int portNumber;
private Ports( int portNumber ){  //Access modifier private 
    this.portNumber = portNumber;
}
};
In above code, we can see the Constructor of enum in java is declared as private, it must always be private, because any other access modifier can throw compile time error.


Java enum constructor :
Constructor of enum in java should be declared as private.

Also to get the value associated with constant we can add getValue() method which will give
the value associated with it.
2 As we seen above, as constructor is private, we cannot create instance of enum using new operator. So Enum constants can only be created in Enum class itself. The enum constructor is invoked automatically, with the arguments you define after the constant value.
You can also pass more than one argument to the enum constructor in java, similarly overloading of enum constructor is also possible.
3.All enums and enum constant have some built in or predefined methods such as values() and valueOf()
1. Public static EnumType[] values()
This method returns the array of enumeration constants.
2. Public static EnumType valueOf( String str )
This method return enum constant which corresponds to the String passed as an argument.
Java Enum Example 6 : Example of values() method in enum in java.
1
2
3
4
Ports allPorts[] = Port.values(); // Returns array of enum constants.
For( Ports portNumber : allPorts ){
    System.out.println(  portNumber );
}
Java Enum Example 7 : valueOf( String str ) example of enum in java..
1

Ports port = Port.valueOf(“TCP”); // Returns enum constant for  TCP
But what happens when we pass empty value to the valueOf function ? Guess! Right, it throws IllegalArgumentException in enum in java.
Also enum values are case sensitive so make sure you pass correct case parameter with doing trom() to valueOf function.
5.

Ordinal in enum in java

:
Ordinal in enum in java means the position in enum declaration. We don’t need to assign ordinals manually. These ordinals are self numbered. Ordinal values can be found out by using ordinal() method.
Java Enum Example 8 : Java enum ordinal example
1
2
3
for( Ports portNumber : allPorts ) {
    System.out.println(  portNumber.ordinal()  );
 }
If we want to get enum constant from the ordinal you can do it as follows :
Java Enum Example 9 : How to get enum constant from the ordinal in enum in java.
1
Port portNo = Port.values()[ ordinal ];
6. Constants defined inside enum in java are static and final so we can directly compare them using == operator.
Following program demonstrates the use of equality operator in enum in java.
1
2
3
4
Port tcpPort = Port.TCP;
If(  tcpPort == Port.TCP  ){
    System.out.println( "Ports are equal");
}
8.Enum in Switch statement :
Enum in java can be used as an argument to the Switch statement to be used as a case as we use it in case of int and char type. Before Java 7 we were not using String in Switch case statement. (Java 7 uses String in Switch statement) but for some reason if you are not using java 7 and above then enum makes a great option to be used in Switch statement.
Java Enum Example 9 : java enum switch example



Port portNumber = Port.TCP;
switch( portNumber ){
    case TCP:
        System.out.println(  “TCP Port Found” );
    case LDAP:
        System.out.println(  “LDAP Port Found” );
} 


9.Sorting enum in java
Sorting of enums can be done in same way as we do in sorting of array in java. You can create the Comparator object and use it to sort the enum constants in java.

Java Enum Example 10 : Sorting of enum in java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//Using util classes to sort enums
import java.util.Arrays;
import java.util.Comparator;
import static java.lang.System.out;
/**
 * This is an example of sorting or array of enums.
 *
 */
public class EnumSortExample
    {
    public static void main( String[] args )
        {
        Ports[] portNames = { Ports.TCP, Ports.DNS, Ports.LDAP };
        Arrays.sort( portNames ); // default sort
        for ( Ports portInfo : portNames )
            {
                System.out.println( portInfo + " " + portInfo.getPortUidName() +" "+portInfo.ordinal() );
            }
        // Default sorting is done according to the ordinal
        //TCP Tcp 0
        //DNS Dns 1
        //LDAP Ad 2
        Arrays.sort( portNames, new PortUidOrder() ); // sort by port uid
        for ( Ports portInfo : portNames )
            {
                System.out.println( portInfo + " " + portInfo.getPortUidName() +" "+portInfo.ordinal() );
            }
        // displays in Latin name order
        //LDAP Ad 2
        //DNS Dns 1
        //TCP Tcp 0
        }
    }
/**
 * Enum for Ports
 */
enum Ports  //
    {
        TCP( "Tcp" ),
        DNS( "Dns" ),
        LDAP( "Ad" );
    final String portUidName; //Field name for storing port Uid name
     
    Ports( String uidName ) // Constructor
        {
        this.portUidName = uidName;
        }
    // GET / SET METHODS
    String getPortUidName()
        {
        return portUidName;
        }
    }
/**
 *Creating Comparator class to sort enum by port uid
 */
class PortUidOrder implements Comparator<ports>
    {
    // Compare function to compare enums
    public final int compare( Ports a, Ports b )
        {
        return a.portUidName.compareToIgnoreCase( b.portUidName ); // Comparing the enums using compareToIgnoreCase
        }
    }
</ports>

Serialization of java enum

Serialization of java enum means converting java enum to a value which can be either primitive or String to store it easily either in database or file or disk. Deserialization is the process where stored value read back and converted to enum.
Lets see how enum in Java can be serialized :
1. Using user defined value ( Most recommended )
In this approach of serialization and de- serialization user defines one custom value to each enum constant and use toValue() and fromValue() functions to get the constant back. This approach is more dependable as it do not depend upon the ordering of the enum constant or the enum constant itself.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Following code snippet shows use of toValue() and fromValue() functions
public enum Ports {
 TCP("TCP"), DNS("DNS"), LDAP("AD"), UNKNOWN("UNKNOWN");
 private final String value;
 Ports( String value ) {
   this.value = value;
 }
// Usiing fromValue method to get the actual port
 public static Ports fromValue(String value ) {
   if ( value != null ) {
     for ( Ports port : values() ) {
       if (port.value.equals( value )) {
         return port;
       }
     }
   }
//here you can either return default or throw illegal argument exception
 }
 public String toValue() {
   return value;
 }
}
Serialization of enum in java
1
2
Ports port = Ports.TCP;
String savedPort = port.value(); //Serialization done using value()
De-serialization of enum in java
1
Ports savedPortEnum = Ports.fromValue( savedPort );
2. Using name() value :
We can use name() method to get the enum constant value. Lets see how we are serializing the enum constant using this approach :
1
2
Ports port = Ports.TCP;
String savedPort = port.name();
De-serialization of enum in java :
1
Port savedPortEnum = Ports.valueOf( savedPort );

Overriding toString in enum in java

Sometimes we need custom values for enum constants. To achive this we can use or override toString method. Overriding should be done only when we need more programmer friendly String to be used.
Enum implementing an interface :
1.Enum in java implicitly implements Comparable and Serializable interfaces.
2. But why would an enum implement an interface?
Enum in java don’t just provide set of passive constants. They may also have a complex functionality or behaviour.
3. How to implement interface using enum in java?
Lets see how we can implement an interface using java enum.
1
2
3
4
5
6
7
8
        public enum Ports implements Connectable(){
        TCP(123), UDP(345), LDAP(555);
    public void connect(){
    ......
}
}
Thus we see in above article some important aspects of enum in java using java enum example (s). Like declaring enum constant in java, built in functions such as values() and valueof(), ordinal in enum, sorting java enums, serialization of java enum. Hope you liked this article about enum in java.
Share