Reading excel sheet in Java


In our earlier tutorial we have seen how to create excel sheet using Apache POI library in Java. As same we will see how to read excel sheet file using Apache POI. We are using same Employee Details class and excel sheet which used in our earlier tutorial for this demo. So before looking into this tutorial please take a look on earlier tutorial as how we have created the Excel sheet using POI and bean class which we have used. 

POI jar file (Download latest version)


import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ReadExcel {
 
 public static void main(String[] args) {
  
  List<EmployeeDetails> list = readExcelSheet("D://test.xls");
  
  displayEmployeeDetails(list);
 }
 
 public static List<EmployeeDetails> readExcelSheet(String fileName){
  
  List<EmployeeDetails> list = new ArrayList<EmployeeDetails>();
  
  try{
   FileInputStream file = new FileInputStream(new File(fileName));
  
   //Creating Work Book
      HSSFWorkbook workBook = new HSSFWorkbook(file);
   
      //Read first sheet from Excel 
      HSSFSheet sheet = workBook.getSheetAt(0);
       
      //Reading sheet rows 
      Iterator<Row> rows = sheet.iterator();
      
      // Moving to next row to get employee details. Excluding headers 
      rows.next();
      
      while(rows.hasNext()) {
       int empId;
       String empName;
       String designation;
       
       Row row = rows.next();
          
          Iterator<Cell> cellIterator = row.cellIterator();

          empId = (int) cellIterator.next().getNumericCellValue();
          empName = cellIterator.next().getStringCellValue();
          designation = cellIterator.next().getStringCellValue();
          
          list.add(new EmployeeDetails(empId, empName, designation));          
      }   
  }catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }
 
 public static void displayEmployeeDetails(List<EmployeeDetails> list){
  
  System.out.println("Employee ID \t Employee Name \t Designation");
  for(int i=0;i<list.size();i++){
   EmployeeDetails obj = list.get(i);
   System.out.print(obj.getEmpId()+"\t\t");
   System.out.print(obj.getEmpName()+"\t\t");
   System.out.print(obj.getDesignation()+"\n");
  }
 }
}

OUTPUT:


Employee ID   Employee Name   Designation
1  Raj  Software Engineer
2  Kamal  Technical Lead
3  Steve  Senior Software Engineer
4  David  Quality Engineer
5  John  Field Engineer

Creating excel sheet in Java


In this tutorial we see how to create excel sheet in Java using Apache POI library. By using Apache POI library we can create multiple Microsoft files like .xls, .ppt, .doc etc., Lets start this tutorial with creating excel sheet (.xls) file using POI jar. Before starting our program we need POI jar file which can downloaded from below link

POI jar file (Download latest version)


public class EmployeeDetails{
 
 private int empId;
 private String empName;
 private String designation;
 
 public EmployeeDetails(int empId, String empName, String designation){
  this.empId = empId;
  this.empName = empName;
  this.designation = designation;
 }
 
 public int getEmpId() {
  return empId;
 }
 public String getEmpName() {
  return empName;
 }
 public String getDesignation() {
  return designation;
 }
}




import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class CreateExcel {

 public static void main(String[] args) {
  
  List<EmployeeDetails> list = populateData();
  
  createExcelSheet(list, "D:\\test.xls");
 }
 
 public static List<EmployeeDetails> populateData(){
  List<EmployeeDetails> list = new ArrayList<EmployeeDetails>();
  try{
   list.add(new EmployeeDetails(1, "Raj", "Software Engineer"));
   list.add(new EmployeeDetails(2, "Kamal", "Technical Lead"));
   list.add(new EmployeeDetails(3, "Steve", "Senior Software Engineer"));
   list.add(new EmployeeDetails(4, "David", "Quality Engineer"));
   list.add(new EmployeeDetails(5, "John", "Field Engineer"));
  }catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }
 
 public static void createExcelSheet(List<EmployeeDetails> list, String fileName){
  
  try {
   
   //Creating Work Book
   HSSFWorkbook workBook = new HSSFWorkbook();
   
   //Creating sheet
   HSSFSheet sheet = workBook.createSheet("Employee Details");
    
   
   Row row = sheet.createRow(0);
   Cell cell = row.createCell(0);
   cell.setCellValue("Employee Id");
   cell = row.createCell(1);
   cell.setCellValue("Employee Name");
   cell = row.createCell(2);
   cell.setCellValue("Designation");
   
   for(int i=0;i<list.size();i++){
    
    EmployeeDetails obj = list.get(i); 
    row = sheet.createRow(i+1);
    cell = row.createCell(0);
    cell.setCellValue(obj.getEmpId());
    cell = row.createCell(1);
    cell.setCellValue(obj.getEmpName());
    cell = row.createCell(2);
    cell.setCellValue(obj.getDesignation());
   }
   
      FileOutputStream fos = new FileOutputStream(new File(fileName));
      workBook.write(fos);
      fos.close();
      System.out.println("Excel sheet created successfully..");
       
  } catch (Exception e) {   
      e.printStackTrace();
  }  
 }
}


OUTPUT:


Creating excel sheet in Java


Checked and Unchecked Exceptions in Java


Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. By using try-catch in a method and if any error occurs then object creates and handed over to the run-time system. Those objects are called as Exception object which contains information's about the exception occurred. 
In our earlier tutorial we have seen difference between throw and throws in java and these exception objects are called as throwing an exception to the run-time system. Normally there are 3 types of Exceptions in Java and they are 

1. Checked exception (or) Compile time exception 
2. Unchecked exception (or) Run-time exception
3. Error 

Below are the Exception hierarchy in Java.


Checked and Unchecked Exceptions in Java


Checked Exception:

Exceptions which are checked under the block or method and caught at compile time are called as checked exceptions. For example if we are reading a file with input as file name and by mistake file name supplied with wrong name then FileNotFoundException will be thrown from the constructor for non-existing file. A well written program will catch those exception and passed to the run-time system. 

Unchecked Exception:

Unchecked Exception are also called as run-time exception which are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These are usually called as programming bugs are API errors which occurs at run-time. For example consider a method passes the file-name to other method. By some programming flaws its started sending null to the method which caught under NullPointerExpcetion.

Errors: 

Errors also called as unchecked exceptions which are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. For example if application successfully opens a input file, but is unable to read the file because of a hardware or system failure are called as Errors which can't be recovered. 

Below are the few list of checked and Unchecked exceptions in java 

Checked Exceptions:

Exception
FileNotFoundException
ParseException
IOException
NoSuchFieldException
NoSuchMethodException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException


Unchecked Exceptions:

NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
AssertionError
NoClassDefFoundError
ClassCastException
StackOverflowError
IllegalArgumentException
IllegalStateException
ExceptionInInitializerError


Difference between throw and throws in Java

 

This is one of the famous interview question asked. When we talk about throw and throws it comes under Exception handling in Java and both are keywords used to handle different types of exception in our application. Before knowing about throw and throws needs to know about try, catch and finally blocks in Java and how its used to handle and catch the exception in Java.

Throw is used inside any methods or blocks to throw Exception, but throws used to method declaration specifying that list of Exceptions can be thrown from particular method. Below is a sample code to use throw and throws in Java.


public void myMethod() throws FileNotFoundException, RemoteException {
        ....
        throw new NullPointerException();
}


Suppose if any method throws Exception then caller method needs to handle those Exception or can be re-thrown to previous method call. 


public class ThrowTest {
    
    public static void main(String[] args) {
        try{
            myMethod();
        }catch (FileNotFoundException e) {
            // TODO: handle exception
        }catch (RemoteException e) {
            // TODO: handle exception
        }
    }
    
    public static void myMethod() throws FileNotFoundException, RemoteException {
        //....
        throw new NullPointerException();
    }
}


(OR)


public class ThrowTest {
    
    public static void main(String[] args) throws FileNotFoundException, RemoteException {
        myMethod();        
    }
    
    public static void myMethod() throws FileNotFoundException, RemoteException {
        //....
        throw new NullPointerException();
    }
}


Throw statement can be used anywhere in the method statements like inside if-else, switch etc., but throws should be always used in method declaration.

While we throw an Exception explicitly control transferred to the called method. 

If we didn't handle throws Exception in caller method then we will compile time error, where as if didn't handle throw Exceptions then there won't be any compile time error. Statements followed by method call will not be executed. 


public class ThrowTest {
    
    public static void main(String[] args)  {
        System.out.println("Before method call...");
        myMethod();        
        System.out.println("After method call...");
    }
    
    public static void myMethod()  {
        System.out.println("Before throw...");
        throw new NullPointerException();
        
        // Unreachable code 
        //System.out.println(\"After throw...\");
    }
}

OUTPUT:


Before method call...
Before throw...
Exception in thread "main" java.lang.NullPointerException





Try, Catch and Finally in Java

In this tutorial we will see about try, catch and finally blocks in Java. When we talk about these 3 blocks its come under Exception Handling and one on the finest feature in Java to handle both checked and UN-checked exceptions.

  • try() - Try block used to hold statements which may cause exception at compile time or at run-time. Those statements will be surrounded with try block.
  • catch() - Catch block used to catch if any exception occurred in try block statements. Basically list of exceptions will be specified in the catch statement as like given below examples. Before Java 7 each exception should be specified in separate catch blocks and need to catched. But in Java 7 we have got a cool feature to use multi-catch exception handling. Please refer to our earlier tutorial for Java 7 multi-catch
  • finally() - Finally block will execute no matter whether if any exception occurred or not occurred, always finally block will be executed except 
    • - if there are any infinite looping in try or catch block
    • - or if System.exit statement present in try or catch block.
There are few interview questions were interviewer will be asked,

1. Try block can be without catch block?
Answer: Yes, but finally block is necessary in that case. 

2. Try and catch block can be without finally block?
Answer: Yes

3. Finally block can be without try or catch?
Answer: No, finally must be placed with try or try & catch block. 

4. Single try block can have multiple catch blocks?
Answer: Yes

5. Can we have multiple finally blocks?
Answer: No, for single try and catch there must be only 1 finally block.


Lets see few examples

EXAMPLE - 1


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  int number = myFunction();
  System.out.println("NUMBER : "+number);
 }
 
 public static int myFunction(){
  try{
   return 20;
  
  }catch (NumberFormatException e) {
   System.out.println("NumberFormatException occured !!!");
   return 5;
  
  }catch (Exception e) {
   System.out.println("Exception occured !!!");
   return 30;
  
  }finally{
   return 10;
  }
 }
}

OUTPUT:


NUMBER : 10


EXAMPLE - 2


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  int number = myFunction();
  System.out.println("NUMBER : "+number);
 }
 
 public static int myFunction(){
  try{
   return 50;
  }finally{
   return 100;
  }
 }
}

OUTPUT:


NUMBER : 100


EXAMPLE - 3


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  String name = null;
  myFunction(name);  
 }
 
 public static void myFunction(String name){
  try{
   System.out.println("LENGTH: "+name.length());
   System.out.println("NAME: "+name);
  
  }catch (NullPointerException e) {
   System.out.println("NullPointerException occured !!!");
  
  }finally{
   System.out.println("Finally Executed...");
  }
  System.out.println("Function finished ...");
 }
}

OUTPUT:


NullPointerException occured !!!
Finally Executed...
Function finished ...







IP and Domain Name Lookup using Java

 

In this tutorial we will see how to find IP address from domain name and how to find host from IP. We have used dnsjava open source library for this demo. You can download dnsjava jar from external link and can add it in your project.


import java.net.InetAddress;
import java.net.UnknownHostException;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Name;
import org.xbill.DNS.PTRRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.ReverseMap;
import org.xbill.DNS.Type;

public class FindDomain {

 public static void main(String[] args) {
   try {
    InetAddress address = InetAddress.getLocalHost();
    System.out.println("LOCAL ADDRESS : " + address.getHostAddress());
    System.out.println("LOCAL HOST : " + address.getHostName());

    InetAddress ipAddress = java.net.InetAddress.getByName("www.javadiscover.com");
    String ip = ipAddress.getHostAddress();
    System.out.println("\nJAVADISCOVER IP : " + ip);

    final InetAddress ip2 = InetAddress.getByName("74.125.135.121");
    final byte[] bytes = ip2.getAddress();
    final String host = getHostByIPAddress(bytes);
    System.out.println("\nJAVADISCOVER HOST : " + host);

   } catch (UnknownHostException e) {
    System.out.println("Host NOT Avaialble");
   }

  }

  public static String getHostByIPAddress(byte[] addr) throws UnknownHostException {

   Name name = ReverseMap.fromAddress(InetAddress.getByAddress(addr));

   // OPEN DNS SERVERS
   final String[] openDNS = new String[] {"208.67.222.222", "208.67.220.220"};
   final Resolver resolver = new ExtendedResolver(openDNS);
   final Lookup lookUp = new Lookup(name, Type.PTR);
   lookUp.setResolver(resolver);
   Record[] records = lookUp.run();
   if (records == null) {
    throw new UnknownHostException();
   }
   return ((PTRRecord) records[0]).getTarget().toString();
  }
}


OUTPUT:


LOCAL ADDRESS : 10.70.50.16
LOCAL HOST : anandkumar-inl

IP : 74.125.135.121

HOST : ni-in-f121.1e100.net.








How to access Abstract class concrete methods in java?


Basically we can't create instance for Abstract class. In that case if we need to access the concrete methods of abstract class then we need to extend abstract class to other class and by instance of those classes we call Abstract class concrete methods.

In other way we can create anonymous class and by using those instance we can call abstract class methods. Lets see example for both the approaches below,

My Abstract class:


public abstract class MyAbstract {
 
 public abstract void add();
 
 public void test(){
  System.out.println("Inside ABSTRACT class");
 }
}


Using Instance of other class:


public class MyTestClass extends MyAbstract{
 
 @Override
 public void add() {
  System.out.println("Inside add method");
 }
 
 public static void main(String[] args) {
  
  MyTestClass obj  = new MyTestClass();
  obj.test();
  obj.add(); 
 }
}

OUTPUT:


Inside ABSTRACT class
Inside add method



Using anonymous class:



public class MyTestClass {
 
 public static void main(String[] args) {
  
  MyAbstract obj = new MyAbstract() {
   
   @Override
   public void add() {
    System.out.println("Inside add method");
    
   }
  }; 
  obj.test();
  obj.add();   
 }
}


OUTPUT:


Inside ABSTRACT class
Inside add method







Difference between HashMap and HashTable in Java


Map is one of the important Interface in Java Collections and Maps contains key and value which always stores unique keys and values. Both HashMap and Hashtable implements Map interface and works based on hashing algorithm. 

Even HashMap and Hashtable implements Map interface but there are few important difference between these. Before using HashMap and Hashtable in application we need to know the functionality of both, by mistake if we select incorrect implementation class then it leads to lot of performance impact and error in our application. 

From JDK 1.4 onwards Hashtable included in Collection
Lets see few important difference between HashMap and Hashtable in Java.


Difference between HashMap and Hashtable.

  • First important difference between HashMap and Hashtable is, Hashtable is thread-safe (by default synchronized) and HashMap is not thread-safe.
  • HashMap allows null key and null value, but Hashmap won't allow null key and value which will give runtime NullPointerException.
  • As performance wise HashMap will be faster than Hashtable since its not synchronized. 
  • Iterator in HashMap class is a fail-fast iterator and enumerator in Hashtable is fail-safe and throw ConcurrentModificationException if any other Thread modifies.


Alternate for Hashtable:

If we need to use HashMap with thread-safe then we can convert HashMap to synchronized HashMap or we can for ConcurrentHashMap class. How to convert HashMap to synchronized HashMap have seen in our earlier tutorial.

Below are simple example for HashMap and Hashtable.

HashMap:


public  class MyTestClass {

 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMap<String, String>();
  hm.put(null, null);
  hm.put("1", "one");
  System.out.println("Value : "+ hm.get(null));
  
  // Converting HashMap to Synchronized HashMap
  hm = Collections.synchronizedMap(hm);  
 }
}


Hashtable:


public  class MyTestClass {

 public static void main(String[] args) {
  
  Map<String, String> ht = new Hashtable<String, String>();
  
  // gives NullPointerException
  //ht.put(null, null);
  
  ht.put("1", "one");
  System.out.println("Value : "+ ht.get(null));
 }
}