Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Tuesday 23 July 2013

What is the difference between Checked and Unchecked Exception in Java?



Checked Exception: - All the exceptions which required to be catches and handled at the compile time otherwise a compilation error will be given are known as the checked exception. All checked exception is direct sub Class of Exception but not inherit RuntimeException.
Checked Exception are helpful in ensuring that programmer provide recovery strategy or at least handle the scenario gracefully which can fail the program execution.

Type of checked Exception:-
Following are some Examples of Checked Exception:

1.       IOException
2.       SQLException
3.       DataAccessException
4.       ClassNotFoundException
5.       InvocationTargetException

Advantages and Disadvantages of Checked Exception:-

1.       They help to execute the program by handling some known failure situations.
2.       In long programs, we can location and type of error by handling the proper exceptions.
3.       They are useful in writing the log files for a program.
4.       They make the code complex and less readable

Unchecked Exception:-
All the exceptions whose handling cannot be handled at compile time are known as the Unchecked Exceptions. They mostly arise due to programming errors like accessing method of a null object, accessing element outside an array boundary.  Unchecked Exceptions are direct sub Class of RuntimeException.

Types of Unchecked Exception:-
Here are few examples of Unchecked Exception:

1.       NullPointerException
2.       ArrayIndexOutOfBound
3.       IllegalArgumentException
4.       IllegalStateException


Some Important points:
1. Both Checked and Unchecked Exception are handled using keyword try, catch and finally.
2. In terms of Functionality Checked and Unchecked Exception are same.
3. Checked Exception handling verified during compile time.
4. Unchecked Exception are mostly programming errors
5. JDK7 provides improved Exception handling code with catching multiple Exception in one catch block and reduce amount of boiler plate code required for exception handling in Java.

Monday 22 July 2013

What is Assertion in Java?




According to Sun, we can use assertion to test our assumption about programs. That means it validates our program!
In another words we can say that assertions ensures the program validity by catching exceptions and logical errors. They can be stated as comments to guide the programmer. Assertions are of two types:

1.       Preconditions: Preconditions are the assertions which invokes when a method is invoked.
2.       Postconditions:  Postconditions are the assertions which invokes after a method finishes. 
Where to use Assertions?
We can use assertions in java to make it more understanding and user friendly, because assertions can be used while defining preconditions and post conditions of the program.

Example of AssertionExample.java

import java.util.Scanner;

public class AssertionExample
  {
 public static void main( String args[] )
  {
  Scanner scanner = new Scanner( System.in );

  System.out.print( "Enter a number between 0 and 20: " );
  int value = scanner.nextInt();
  assert( value >= 0 && value <= 20 ):
  "Invalid number: " + value;
  System.out.printf( "You have entered %d\n", value );
 }
  }

 Before running above example enable  the assertion at your environment with following command.
java -ea AssertionExample

What is Generics in java?




Arrays in Java have always been type safe. For example, an array declared as type integer can only accept integers (not String, Dog, Cat). But, collections are not like that. There is no syntax for declaring type safe collections before java 5. To create an Collection of a particular type java introduced Generics in java5.

ArrayList Without Generics

ArrayList lst = new ArrayList();

ArrayList With Generics

ArrayList<Integer>  lst = new ArrayList<Integer>();

Example Code:

import java.util.*;

public class demoCollection11
{
    public static void main(String s[])
    {
        System.out.println("ArrayList without Generics");
        ArrayList ar = new ArrayList();
        ar.add(10);
        ar.add(11);
        ar.add(12);
        Object a = ar.get(1);//Before generic it always return the object type
        System.out.println(ar);
        System.out.println("");
        System.out.println("ArrayList with Generics");
        ArrayList<String> ar1 = new ArrayList<String>();
        //ar1.add(10);   This will give error because ar1 list is of String type
        ar1.add("Ten");
        ar1.add("Eleven");
        ar1.add("Twelve");
       
        String str = ar1.get(1); //With generic, You can directly get the value in string type variable
        System.out.println(ar1);
    }
}

Output:

ArrayList without Generics
[10, 11, 12]

ArrayList with Generics
[Ten, Eleven, Twelve]

What is VarArgs or Variable length Arguments in java?

This is used when we don’t know how much argument should be passed to the Method but this is not a good practice in real time environment as it leads to maintenance problems. TO understand this more clearly please see the example below.

public class demoVarArgs
{
     void demoMethod(int a)
     {
         System.out.println("One argument demoMethod is called");
     }
     void demoMethod(int a,int b)
     {
         System.out.println("Two argument demoMethod is called");
     }
     void demoMethod(int...a)
     {
         System.out.println("Varible argument demoMethod is called");
     }

     public static void main(String s[])
     {
         demoVarArgs obj = new demoVarArgs();
         obj.demoMethod(1);
          obj.demoMethod(1,2);
           obj.demoMethod(1,2,3,4,5,6,7,8,9,10);
     }
}

Output:

One argument demoMethod is called
Two argument demoMethod is called
Varible argument demoMethod is called

In the above example there are three demoMethods with one ,two and variable number of arguments and we called the demoMethod by giving one, two and variable number of arguments. When it meets the exact number of argument defined in the method it called that particular method otherwise it always call method with variable number of arguments.