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));
 }
}









Difference between Abstract Class and Interface


This is one of the important interview question ever asked in Java interviews like, What is the the difference between Abstract class and Interface? When we need to use Abstract class and Interface? etc., First lets walk through what is Abstract Class and Interface. 

Abstract Class:


Abstract class is a class which declared as abstract, may or may not contain abstract methods. Abstract method is a method which wont't have any method definition. So in this case abstract class can have abstract methods as well as concrete methods. Once we say these answer few other questions which may asked from interviewer are,


Abstract class can have class variable or not?

Answer: Yes.

Abstract class can have multiple abstract methods and concrete methods? 

Answer: Yes, abstract class can have any no. of abstract and concrete methods.

Abstract class can extend other abstract class and can implement interfaces?

Answer: Yes, It can extend any class and can implement N no. of interfaces. 

Abstract class can also be a Final class?

Answer: No, it can either one only. 

Abstract class can be instantiated?

Answer: No, Abstract class can not be instantiated directly. But we can instantiate by using anonymous class. 

Main thing which we need to remember is, if a class contains any abstract method then compulsory class needs to be declared as abstract.



Interface:
Interfaces will be declared only with method declarations, there will not be method definition. In general all methods are implicitly abstract methods in Interface. Suppose if a Interface declared without any method declaration or variable, then its a Marker Interface. As same as Abstract class few other questions which may be on Interface are,

Interface can have variable or not?
Answer: Yes we can have but it should be Final variable. 

Interface can extend other class ?
Answer: No, Interface can extends only other interfaces.

How many Interfaces can be extended in a single Interface?
Answer: Interface can extends multiple Interfaces like below

public interface MyInterface  extends FirstInterface, SecondInterface {

public int val = 10;

public void myMethod();
}


Difference between Abstract class and Interface?

  • Abstract class can have Abstract method and as well as concrete methods. But Interface always should will have Abstract methods. 
  • Overriding all the Abstract method is not mandatory while we extends Abstract class. But if its a Final class then we need to Override all abstract methods. On other hand when we implements Interface we need to Override all abstract methods in our class. Only in case of Abstract class we don't need to provide implementation (Override) for all methods in Interface. 
  • Abstract class methods can have any access modifiers. But Interface methods should be always public. 
  • As we seen above Abstract class and extends only one class, where as Interface can extends multiple Interfaces. 
  • Abstract class can have Final and non-Final variables. Where as Interface can contain only Final variables. 
  • Abstract class can have Constructors, but Interface cannot have Constructor.
  • As by performance Abstract class will be faster than Interface since it consumes little more time on routing to Override methods. 
  • When we add any new methods in Abstract class then the base classes won't get affected. But in case of Interface if we add any method then all implemented classes will get affected and need to implemented those new methods also.

When to use Abstract class and Interface in Java?

Whenever we talk about When to use Abstract class and Interface in Java will lead to a multiple questions and answers. So in that case programmer need to decide to choice his best in his design stage. Lets see few choices of using Abstract class or Interface according to our needs,

  • Abstract class is more suited for code reuse like inheritance, where as Interfaces are better suited for Type declaration.
  • Using Interface will be suitable if we feel API will be stable for quite long time.
  • Abstract classes are better if we add any methods in our future, since it won't break the code. 
  • Abstract class will be better when we have common method definition and also non public methods and variables. 
  • Interface will be better when we need similar to multiple inheritance. 
  • Best suitable for Template pattern will be Abstract class declaration. 
  • Prefer Interface for providing more design flexibility. 





Google Maps API with multiple marker


In our application or site we will be in need of showing Google MAP with markers of office or other location details. Here we will see simple example for showing a multiple animate overlay markers. Its a basic HTML code were everyone will be searching online. 

Lets see simple example like showing markers in Indian cities like New Delhi, Mumbai, Kolkata, Chennai, Coimbatore, Bangalore and Haldwani. Below is the code while shows marker in each cities. 








<html> 
 <head> 
   <title>Indian Cities </title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
 </head> 

 <body>
  <div id="india" style="width: 650px; height: 700px;"></div>

  <script type="text/javascript">
   
   var cities = [ ['New Delhi', 28.630657, 77.220154, 1],
           ['Mumbai', 19.059868, 72.880554, 2],
         ['Kolkata', 22.571240, 88.360291, 3],
         ['Chennai', 13.042734, 80.260620, 4],
         ['Bangalore', 12.967803, 77.590942, 5],
         ['Haldwani', 29.212430, 79.521790, 6],
         ['Coimbatore', 11.014352, 76.956482, 7] ];

   var map = new google.maps.Map(document.getElementById('india'), {
     zoom: 5,
     center: new google.maps.LatLng(23.322080, 82.134766),
     mapTypeId: google.maps.MapTypeId.ROADMAP,
     animation:google.maps.Animation.BOUNCE
   });

   var infowindow = new google.maps.InfoWindow();

   var marker;

   for (var i = 0; i < cities.length; i++) {  
     marker = new google.maps.Marker({
    position: new google.maps.LatLng(cities[i][1], cities[i][2]),
    animation:google.maps.Animation.BOUNCE,
    map: map
     });

     google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(cities[i][0]);
      infowindow.open(map, marker);
    }
     })(marker, i));
   }
    </script>
 </body>
</html>


Difference between String, StringBuffer and StringBuilder


In this tutorial we will see about difference between String, StringBuffer and StringBuilder. The most important difference that String Object is immutable but whereas StringBuffer/ StringBuilder are mutable. 

So what is immutable and mutable?
Once a value assigned to the String Object then the values can't be modified or changed is called as immutable class. On the other end the values can be changed and modified is called as mutable class.

How String works in Java?
Since String is immutable class we can't change the values once we placed in String Object. But we are able to modify the String value in Java and how its possible? Yes, whenever we modify a String Object new Object will be created. Below example will explain more details on how String works in Java.

String val = "My";
val = val + " Friend";
System.out.println(val);

Output of above code will be "My Friend". We assume that value of "val" gets concatenated. But internally Java creates Object for every String operation which we does. In Java we can create String Object by 2 ways like 

Using "new" operator:
String val = new String("My");

Using String Literal:
String val = "Friend";

Since String creates Objects at each time, we need to switch to StringBuffer or StringBuilder whenever we does String concatenations to avoid multiple String Objects creation and to increase our application performance.

Internally StringBuilder and StringBuffer or mutable, then what is the difference?
If we go back to JDK versions StringBuffer introduced in JDK 1.4 and StringBuilder introduced in JDK 1.5 version. 
Other main difference between StringBuffer and StringBuilder are synchronization. Internally StringBuffer is synchronized and StringBuilder is non-synchronized. Synchronized means it is thread safe and we can use when we implement any multi-threading operations, only one thread can modify StringBuffer at a time. Whereas StringBuilder is not thread safe.

Lets see how to create StringBuffer and StringBuilder

StringBuffer:
StringBuffer str = new StringBuffer();
str.append("My");
str.append(" Friend");
System.out.println(str);

StringBuilder:
StringBuilder str = new StringBuilder();
str.append("My");
str.append(" Friend");
System.out.println(str);