Wrapper classes in Java


We all many know that Java is Object Oriented programming and in the world of Java everything will be considered as an Object. In that case when we see about primitive datatypes in java those are all not under any classes in Java. And also before JDK 1.5 all data structures used to store only Objects. In those cases they have came with Wrapper classes for all 8 primitive datatypes in Java. As a name represents "Wrapper" it wraps around the primitive datatype and gives the Objects. 

How these wrapping are done in Java from primitive to Wrapper class objects?
Wrapping done by using constructor of each classes. Each class will accept different types of primitive datatype or Object as a constructor parameter and those parameters are converted to Objects. All these 8 Wrapper classes comes inside java.lang package and immutable classes. Apart from these 8 Wrapper classes other wrapper classes like BigDecimal and BigInteger are not one of the primitive wrapper classes and are mutable. 

Below are the list of 8 primitive datatypes and their corresponding Wrapper classes along with their constructor parameter types.

Primitive typeWrapper classConstructor Arguments
byteBytebyte or String
shortShortshort or String
intIntegerint or String
longLonglong or String
floatFloatfloat, double or String
doubleDoubledouble or String
charCharacterchar
booleanBooleanboolean or String


Bellow is the Wrapper class hierarchy


Wrapper classes in Java

The Byte, Short, Integer, Long, Float, and Double wrapper classes are all sub-classes of the Number class. Lets see small example for converting primitive datatype to Object and from Object to primitive type. 


public class WrapperTest {
 
 public static void main(String[] args) {
  
  int _int = 1;
  byte _byte = 2;
  short _short = 3;
  long _long = 4;
  float _float = 5.5f;
  double _double = 6;
  char _char = 'a';
  boolean _boolean = true;
  
  Integer w_int = new Integer(_int); 
  Byte w_byte = new Byte(_byte);
  Short w_short = new Short(_short);
  Long w_long = new Long(_long);
  Float w_float = new Float(_float);
  Double w_double = new Double(_double);
  Character w_char = new Character(_char);
  Boolean w_boolean = new Boolean(_boolean);
  
  System.out.println("Printing Wrapper class");
  System.out.println("Integer      : "+w_int);
  System.out.println("Byte         : "+w_byte);
  System.out.println("Short        : "+w_short);
  System.out.println("Long         : "+w_long);
  System.out.println("Float        : "+w_float);
  System.out.println("Double       : "+w_double);
  System.out.println("Character    : "+w_char);
  System.out.println("Boolean      : "+w_boolean);
  
  int _int1 = w_int;
  byte _byte1 = w_byte;
  short _short1 = w_short;
  long _long1 = w_long;
  float _float1 = w_float;
  double _double1 = w_double;
  char _char1 = w_char;
  boolean _boolean1 = w_boolean;
  
  System.out.println("\nPrinting Primitive datatype from Wrapper class");
  System.out.println("int          : "+_int1);
  System.out.println("byte         : "+_byte1);
  System.out.println("short        : "+_short1);
  System.out.println("long         : "+_long1);
  System.out.println("float        : "+_float1);
  System.out.println("double       : "+_double1);
  System.out.println("char         : "+_char1);
  System.out.println("boolean      : "+_boolean1);
 }
}

OUTPUT:


Printing Wrapper class
Integer      : 1
Byte         : 2
Short        : 3
Long         : 4
Float        : 5.5
Double       : 6.0
Character    : a
Boolean      : true

Printing Primitive datatype from Wrapper class
int          : 1
byte         : 2
short        : 3
long         : 4
float        : 5.5
double       : 6.0
char         : a
boolean      : true


Difference between ArrayList and Vector in Java

 

ArrayList and Vector are the important collection classes which used in Java. And also widely asked in interview about their difference and similarities between these 2 classes. Before looking into the difference and similarities between these two classes lets discuss some of the collection classes and interface in Java Collection framework. Below hierarchy diagram will give you the brief structure of the interface and classes in Collection framework like what are all the classes derived from different interface. 


Java Collections


Similarities:

  • Both ArrayList and Vector implements List interface.
  • Both ArrayList and Vector are ordered collection and allow duplicate and null values.
  • Both ArrayList and Vector are index based and values can retried by using index, which means internally it uses array as data structure to store the values. 
  • While initializing both ArrayList and Vector size will be 10 by default.


Differences: 

  • Vector is thread-safe and ArrayList is non thread-safe, which means Vector is synchronized and ArrayList is not. Suppose if we using any multi-threading or concurrent process then Vector will be best suited and other ways ArrayList will be best.
  • Performance wise Vector will be slow since its synchronized. 
  • Vector introduced in first version of JDK and from JDK 1.2 its merged with Java Collection framework and its implements List interface. Where as ArrayList introduced in JDK 1.2 along with Collection framework
  • By default both ArrayList and Vector increment the size automatically. The difference is ArrayList will increments its array size by half of its size, where as Vector will doubles the size of its array when its size is increased by default suppose if we didn't set the capacity Increment size.
  • Vector's capacity size increment can be set to any number when we initialize  where as ArrayList we can't. 


ArrayList initialize:

ArrayList<String> arr = new ArrayList<String>(); // Default initialCapacity = 10

ArrayList<String> arr = new ArrayList<String>(100); // initialCapacity = 100

Vector initialize:

Vector<String> vec = new Vector<String>(); // Default initialCapacity = 10

Vector<String> vec = new Vector<String>(100); // initialCapacity = 100

Vector<String> vec = new Vector<String>(100,10); // initialCapacity = 100 and capacityIncrement = 10


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 ...