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

Monday 6 October 2014

Exceptions with method overriding in java

In java methods can throw the different checked/unchecked exceptions, this seems to be simple as long as we are talking about the single methods in java but when we deal with method overriding in java the concept of exception which can be thrown by overriding or overridden method are bit tricky. The overriding method cannot throw the new/broader exception than the overridden method is throwing but this case is only true for checked exception and not true for unchecked/runtime exception.

If overriding method is throwing a checked exception which is new/broader than your overridden method exception then your code will not compile.

The combination of base class overridden method and derived class overriding method with respect to exceptions can be categorized into the below five cases as:

1.    Base class method throwing no exception and derived class method is throwing exception.
       •    In case of checked exception code will not compile
       •    In case of runtimeException code will work fine.

2.    Base class method throwing less newer/broader exception than derived class method is throwing.   
       Suppose base class overridden method is throwing ArithmeticException and derived class overriding
       method is throwing general Exception so then code will not compile.
      •    In case of checked exception code will not compile
      •    In case of runtimeException code will work fine.

3.    Both base and derived class overridden method throw same exception
       •    Code will compile and run perfectly in both cases of checked and unchecked exception.

4.    Base class overridden method throwing newer/broader exception than derived class overriding method.
       Suppose base class overridden method is throwing general Exception and derived class overriding
       method is throwing ArithmeticException so then code will compile and work fine.
       •     Code will compile and run perfectly in both cases of checked and unchecked exception.

5.    Base class overridden method is throwing exception but Derived class overriding method is not 
       throwing  exception.
      •    Code will compile and run perfectly in both cases of checked and unchecked exception.

Monday 29 September 2014

How to compile .JRXML file and produce .jasper file with JAVA code

The Jasper Report design file specifies the layout and appearance of the report and they works best with the .JRXML extension files. We use iReport to deal with the jrxml reports but sometimes we need to compile JRXML file through our java code. We can do this with the help of net.sf.jasperreports package.
Change the path of the JRXML and jasper files in below code and run this code to compile any JRXML file and generate jasper report.

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;


public class compileJasper{

public static void main(String[] args)
    {
    //    below code will compile the jasper file which is located on path given below
        try {
    JasperCompileManager.compileReportToFile("PathOfTheJRXMLFile(which needs to be compiled)" ,"PathOfJasperFile(Where to save generated jasper file)");
        } catch (JRException e) {
           
        }
    }
}

What is the difference between JDK, JRE, JVM


This question is very common in all java interviews. Basically it checks the candidates knowledge of how java works. This question can be extended in further questions like java class loader and how class files are loaded in java etc. but for that firstly we should know that what these three terms actually means

JDK : -
JDK means Java Development Kit. JDK contains Java Run-time Environment (JRE) , Compilers and debuggers required to develop applets and applications.

JRE :-
JRE is subset of JDK, It contains Java Virtual Machine (JVM) along with Java Class Libraries which implement the Java application programming interface (API) form the Java Runtime Environment (JRE).

JVM : -
Java Compilers compile JAVA source code and create a .class file having the byte code. Java Virtual Machine(JVM) interpreters Java byte code and send necessary commands to underlying hardware or Just in time compiled to native machine code and execute it directly on the underlying hardware . If we have already compiled code of java (.class files) then we just only needs the JVM to interpreters .class file codes.

Friday 23 August 2013

How to sort HashTable and HashMap in java collection?



Map interface does not provide a direct sort() method like collection interface so we have to sort them manually. We took the example of HashMap and HashTable for sorting. HashMap is by default sorted on the basis of Key but HashTable is not sorted at all. 

1 - Hashtable sorting:
We have two ways to sort HashTable.
  • On the basis of key.
HashTable  --> TreeMap or HashMap
  • On the basis of value.
HashTable --> ArrayList --> Comparator sorting of ArrayList --> convert to map again

Example Code:-
 import java.util.*;
public class demoSortHashTable
{
 public static void main(String s[])
        {
            Map mp = new Hashtable();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
          
            System.out.println("Print HashTable contents without sorting");
            System.out.println(mp);

           //First way to sort hashmap by converting it to TreeMap(it will sort on the basis of key)
           System.out.println("HashTable contents after sorting by key");
           Map mpt = new HashMap(mp);
           System.out.println(mpt);

           //Second way to sort hashmap by converting it to List(it will sort on the basis of value also)
           System.out.println("HashTable contents after sorting by value");
           //Converting HashMap to ArrayList
           List lt = new ArrayList(mp.entrySet());
           //Sorting the ArrayList with Comparator
           Collections.sort(lt, new Comparator() {
                                                public int compare(Object o1, Object o2) {
                                                                return ((Comparable) ((Map.Entry) (o1)).getValue())
                                       .compareTo(((Map.Entry) (o2)).getValue());
                                                }
                                });
            //Putting the value of the List into LinkedHashSet
            Map mp1 = new LinkedHashMap();
            Iterator it1 = lt.iterator();
            while (it1.hasNext())
             {
                 Map.Entry ent = (Map.Entry) it1.next();
                 mp1.put(ent.getKey(),ent.getValue());
             }
          System.out.println(mp1);
        }
}

Output:
Print HashTable contents without sorting
{4=Fourth, 3=Third, 2=Second, 1=First}
HashTable contents after sorting by key
{1=First, 2=Second, 3=Third, 4=Fourth}
HashTable contents after sorting by value
{1=First, 4=Fourth, 2=Second, 3=Third}



2 - HashMap sorting:
HashMap is sorted by default (on key) so we just need to sort it on the basis of Value if needed.

Example Code:
import java.util.*;
public class demoSortHashMap
{
 public static void main(String s[])
        {
            Map mp = new HashMap();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("HashMap contents are sorted on keys by default");
            System.out.println(mp);

          //Sort hashmap by converting it to List(it will sort on the basis of value also)
           System.out.println("HashMap after sorting by value");
           //Converting HashMap to ArrayList
           List lt = new ArrayList(mp.entrySet());
           //Sorting the ArrayList with Comparator
           Collections.sort(lt, new Comparator() {
                                                public int compare(Object o1, Object o2) {
                                                                return ((Comparable) ((Map.Entry) (o1)).getValue())
                                       .compareTo(((Map.Entry) (o2)).getValue());
                                                }
                                });
            //Putting the value of the List into LinkedHashSet
            Map mp1 = new LinkedHashMap();
            Iterator it1 = lt.iterator();
            while (it1.hasNext())
             {
                 Map.Entry ent = (Map.Entry) it1.next();
                 mp1.put(ent.getKey(),ent.getValue());
             }
          System.out.println(mp1);
        }
}

Output: -
HashMap contents are sorted on keys by default
{1=First, 2=Second, 3=Third, 4=Fourth}
HashMap after sorting by value
{1=First, 4=Fourth, 2=Second, 3=Third}

Thursday 22 August 2013

How to traverse HashMap and HashTable with iterator in Java Collection framework?



Traversing Map interface is bit differ from traversing the collection interface because we have key, Value pair is stored in map and we have to traverse them as a set. We use some properties of Map interface to do the work like Map.Entry, Map.entryset(), which are used to tackle key, value pair as set. We can get the value of key and value with getKey() and getValue() methods from object of Map.Entry type. Please see the program below to understand it more clearly.
In below examples, we traversed both HashMap and Hashtable. There is no difference between traversing of them, the only difference is the output of both program.  The HashMap produce a sorted output but Hashtable  produce a unsorted output (As per their properties).

1 - Traverse HashMap with Iterator Example:
import java.util.*;
public class demoTraverseHashMap
{
 public static void main(String s[])
        {
            Map mp = new HashMap();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("Print MAP contents without traversing");
            System.out.println(mp);


           System.out.println("Print MAP contents with Iterator traversing");
           Iterator it = mp.entrySet().iterator();
           while(it.hasNext())
           {
               Map.Entry pairs = (Map.Entry) it.next();
               System.out.println("Key : "+pairs.getKey()+", Value : "+pairs.getValue());
           }
        }
}

OutPut:
Print MAP contents without traversing
{1=First, 2=Second, 3=Third, 4=Fourth}
Print MAP contents with Iterator traversing
Key : 1, Value : First
Key : 2, Value : Second
Key : 3, Value : Third
Key : 4, Value : Fourth


2 - Traverse HashTable with Iterator Example:
 import java.util.*;
public class demoTraverseHashMap
{
 public static void main(String s[])
        {
            Map mp = new Hashtable();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("Print MAP contents without traversing");
            System.out.println(mp);


           System.out.println("Print MAP contents with Iterator traversing");
           Iterator it = mp.entrySet().iterator();
           while(it.hasNext())
           {
               Map.Entry pairs = (Map.Entry) it.next();
               System.out.println("Key : "+pairs.getKey()+", Value : "+pairs.getValue());
           }
        }
}

OutPut:
Print MAP contents without traversing
{4=Fourth, 3=Third, 2=Second, 1=First}
Print MAP contents with Iterator traversing
Key : 4, Value : Fourth
Key : 3, Value : Third
Key : 2, Value : Second
Key : 1, Value : First

Wednesday 24 July 2013

What is Comparator and Comparable interface in java and what are the differences between them?



The Array.sort() and Collections.sort() can sort array and arraylist on the basis of single values but Lists are meant to store objects and they can have multiple properties so if need to sort list on the basis of some other properties than we need to use Comparable and Comparator interfaces.

Basically, Collections.sort()  have two types in java collection framework .
  1. Collections.sort(List of objects of class which implements Comparable   or list of objects);
  2. Collections.sort(list of objects, object of class implementing Comparator);

Comparable Interface: When we use Collection.sort() with single arguments or first type of Collections.sort then it basically needs the object of the class and the class should implement Comparable interface of Java.lang package.Comparable interface of java has an abstract method compareTo(Class object) which need to be implemented every time the class implements the Comparable interface. This method is containing the logic for sorting the list on the basis of some property. It compares the property with object property and returns the integer type result as:
Positive    – this object is greater than object’s property
Zero          – Both properties are equal
Negative – this object is less than object’s property

Let‘s suppose that we have a class containing the employee data(Emp Name, Emp Age). Now we can sort the list on the basis of name as well as age with the help of Comparator (refer below example).

 import java.util.*;

class empData implements Comparable<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compareTo(empData obj)    {
         // return this.age - obj.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return this.name.compareTo(obj.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparable
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects which implements Comparable interface */
Collections.sort(list); 
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}
      
Comparator Interface: When we use Collection.sort() with two arguments or second type of Collections.sort then it basically needs the object of the class and the class should implement Comparator interface of Java.util  package. Comparable interface of java has an abstract method compare(Class object 1,class object2) which need to be implemented every time the class implements the Comparator interface. This method is containing the logic for sorting the list on the basis of some property. It compares the object2 property with object1 property and returns the integer type result as:
Positive    – Object1 property is greater than object 2 property
Zero          – Both properties are equal
Negative – Object1 property is less than object 2 property

Same above example can be recreated as below example to understand the concept of Cmparator sorting.

import java.util.*;

class empData implements Comparator<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compare(empData a, empData b){
         // return a.age - b.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return a.name.compareTo(b.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparator
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects  and object of the class which implement the comparator(it can be same class whose properties need to be sort or any other class implementing the comparator interface)*/
Collections.sort(list,new empData());
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}


Differences between Comparator and Comparable

S.No.
Comparable
Comparator
1
Comparable comes under JAVA.LANG Package
Comparator comes under JAVA.UTIL Package
2
It has an abstract method compareTo(class type variable)
It has an abstract method compare(class type variable1 ,class type variable2)
3
The class whose properties need to be sort must implement Comparable interface that’s why they provide natural ordering
The class whose properties need to be sort may or may not implement Comparator interface. Some other class can have the sorting logic or can implement Comparator interface.
4
It is called when Collections.sort(list) is called
It is called when Collections.sort(list, comparator) is called