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

December 20, 2015

Unrechable catch block error in exeception handling


When we are using multiple catch blocks at that time the order of the catches are matter most. It means that all catch blocks must be from most specific one to most general ones. which is sub classes of Exception must come first and then the super classes. If we change the order of the catch block the compiler will give the error of unreachable block. Take a look at the following code snippet.

public class ExceptionTest
{
    public static void main(String[] args)
    {
        try
        {
            int i = Integer.parseInt("abc");   //This statement throws NumberFormatException
        }
  
        catch(Exception ex)
        {
            System.out.println("This block handles all exception types");
        }
  
        catch(NumberFormatException ex)
        {
            //Compile time error
            //This block becomes unreachable as
            //exception is already caught by above catch block
        }
    }
}

December 03, 2015

What is an Exception ?

  • An Exception is an abnormal condition that arises during the execution of any program. 
  • An exception is a run-time error. In computer languages that do not support exception handling, errors of the program must be checked and handled manually.
  • Java's exception handling avoids these problems by providing a wide range of exception classes. 
  • A java exception is an object that describes the exceptional (i.e., error) condition that has occurred in a program.
  • When an exceptional condition arises, an object representing that exception is created and thrown to method that caused the error.
Java exception handling is managed by the following five keywords:
  • try
  • catch
  • throw
  • throws
  • finally
The following is the basic block of simple exception handling in java:

try{
   //Block of code to be monitored
}
catch(ExceptionType1Object ob){
   //Exception handling code for ExceptionType1
}
catch(ExceptionType2Object ob){
   //Exception handling code for ExceptionType2
}
.
.
.
finally{
   //Block of code to be executed before try block ends
}

Basic description of the above block:
  • The code / program statement to be monitored for exception are to be written in try block.
  • If any exception occurs within try block, it is thrown and our code can catch that exception using catch block and handle it in some of the very user friendly manner.
  • System generated exceptions are automatically thrown by the Java run-time system. 
  • To manually throw an exception, we can use the throw keyword.
  • Any exception that is thrown out of a method must be specified using throws keyword.
  • The finally block is a block is executed compulsory. A code which we want to be executed for sure whether exception occurs or not, like releasing resources, closing database connections, closing stream connections, etc, we can write that code in finally block.

November 26, 2015

Interface in Java

By using the keyword interface we can fully abstract a class. That is, by using interface we can specify what a class must do, not how it does. By syntax of the interface are similar to the class, but they are not having any instance variables, and also the methods declared in the interface are not having any kind of body structure. In a simple meaning interfaces are generally used to create a kind of blue print.

Once an interface is created any number of classes can implement it and even particular one class can also implements any number of interfaces at any time.

To implement an interface a class must have to create complete set of methods declared in the interface. However each class is free to decide what to implement in the method of the interface.

Interface is generally used to achieve concept of multiple inheritance in java. This is because we can extends only one class at time, which does not allow to extend more than one class at a time. So the interfaces are in introduced in java, where after implements keywords in class we can write any number of interfaces in it. This is how the multiple inheritance is achieved in java.

By default methods declared in interface are public abstract and variables declared in interface are static final.

Difference between abstract and interface:

Difference abstract-interface

Map Interface

Map is very unique and very much useful interface of the collection framework and also a very helpful in very big and complex applications of the java technology.

Map is an interface which maintains data in Key,Value pair. Both key and value are type of Object. Which means we can make any type of data as Key and any type data as Value. But very important thing is that Map contains unique key. Each and every key has some value.

AbstractMap is the abstract class which implements Map interface and HashMap is the concrete sub class of  AbstractMap. TreeMap is an interface which implements SortedMap.

Following is the list of methods provided by Map interface.


  1. put(Object key, Object value)
  2. get(Object key)
  3. size()
  4. clear()
  5. isEmpty()
  6. putAll(Map)
  7. getKey()
  8. getValue()
  9. setValue()


Map.Entry Interface

Map.Entry interface is an interface which is nested interface of Map interface. It generally used for getting key and value from map separately. Following is a simple example which shows the use of Map.Entry interface.

import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

class MapDemo
{
public static void main(String[] ar)
{
HashMap hm = new HashMap();
hm.put("India",95);
hm.put("China",100);
hm.put("Srilanka",5);
hm.put("Austrila",70);

Set s = hm.entrySet(); // Method 1
Iterator i = s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
System.out.println("\n");
for(Object o : s) // Method 2
{
System.out.println(o);
}
System.out.println("\n");
for(Object o : s) // Method 3
{
Map.Entry me = (Map.Entry)o;
System.out.println(me.getKey() + " " + me.getValue());
}
}
}

Set Interface

Set is the interface having only a unique set of elements.

Sorted Set is an interface which extends from Set. It extends from collection interface.

Very important thing to remember in Set interface is there are no new methods available in Set other than Collection interface.

AbstractSet is the abstract class which implements Set interface. HashSet is concrete sub class of AbstractSet.

List Interface

A list is an ordered collection sometimes is also known as sequence. List may have contains duplicate values.
AbstractList is an abstract class which implements List interface. ArrayList, LinkedList, Vector are the concrete sub class of AbstractList.

As List interface implements the root interface (which is Collection) it has all the methods of Collection interface but also some new methods are there which is listed below:


  1. void add(int index, Object data)
  2. void set(int index, Object data)
  3. Object get(int index)
  4. Object remove(int index)
  5. int indexOf(Object data)
  6. int lastIndexOf(Object data)
  7. List subList(int start, int end)
  8. ListIterator listIterator()

Now there is a method listIterator() which return the reference of ListIterator. We can also use the simple iterator() of the Collection interface. But the ListIterator have some of the extra facility provided which is not in the Iterator interface.

ListIterator Interface

ListIterator is an interface which extends from Iterator. Using the ListIterator we can also add, set elements at the specified position which is not possible in the Iterator interface.
We can also get an index of the next elements using ListIterator and also can get the previous element while iterating in forward direction.
We can also make iterations in backward directions, which is also not possible in Iterator interface.
Following is the list of the methods provided by ListIterator interface :

  1. hasNext()
  2. next()
  3. remove()
  4. previous()
  5. preivousIndex()
  6. nextIndex()
  7. add()
  8. set()

Collection Framework in java

Java has a very huge variety of feature one of which is Collection interfaces.

Java has a rich Collection interfaces and Classes to use for the developer community. And now a days these collections are very much helpful to the developers for the storing multiple data.

Collection is something like the array but it is too different from the array. Main difference is array stores only one type of data in whole array, like if array is type of integer we can store only numeric values in it where as in a particular collection object we can store any type of data at a time.

Collection enables us to work with the group of objects.

Collection framework have main 3 types of interface

  1. List
  2. Set
  3. Map


Core interfaces of Collection Framework

From the above image we can see that root of Set and List interface is Collection interface. A Map is separate interface but it is to be in the collection framework.

There are some of the common method which is in Collection interface which we can use in all the sub interfaces of the collections. Methods are listed below:

  1. add()
  2. addAll()
  3. clear()
  4. iterator()
  5. remove()
  6. removeAll()
  7. size()

September 09, 2015

Type conversion in Java

Type conversion is very much necessary in the world of programming. We all know when it is needed. There are three types of type conversion in Java.

  1. Widening 
  2. Narrowing
  3. Mixed

  • Widening Conversion
The conversion from Sub to super data type is called the Widening Conversion. This conversion is also known as Implicit type conversion. This type conversion is automatically done by jvm.

The following type conversion is possible from one datatype to another datatype.
  1. byte to short, int, long, float, double
  2. short to int, long, float, double
  3. int to long, float, double
  4. long to float, double
  5. float to double

  int i = 123456789;
  float f = i;          // Widening conversion
  int j = (int) f;      // Narrowing conversion
  • Narrowing Conversion
The conversion from super to it's sub data type is called the Narrowing Conversion. This conversion is also known as Explicit type conversion. This conversion we need to do by our own. In this type conversion we need to do type casting otherwise compiler will give an error "Possible lose of Precision".

The following type conversion is possible from one datatype to another datatype.
  1. double to float, long, int, short, byte
  2. float to long, int, short, byte
  3. long to int, short, byte
  4. int to short, byte
  5. short to byte

   int i = 12345;
   short s = (short) i;

  • Mixed Conversion
The conversion from char to it's sub type and conversion from sub type of int to char is called mixed conversion. It is mixed type conversion because it contains narrowing and widening conversion.
The following type conversion is possible from one datatype to another datatype.
  1. byte to char
  2. short to char
  3. char to short, byte
    char c= 88;     //X
    System.out.println( c = (char)(c+2));  // will print Z

April 13, 2015

Java Features

There are following features of the java which we will going to understand one by one...


  1. Simple
  2. Object-oriented
  3. Platform-independent
  4. Secured
  5. Robust
  6. Multithreaded



  • Simple
Java is said to be a simple language it is because java is based on the very popular language C++ means the syntax of the Java language is based on C++, so the programmers of the C++ can easily be moved from C++ to Java. Even the C++ programmers will enjoy the codding java programs because as like C++ we need not to do any kind of cleaning process for unreferenced objects(like destructors in C++). It is done by JVM automatically by garbage collections.

  • Object-oriented
Java is an object-oriented language but not fully/pure object-oriented. There are lot's of dicussion on the StackOverflow about this topic. The truth is it is not fully object-oriented language. The main and very first reason is java is still supporting/uses the primitive type (int,float,long,double,etc). 

  • Platform-independent
Java is platform-independent language which means the program written/tested on a platform can run on any other platform. For example, assume we have written our first program "Hello World" in Windows platform after compiling and running it, take the ".class" of that program and run that on any other operating system like Mac or Linux having JRE(Java Runtime Environment) installed in it.

  • Secured
Java is also said to be a secure language. The reason is it doesn't support any type of pointers in our application. Programs will run inside the JVM unlike C++ which uses operating systems' runtime environment. 

  • Robust
Simply robust means strong/powerfull. Java uses a powerfull memory management. It is lack of pointers which avoids security problems.

  • Multithreaded
Java is a multithreaded language. Multi threading is a very important and very useful feature of java. When we want to execute two processes simultaneously at that time the multi threading will helpful. 

Above listed and explained features are important features of the java.

April 09, 2015

Hello World

In every language very first program was/is/will be "Hello World".

public class HelloWorld{
         public static void main(String[] args){
                  System.out.println("Hello World!!!!!");
         }
}

  • Write the above program in any editor (I recommend to use notepad++/notepad) and save it as HelloWorld.java
  • Now compile the program from command prompt using the command javac 
    • javac HelloWorld.java
  • After successfully compilation it will generate the .class file generate which we are going to run. by using java command from command prompt
    • java HelloWorld

April 08, 2015

Basic of Java

As we all know that the java is a very powerful, easy, and most using platform of the current IT world. Most of the MNCs are also using the Java platform to create the desktop application, web applications. 

For more details of the java you can visit the Wikipedia link : Java (Programming Language)

Java is a very easy to understand languages. Java is an Object oriented languages. The 4 pillars of java is following:
  1. Encapsulation
  2. Polymorphism
  3. Inheritance
  4. Abstraction
Java uses its JVM (Java Virtual Machine) for the garbage collections of the objects created in the programs or any external resources to be released we used in the programs.
The garbage collections is whole the automated process we cannot garbage manually.
But we can request the JVM to start the garbage collection. but in that also we can not sure that it will start the garbage collections.