Search This Blog

Wednesday, May 28, 2014

New API in Java 8 to handle Date, Time and Zone

java.time (Java 8)

Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.
Getting current time in UTC/GMT is a simple one-liner…
ZonedDateTime now = ZoneOffset.UTC );
Dump to console…
System.out.println( "now: " + now );
When run…
now: 2014-05-27T23:42:03.522Z
The java.time classes are defined by JSR 310. They were inspired by Joda-Time but are entirely re-architected.

Wednesday, May 14, 2014

Features of Java 7

Using Strings in switch Statements

Do you know , In the JDK 7 release, you can use a String object in the expression of a switch statement:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {

     String typeOfDay;

     switch (dayOfWeekArg) {

         case "Monday":

             typeOfDay = "Start of work week";


         case "Tuesday":

         case "Wednesday":

         case "Thursday":

             typeOfDay = "Midweek";


         case "Friday":

             typeOfDay = "End of work week";


         case "Saturday":

         case "Sunday":

             typeOfDay = "Weekend";



      throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);


     return typeOfDay;


The switch statement compares the String object in its expression with the       expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient byte code from switch statements that use String objects than from chained if-then-else statements.

Hibernate Configuration Using Annotation

Dear JTLs, In previous posts we learned about how to configure Spring MVC using annotations  and Initialization and configuration of Spring application using annotation. Today I will discuss about Hibernate configuration using annotation.
Hibernate ORM (Hibernate in short) is an object-relational mapping library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
In previous hibernate releases we always tried to configure our hibernate app by using XML's. XML based configurations comes with following files -
  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH
  2. – A Java compliant property file which holds key value pair for different hibernate configuration strings.
  3. resource.hbm.xml- For each database tables,  we need to create a mapping XML file which contains mapping of table columns with the XML column elements. After some time these XML based resource configuration are upgraded and we are now able to use Java classes with @Entity annotation to map table columns into our hibernate app entity classes.
So coming to the point what steps we need to configure hibernate using annotation, are given below in example class -

@PropertySource({ "" })
@ComponentScan({ ApplicationConstants.MODEL_OBJ_LOCATION })
public class HibernateConfig {

private Environment env;

public LocalSessionFactoryBean sessionFactory() {
        final LocalSessionFactoryBean sessionFactory = new         LocalSessionFactoryBean();
sessionFactory.setPackagesToScan(new String[] { ApplicationConstants.MODEL_OBJ_LOCATION});
return sessionFactory;

public DataSource restDataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env .getProperty(ApplicationConstants.DB_DRIVER_CLASS_PROPERTY_NAME));
dataSource.setUsername(env .getProperty(ApplicationConstants.DB_USER_NAME_PROPERTY_NAME));
dataSource.setPassword(env .getProperty(ApplicationConstants.DB_PASSWORD_PROPERTY_NAME));

return dataSource;

public HibernateTransactionManager transactionManager() {
final HibernateTransactionManager txManager = new    HibernateTransactionManager();
return txManager;

public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();

Properties hibernateProperties() {
return new Properties() {
* Default serial version ID
 private static final long serialVersionUID = 1L;
setProperty(           ApplicationConstants.HIBERNATE_GLOBALY_QUOTED_IDENTIFIERS,
env.getProperty(ApplicationConstants.HIBERNATE_GLOBALY_QUOTED_IDENTIFIERS         ));

Using @Configuration Spring annotation we can declare any class as a configuration class the above class is configured to contain hibernate configuration.
@PropertySource({ "" }) : defines all the properties related to database like database URL, userName, password, connection pool etc will be available to this app 
.@ComponentScan({ ApplicationConstants.MODEL_OBJ_LOCATION }): Here component scan does scanning all the entity classes put into provided package.

This is all about hibernate configuration using annotation if you have any other option or way then please mention that into comment box.

Friday, May 9, 2014

How STATIC keyword works in Java?

Dear Friends , As you all would be aware of static variables, static methods , static classes and static inner classes. So have you ever thought about the pros and cons of static use in java . Lets have a look on the explanation to get a deeper idea about its uses.

Static Variables 

  • Static variable are known as class level variable also. So it will be accessed on class only whenever you want to search from outside of this class.
  • Some programmers use object to access on static variables but that's a programmer fault, Its recommended to access static variables only on class level.
  • Static variables always share a common memory location for all the objects which access them.
  • Static variables can be accessed inside non static methods as well but its not true for non static variables in java. It means non static variables can be accessed only in non static methods.
  • For each object of a class , non static variables will have the different references however static variable will have the same reference for all the objects. for example-
          private static int a = 10;//static declaration of java variable
          private int b = 20;//non static java variable
  • Static variables are bonded using static binding at compile time so they are comparatively faster than there non-static counter part which were bonded during run time.
  • Static fields are initialized at the time of class loading in Java, opposite to instance variable which is initialized when you create instance of a particular class.

Static Methods

  • Static methods in java have the same loading mechanism as static variables.
  • These methods can access or use only static variables , non static variables are not allowed inside static methods.
  • static method can not be override into its subsequent child classes because they are part of the class in which they have been declared not a part of its object. so if you have same static  method in subclass and super class , method will be invoked based on declared type of object instead of runtime.
  • Be careful while using static keyword in multi-threading or concurrent programming because most of the issue arise of concurrently modifying a static variable by different threads resulting in working with stale or incorrect value if not properly synchronized. most common issue is race condition which occurs due to poor synchronization or no synchronization of static variable.
  • Java static methods cannot use the ‘this’ keyword

Static Class

  • The classes which contains only static methods are known as Static class. 
  • Normally we make a class static in Java when we want a single resource to be shared between all instances and normally we do this for utility classes which are required by all components and which itself doesn't have any state. Sometime interviewer ask  when to use Singleton vs Static Class in Java for those purpose,answer is that if its completely stateless and it work on provided data then you can go for static class otherwise Singleton pattern is a better choice.

That's all on What is static variable, method and nested static class in Java. knowledge of static keyword in Java is must for any Java programmer and skill to find out when to use static variable or static method is an important skill. Incorrect and careless use of static variable and static method in Java will result in serious concurrency issues like deadlock and race condition in Java.

Tuesday, May 6, 2014

Spring Web MVC configuration using annotation

After configured Spring Application Initializer , we need to write one more class that will include all the configuration related to Spring web MVC. Once Spring web container will invoked it will search for the annotated class which have configuration like 'view resolver' , 'resource handler ' etc. To get more details on this please refer following code snippet-

@ComponentScan(basePackages = ApplicationConstants.CONFIG_LOCATION)
public class WebConfig extends WebMvcConfigurerAdapter{

* Default constructor
public WebConfig() {


* The view resolver for the application
* @return InternalResourceViewResolver
public InternalResourceViewResolver getInternalResourceViewResolver() {
   InternalResourceViewResolver resolver = new InternalResourceViewResolver();
   return resolver;

/* (non-Javadoc)
* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#addResourceHandlers(org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry)
public void addResourceHandlers(ResourceHandlerRegistry registry) {

/* (non-Javadoc)
* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#configureDefaultServletHandling(org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer)
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {


Kindly comment if anything , I have missed here. I will update the same accordingly.

Monday, May 5, 2014

How to initialize and configure Spring MVC application without creating any *-servlet.xml?

Spring Annotations From its beginning, Spring’s most common means of configuration has been XML-based. But as developers grow weary of navigating through a seemingly endless maze of angle-brackets, some have started looking for other ways to wire the beans in their Spring-enabled applications. Spring has responded with several annotation-driven configuration options. In this post, you will find a guide to all of the annotations supported in Spring 2.5.

To configure your application by using annotations we need to override 'onStartup' method of 'WebApplicationInitializer' Interface.

To get more detail about this please refer the following code snippet-

 WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
//Register your dispatcher servlet into servlet context
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(ApplicationConstants.SERVLET_NAME, new DispatcherServlet(context));
//provide your default or base path mapping here

Remember getContext() is a custom method to get Context of your application ,This would be implemented like -

 AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

        return context;
Where config location is your component classes location path.

Hope you like this tutorial, Please keep questioning and comment on this.

Thursday, May 1, 2014

Why String is Immutable?

5 Reasons of Why String is final or Immutable in Java

Though true reasons of why String class was made final is best known to Java designers, and  apart from that hint on security by James Gosling, I think following reasons also suggest Why String is Final or Immutable in Java.

1) String Pool
Java designer knows that String is going to be most used data type in all kind of Java applications and that's why they wanted to optimize from  start. One of key step on that direction was idea of storing String literals in String pool. Goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties which are unknown to each other. Let's take an hypothetical example, where two reference variable is pointing to same String object:

String str1 = "Java";
String str2 = "Java";

Now if str1 changes the object from "Java" to "C++", reference variable also got value str2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, key idea of String pool can not be implemented without making String final or Immutable in Java.

2) Security
Java has clear goal in terms of providing a secure environment at every level of service and String is critical in those whole security stuff. String has been widely used as parameter for many Java classes, e.g. for opening network connection, you can pass host and port as String, for reading files in Java you can pass path of files and directory as String and for opening database connection, you can pass database URL as String. If String was not immutable, a user might have granted to access a particular file in system, but after authentication he can change the PATH to something else, this could cause serious security issues. Similarly, while connecting to database or any other machine in network, mutating String value can pose security threats. Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.

3) Use of String in Class Loading Mechanism
Another reason for making String final or Immutable was driven by the fact that it was heavily used in class loading mechanism. As String been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. can be changed to malicious class com.unknown.DataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading correct classes.

4) Multithreading Benefits
Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, means much cleaner code involving sharing of String between multiple threads. This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code. 

5) Optimization and Performance
Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee open path for many performance optimization e.g. caching. String itself know that, I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple world, when you first call hashCode() method of any String object, it calculate hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g.Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.