Difference between Checked vs Unchecked Exceptions in Java

Checked Exception and Unchecked Exception

Checked Exception
When there is possible chances of Failure Checked Exceptions are Introduced. Checked Exceptions are the one checked at compile time by Java. Checked Exceptions must be caught within try-catch block or throw that exception in its definition using throws keyword.

Any Exception that is direct sub-class of Exception but doesn't inherit java.lang.RuntimeException are Checked Exception.


Example of Checked Exception
You want to read any file on system using FileReader, So there is chances of File not found on specified path this is called Checked Exception(Possible chances of Failure).
import java.io.*;

public class CheckedException {

   public static void main(String[] args) {
	/* Create object of File by providing absolute path */
	File objFile = new File("D:\\myfile.txt");
	BufferedReader objBufferedReader = null;
	FileReader objFileReader = null;
	try {
	   /* Get FileReader on File */
	   objFileReader = new FileReader(objFile);
	   /* Get BufferedReader from FileReader */
	   objBufferedReader = new BufferedReader(objFileReader);
   	   String strFileline = "";
	   /* Read file line by line */
	   while((strFileline = objBufferedReader.readLine()) != null){
	 	System.out.println(strFileline);
	   }
	} catch (FileNotFoundException e) {
	   /* Checked Exception */
	   e.printStackTrace();
	} catch (IOException e) {
	   /* Checked Exception */
	   e.printStackTrace();
	}finally{
	   /* Close the resources used for file reading */
	   try {
		if(objBufferedReader != null){
		   objBufferedReader.close();
		}
		
		if(objFileReader != null){
		   objBufferedReader.close();
		}
	   } catch (IOException e) {
		e.printStackTrace();
	   }
	}
   }
}

Unchecked Exception
Exception that are not checked by Java Compiler at compile time called Unchecked Exception. Any Exception that inherits java.lang.RuntimeException are UnChecked Exception.


Example of Unchecked Exception
Dividing two Integer numbers is best example of Unchecked Exception. You are getting two values after evaluation of your logic and not sure what will be the values and divide it, that leads to java.lang.ArithmeticException.
public class UnCheckedException {

   public static void main(String[] args) {
	int x = 10;
	int y = getY();
	System.out.println(x / y);
   }

   /**
    * This is example of getting value from some method call.
    * There is possibilities of getting value `0`.
    *  
    * Java compiler can't identify such errors
    */
   public static int getY(){
	return 2-2;
   }
}

How to get valued query from Hibernate Criteria(Not Logger)?


As per my knowledge there is no library available that allows you get Criteria query with its real values. So I came up with solution that allows you to do that.

Hibernate Assist, Its an open source Hibernate Criteria analysis tool. It has many features one of them is to get Criteria query with its value.

Download Librarywww.javaquery.com/p/hibernateassist.html

Source Code
Criteria criteria = objSession.createCriteria(User.class);
criteria.createAlias("Messages", "Messages");
criteria.createAlias("CreditCard", "CreditCard");
criteria.add(Restrictions.eq("Email", "vicky.thakor@javaquery.com"));
List<User> listUser = criteria.list();

HibernateAssist objHibernateAssist = new HibernateAssist(objSession);
objHibernateAssist.setCriteria(criteria);
String strQuery = objHibernateAssist.getValuedCriteriaQuery();
System.out.println(strQuery);

Output
SELECT this_.id                        AS id0_2_, 
       this_.username                  AS username0_2_, 
       this_.password                  AS password0_2_, 
       this_.email                     AS email0_2_, 
       messages1_.id                   AS id1_0_, 
       messages1_.user_id              AS user2_1_0_, 
       messages1_.message_text         AS message3_1_0_, 
       creditcard2_.id                 AS id2_1_, 
       creditcard2_.user_id            AS user2_2_1_, 
       creditcard2_.credit_card_number AS credit3_2_1_ 
FROM   user_master this_ 
       INNER JOIN message messages1_ 
               ON this_.id = messages1_.user_id 
       INNER JOIN creditcard creditcard2_ 
               ON this_.id = creditcard2_.user_id 
WHERE  this_.email = 'vicky.thakor@javaquery.com' 
Note: I tried to manage almost all cases however if you find for your Criteria its not working please comment your issues.

How to invoke(call) Setter and Getter method of field(variable) using Reflection?


In my previous article we've seen How to get fields(variables) name and type of class using Reflection?. Now its time to know how you can set value and get value of field using reflection.

Source Code
I've created some sample bean for example.
/* Actor.java */
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Actor {
   private long id;
   private String Name;
   private Set Films;
   private List LanguageSpeaks;
   private Map dummyMap;
}

public String getName() {
   return Name;
}
public void setName(String name) {
   Name = name;
}
/* Other Setter and Getter methods */

Source Code
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

public class InvokeSetterGetter {

   public static void main(String[] args) {
    /* Create object of Actor. */
    Actor objActor = new Actor();

    InvokeSetterGetter objInvokeSetterGetter = new InvokeSetterGetter();
    /* Call invokeSetter method */
    objInvokeSetterGetter.invokeSetter(objActor, "Name", "Benedict Cumberbatch");
    /* Call invokeGetter method */
    objInvokeSetterGetter.invokeGetter(objActor, "Name");
   }
 
   private void invokeSetter(Object obj, String variableName, Object variableValue){
      /* variableValue is Object because value can be an Object, Integer, String, etc... */
      try {
        /**
         * Get object of PropertyDescriptor using variable name and class
         * Note: To use PropertyDescriptor on any field/variable, the field must have both `Setter` and `Getter` method.
         */
         PropertyDescriptor objPropertyDescriptor = new PropertyDescriptor(variableName, obj.getClass());
         /* Set field/variable value using getWriteMethod() */
         objPropertyDescriptor.getWriteMethod().invoke(obj, variableValue);
      } catch (IllegalAccessException | IllegalArgumentException
        | InvocationTargetException | IntrospectionException e) {
        /* Java 8: Multiple exception in one catch. Use Different catch block for lower version. */
        e.printStackTrace();
      }
   }

   private void invokeGetter(Object obj, String variableName){
      try {
        /**
         * Get object of PropertyDescriptor using variable name and class
         * Note: To use PropertyDescriptor on any field/variable, the field must have both `Setter` and `Getter` method.
         */
         PropertyDescriptor objPropertyDescriptor = new PropertyDescriptor(variableName, obj.getClass());
        /**
         * Get field/variable value using getReadMethod()
         * variableValue is Object because value can be an Object, Integer, String, etc...
         */
         Object variableValue = objPropertyDescriptor.getReadMethod().invoke(obj);
        /* Print value of variable */
         System.out.println(variableValue);
      } catch (IllegalAccessException | IllegalArgumentException
        | InvocationTargetException | IntrospectionException e) {
       /* Java 8: Multiple exception in one catch. Use Different catch block for lower version. */
        e.printStackTrace();
      }
   }
}

How to get fields(variables) name and type of class using Reflection?

Java Reflection
Reflection API is used to interact, examine or modify run-time behavior of programs running in the Java virtual machine. Reflection is bit costly so use it only when you have no other options left. Today we'll see how you can get name and type of fields(variables) declared in class.

Source Code
I've created some sample beans for example.
/* Actor.java */
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Actor {
   private long id;
   private String Name;
   private Set<Film> Films;
   private List<Language> LanguageSpeaks;
   private Map<string long=""> dummyMap;
}

/* Film.java */
public class Film {
   private long id;
   private String Name;
}

/* Language.java */
public class Language {
   private long id;
   private String Name;
}

Source Code
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

public class ClassFieldsReflection {
   public static void main(String[] args) {
      ClassFieldsReflection objClassFieldsReflection = new ClassFieldsReflection();
      objClassFieldsReflection.AccessFieldsUsingReflection(new Actor());
   }
	
   /**
    * Access fields of Object using Reflection.
    * @param obj
    */
   private void AccessFieldsUsingReflection(Object obj){
      /* Get array of fields declared in Class */
      Field[] fields = obj.getClass().getDeclaredFields();
      /* Loop through all fields */
      for(int i = 0; i < fields.length ; i++){
	 /* Get field name */
	 String fieldName = fields[i].getName();
	 /* Get generic/base type of field (int, short, long, String, etc...) */
	 Object fieldType = fields[i].getGenericType();
		
	 System.out.println("Field(variable) name: " + fieldName);
	 System.out.println("Generic Type: " + fieldType);
			
	 /* Set<E>, List<E> and Map<K,V> are ParameterizedType */
	 if(fieldType instanceof ParameterizedType){
	   /**
	    * This will give you Actual Type of Set<E>, List<E> and Map<K,V>.
	    * Example:
	    * List<String> -> String is ActualType
	    * Set<Integer> -> Integer is ActualType
	    * Map<String, Long> -> String, Long is ActualType
	    */
	    System.out.println("Actual Type:");
	    for(Object objActualType : ((ParameterizedType) fieldType).getActualTypeArguments()){
		System.out.println("-- "+objActualType);
	    }
	 }
	 System.out.println("+++++++++++++++++++++++++++++++");
      }
   }
}

Output
Field(variable) name: id
Generic Type: long
+++++++++++++++++++++++++++++++
Field(variable) name: Name
Generic Type: class java.lang.String
+++++++++++++++++++++++++++++++
Field(variable) name: Films
Generic Type: java.util.Set
Actual Type:
-- class javaQuery.beans.Film
+++++++++++++++++++++++++++++++
Field(variable) name: LanguageSpeaks
Generic Type: java.util.List
Actual Type:
-- class javaQuery.beans.Language
+++++++++++++++++++++++++++++++
Field(variable) name: dummyMap
Generic Type: java.util.Map
Actual Type:
-- class java.lang.String
-- class java.lang.Long
+++++++++++++++++++++++++++++++

What is try-with-resources in Java 7 or above?

try-with-resources + java 7 + feature

Java designer has finally came up with better solution for closing resource. try-with-resources introduced in Java 7. Its one of noticeable feature of Java 7 and currently used by developers around the world.

The try-with-resources statement ensures that all your resources like BufferedReader, FileInputStream, ObjectInputStream, etc... closed at the end of statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Source Code
import java.io.BufferedReader;
import java.io.FileReader;

public class TryWithResourcesExample {
   public static void main(String[] args) {
      /**
       * Resources declared in parentheses `()` after `try` keyword 
       * implements java.io.Closeable interface.
       * 
       * Note: 
       * - Even if exception occurs both the resources will be closed.  
       * - close methods of resources are called in the opposite order of their creation.
       */
      try(
      /* Create object of FileReader */
   FileReader objFileReader = new FileReader("D:\\Dropbox\\Notes.txt");
   /* Create object of BufferedReader using object of FileReader */
   BufferedReader objBufferedReader = new BufferedReader(objFileReader);
 ){
   /* Print the first line of file */
   System.out.println(objBufferedReader.readLine());
      }catch(Exception ex){
   ex.printStackTrace();
      }
   }
}

Note
  • - Even if exception occurs all resources will be closed.
  • - close methods of resources are called in the opposite order of their creation.


How to Serialize and Deserialize object in Java?


javadoc
To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Deserialization is the process of converting the serialized form of an object back into a copy of the object.

Source Code (User.java)
Any object that implements Serializable interface is eligible for Object Serialization.
import java.io.Serializable;

public class User implements Serializable{
    private transient long id;
    private String Firstname;
    private transient String Lastname;
    private transient boolean status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
    
    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

transient keyword
Any variable or object declared with transient keyword will not be stored in Serialize Object. It will give you default value particular data type.
  • Boolean Data type: transient boolean will give false value in Object Deserialization.
  • Numeric Data types: transient int, double, long, float will give 0 value in Object Deserialization.
  • String Data type: transient String will give null value in Object Deserialization.
  • Any Object: transient ANY_OBJECT will give null value in Object Deserialization.

Source Code (SerializeObject.java)
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Serialization Code...");
        /* Creating an object of User */
        User objUser = new User();
        
        /* Set properties of User object */
        /* Id will be set to `0` in serialized object because it is declared as `transient` */
        objUser.setId(111l);
        /* Set Firstname */
        objUser.setFirstname("Vicky");
        /* Lastname will be set to `null` in serialized object because it is declared as `transient` */
        objUser.setLastname("Thakor");
        /* Status will be set to `false` in serialized object because it is declared as `transient` */
        objUser.setStatus(true);
        
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileOutputStream to store object in file [Windows: C:\Users\CurrentUser\User.ser(i.e: `.ser` Standard File Extension)] */
                FileOutputStream objFileOutputStream = new FileOutputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectOutputStream to write objUser on file. */
                ObjectOutputStream objObjectOutputStream = new ObjectOutputStream(objFileOutputStream);
            ){
            /* Write object on file. */
            objObjectOutputStream.writeObject(objUser);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Source Code (DeSerializeObject)
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Deserialization Code...");
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileInputStream to get serialized file. */
                FileInputStream objFileInputStream = new FileInputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectInputStream to read User object from file. */
                ObjectInputStream objObjectInputStream = new ObjectInputStream(objFileInputStream);
           ){
            /* Read the User object from file. We've to cast it to our object */
            User objUser = (User) objObjectInputStream.readObject();
            /* Print the properties of User object */
            System.out.println(objUser.getId());
            System.out.println(objUser.getFirstname());
            System.out.println(objUser.getLastname());
            System.out.println(objUser.isStatus());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Output (DeSerializeObject.java)
Object Deserialization Code...
0
Vicky
null
false

An Example of HttpSessionAttributeListener in Java


HttpSessionAttributeListener, is used to keep track of every HttpSession attribute Added, Replaced or Removed in your current web application.

Source Code
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class SessionAttributeListener implements HttpSessionAttributeListener {
    /**
     * Called when any servlet/jsp in application add the Attribute in HttpSession 
     * @param event 
     */
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        /**
         * Get the attribute name.
         * Attribute name is always in String
         */
        String strAttributeName = event.getName();
        /**
         * Get the attribute value
         * Attribute value can be String, Object, etc...
         */
        Object objAttributeValue = event.getValue();
        /* Print the value of AttributeName and AttributeValue */
        System.out.println("Attribute added: [" + strAttributeName + " : " + objAttributeValue + "]");
    }

    /**
     * Called when any servlet/jsp in application override/replace/add_same_attribute_to the HttpSession
     * @param event 
     */
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        /**
         * Get the attribute name.
         * Attribute name is always in String
         */
        String strAttributeName = event.getName();
        /**
         * Get the attribute value
         * Attribute value can be String, Object, etc...
         */
        Object objAttributeValue = event.getValue();
        /* Print the value of AttributeName and AttributeValue */
        System.out.println("Attribute removed: [" + strAttributeName + " : " + objAttributeValue + "]");
    }

    /**
     * Called when any servlet/jsp in application try to remove the attribute from HttpSession
     * @param event 
     */
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        /**
         * Get the attribute name.
         * Attribute name is always in String
         */
        String strAttributeName = event.getName();
        /**
         * Get the attribute value
         * Attribute value can be String, Object, etc...
         */
        Object objAttributeValue = event.getValue();
        /* Print the value of AttributeName and AttributeValue */
        System.out.println("Attribute replaced: [" + strAttributeName + " : " + objAttributeValue + "]");

    }
}

Attach SessionAttributeListener in your web application through web.xml . Add following code in you web.xml between web-app tag.
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
...
...
    <servlet>
        <servlet-name>SessionAttributeServlet</servlet-name>
        <servlet-class>com.javaquery.servlet.SessionAttributeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionAttributeServlet</servlet-name>
        <url-pattern>/SessionAttributeServlet</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>com.javaquery.Listeners.SessionAttributeListener</listener-class>
    </listener>
</web-app>

Source Code (Sample Servlet)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionAttributeServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            HttpSession httpSession = request.getSession();
            /* SessionAttributeListener.attributeAdded(HttpSessionBindingEvent event) will be called */
            httpSession.setAttribute("username", "vicky.thakor"); 
            /* SessionAttributeListener.attributeRemoved(HttpSessionBindingEvent event) will be called */
            httpSession.setAttribute("username", "rajpriya.chudasama");
            /* SessionAttributeListener.attributeReplaced(HttpSessionBindingEvent event) will be called */
            httpSession.removeAttribute("username");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}