Tuesday, April 16, 2013

Blank final variable and static blank final variable


Blank final variable:-

The final variable that is not initialized during the time of declaration is called blank final variable. These variables need to be initialized either in intializer block or in Constructor.

Static blank final variable:-

The static final variable that is not initialized during the time of declaration. These variables need to be initialized in static initializer block. Static initializer block is the only place where a static blank final variable can be initialized.

public class Test {

       static final int varStatic;
       final int var1;
       final int var2;
       static
       {
              System.out.println("In static initializer block");
              varStatic = 0;
       }
       //Initializer block
       {
              System.out.println("In initializer block");
              var1 = 0;
       }
       Test()
       {
              System.out.println("In constructor");
              var2 = 0;
       }
       public static void main(String[] args)
       {
              System.out.println("In Main");
       }

}



Order of execution of Java class

Below is the order of execution of a java class

1)Static initializer block
2)main method
3)Initializer block
4)Constructor

Initializer block and Constructor will be executed only when we create an object.

public class Test {

       static
       {
              System.out.println("In static initializer block");
       }
       //Initializer block
       {
              System.out.println("In initializer block");
       }
       Test()
       {
              System.out.println("In constructor");
       }
       public static void main(String[] args)
       {
              System.out.println("In Main");
       }

}


O/P:-
In static initializer block
In Main

public class Test {

       static
       {
              System.out.println("In static initializer block");
       }
       //Initializer block
       {
              System.out.println("In initializer block");
       }
       Test()
       {
              System.out.println("In constructor");
       }
       public static void main(String[] args)
       {
              System.out.println("In Main");
              Test t = new Test();
       }
}

 O/P:-
In static initializer block
In Main
In initializer block
In constructor


Thursday, April 11, 2013

Difference between == and equals()


== operator compares the object reference and returns true if the reference of both the objects are same. i.e. Both are same object.
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
Integer i3 =  i1;
System.out.println(i1==i2);
System.out.println(i1==i3);

O/P:-
false
true

equals() method of Object class is same as == operator. i.e. it compares the reference. But we can override it to write our business logic and return TRUE or FALSE accordingly. For example String class and Integer class have overridden equals methods to return true if the value of objects are equal.
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
             
System.out.println(i1==i2);
System.out.println(i1.equals(i2));

O/P:-
false
true

Monday, April 8, 2013

Equal assignment operator vs clone()


Equal assignment operator

When we use assignment operator to assign one object to another a new object does not get created. Both the objects point to same reference. Only reference gets copied. Changes in any object will change the object reference and will be reflected for the other one. Comparison using (==) operator will return TRUE since both points to same reference. Needless to mention equal() also returns TRUE.
Default hashCode() of super class will return same result for both.

package com.deva;

public class Student implements Cloneable {
      
       private int age;
       private String name;
       private String dept;
       public String getDept() {
              return dept;
       }
       public void setDept(String dept) {
              this.dept = dept;
       }
       public int getAge() {
              return age;
       }
       public void setAge(int age) {
              this.age = age;
       }
       public String getName() {
              return name;
       }
       public void setName(String name) {
              this.name = name;
       }
      
       public static void main(String[] args) throws CloneNotSupportedException {
             
              Student student =new Student();
              student.age=25;
              student.name="deva";
              student.dept="CS";        
              Student student2 = student;
              student2.age = 35;
             
              System.out.println("Student1 detail "+student);
              System.out.println("Student2 detail "+student2);
              System.out.println("Student1 hashcode="+student.hashCode());
              System.out.println("Student2 hashcode="+student2.hashCode());
              System.out.println("== operator returns "+(student==student2));
              System.out.println("equals method returns "+(student.equals(student2)));         
                                 
       }
      
       @Override
       public String toString() {

              String s = "Age="+this.age+"  Name="+this.name+"  Dept="+this.dept;
              return s;
       }
}


O/P:-
Student1 detail Age=35  Name=deva  Dept=CS
Student2 detail Age=35  Name=deva  Dept=CS
Student1 hashcode=1523239031
Student2 hashcode=1523239031
== operator returns true
equals method returns true


Creation of Object using clone()

In case when we create an object using clone() method a separate object gets created with a different reference but with same properties. Changes to one object will not be reflected for other one since both the object has different reference. Comparison using (==) operator will return FALSE.
Default equals() method of parent class will also return FALSE and hashCode() of super class will return different result for both.

package com.deva;

public class Student implements Cloneable {
      
       private int age;
       private String name;
       private String dept;
       public String getDept() {
              return dept;
       }
       public void setDept(String dept) {
              this.dept = dept;
       }
       public int getAge() {
              return age;
       }
       public void setAge(int age) {
              this.age = age;
       }
       public String getName() {
              return name;
       }
       public void setName(String name) {
              this.name = name;
       }
      
       public static void main(String[] args) throws CloneNotSupportedException {
             
              Student student =new Student();
              student.age=25;
              student.name="deva";
              student.dept="CS";        
              Student student2 = (Student) student.clone();
              student2.age = 35;
             
              System.out.println("Student1 detail "+student);
              System.out.println("Student2 detail "+student2);
              System.out.println("Student1 hashcode="+student.hashCode());
              System.out.println("Student2 hashcode="+student2.hashCode());
              System.out.println("== operator returns "+(student==student2));
              System.out.println("equals method returns "+(student.equals(student2)));         
                                 
       }
      
       @Override
       public String toString() {

              String s = "Age="+this.age+"  Name="+this.name+"  Dept="+this.dept;
              return s;
       }
}


O/P:-
Student1 detail Age=25  Name=deva  Dept=CS
Student2 detail Age=35  Name=deva  Dept=CS
Student1 hashcode=925838130
Student2 hashcode=2042428395
== operator returns false
equals method returns false

Thursday, January 17, 2013

java.util.Arrays.ArrayList

We are not discussing about the ArrayList class which is there in java.util package.

The ArrayList class that comes under java.util.Arrays is a private static nested class inside Arrays class.
This class implements List interface and extends AbstractList class.

It doesnot provide implementation for all the methods of List Interface. Infact it provides implementation to very few methods.

Methods in Arrays$ArrayList:-

public boolean contains(Object object)
public E get(int location)
public int indexOf(Object object)
public int lastIndexOf(Object object)
public E set(int location, E object)
public int size()
public Object[] toArray()

So if we will try access any other methods of List using runtime polymorphism it will access the method in AbstractList class. Hence throw an Exception if it is thrown in the AbstractList class.

Ex:- If we try to access add(Object obj) or remove(int location) it will throw UnsupportedOperationException.

Lets consider below scenario

List<String> list = Arrays.asList("tom","pom","kom","bom");
Iterator<String> i = list.iterator();
while(i.hasNext())
{
if(i.next().equals("pom"));
i.remove();//Exception thrown at this line
}


The above code will compile successfully but exception will be thrown at runtime when we will try to invoke remove();

Reason:- When we invoke remove() Iterator tries to invoke the remove(int location) of ArrayList class which is there in Arrays class. Since ArrayList class of Arrays class does not provide implementation for remove(int location) method it invokes remove(int location) of AbstractList class. Hence throws an UnsupportedOperationException.






Iterator and Iterable

Coming soon....

Saturday, January 5, 2013

Collection in Java

Collection is a data structure which provides us a way to store a group of Objects in a single variable.


Collection in Java is nothing but an API that has been provided by JRE in rt.jar under java.util package. This API makes the operations like searching, sorting, addition, delete easier for us.

In Collection we have two major Interfaces
1)Collection
2)Map

Lot many implementing classes and Interfaces are there in collection framework but we will discuss few commonly used ones.
Below provided is a very small portion of Collection and Map hierarchy which is used in daily life very frequently.










The basic difference between a List and a Map is List contains a group of Objects where Map contains Kay and value pair.

Ex:-

Without Generics

List li = new ArrayList();
Map map = new HashMap();
With Generics

List<Object> li = new ArrayList<Object>();
Map<Object,Object> map = new HashMap<Object,Object>();

Collection Interface hierarchy

Two very commonly used data structure under Collection hierarchy are List and Set. Both List and Set are Interfaces.
The basic difference between a List and Set is, List can contain duplicate element but Set cannot.

Frequently used concrete classes that Implement List

ArrayList :- This is the best preferred when we want to access elements form List very frequently. This is not synchronized. We will get the data in same order in which these were inserted to the ArrayList. We can add null value to ArrayList.

Syntax:- 
List<Object> li = new ArrayList<Object>();

LinkedList:- This is also one concrete class which implements List Interface. Doing operations like adding deleting is faster in LinkedList. We can add null value to LinkedList. Takes more memory that ArrayList.
Specialty of LinkedList is adding an element at a particular index in the list is much faster than the ArrayList.
It maintains ordering.i.e.We will get the data in same order in which these were inserted

Syntax:-
List<Object> li = new LinkedList<Object>();


Vector:- This is also another concrete  class which implements List.  This roughly equivalent to ArrayList . We can add null value to Vector. It maintains ordering.
The only difference is Vector is synchronized where as ArrayList is not synchronized.

Syntax:- 
List<Object> li = new Vector<Object>();

Q) When to use LinkedList , ArrayList and Vector?

Ans:- If you need to do operations like add, remove frequently or add an element at a particular index in the List you should go for in LinkedList.

If you are simply accessing the the elements from the List its better to use ArrayList.

Vector is most useful is a Thread safe application.

Frequently used concrete classes that Implement Set

HashSet:- This a concrete class that implements Set Interface. We can not add duplicate elements to it. We can add null value to HashSet. It does NOT maintain ordering. i.e. We may not get the data in same order in which these were inserted

LinkedHashSet:- This is a concrete class that implements Set Interface and extends HashSet. This is the combination of HashSet and LinkedList. We can add null value to LinkedHashSet.


TreeSet:- This is a concrete class which implements NavigableSet Interface which comes under Set hierarchy. So TreeSet also implements Set Interface. Specialiy of Tree set is, its naturally ordered. Irrespective of the order in which elements will be added but we will get the elements in sorted order.
We can NOT add null values to it.

Map Interface hierarchy

Map contains Key value pair where key is unique. 

Q)What will happen if we will add a pair with an existing key.
Ans:- The existing value will be overridden with the new value.

Frequently used concrete classes that Implement Map


Hashtable:- This Implements Map interface. This is synchronized, hence most useful in Thread safe application. We can NOT add null for key or value.

HashMap:- This is the most used concrete class that implements Map Interface.  This is very similar to Hashtable except this is not Synchronized and we can add null for key or value.

LinkedHashMap:- This Implements Map interface and extends HashMap. This is a combnination of LinkedList and HashMap. We can add null for key or value.

TreeMap:- It implements NavigableMap Interface and NavigableMap Interface comes under Map hierarchy. Hence TreeMap implements Map Interface. Irrespective of the sequence we will add the key value pairs, those will be sorted in ascending order for Keys.
We can NOT add null for key or value.

Use of Iterator in Java

To know about Iterator please visit Iterator and Iterable.

Iterator can be used to traverse through a Collection.

Ex:-



List<String> list = new ArrayList<String>();
list.add("tom");list.add("bob");list.add("jon");list.add("james");

Iterator<String> i = list.iterator();
String str = "bob";
String local;
while(i.hasNext())//Returns true if the iteration has more elements.
{
local = i.next(); // Returns the next element in the iteration
System.out.println(local);
if(str.equals(local))
{
i.remove();//Removes from the underlying collection the last element returned by the iterator
}
}



Note:- In above example if we use 
List<String> list = Arrays.asList("tom", "jon","bob","james"); at first line it will throw an exception UnsupportedOperationException when we call remove() of Iteretor. For more information please visit ArrayList in Arrays class.



Q:- What if I call remove() first before calling next(); ?

Ans:- I will throw IllegalStateException if we call remove() before calling next();.

for each loop in Collection

This is a new feature of Java that was introduced in Java 1.5. It is used to traverse thorough a Collection or an Array.

Ex with List:-

List<String> list = new ArrayList<String>();
list.add("tom");list.add("bob");list.add("jon");list.add("james");
Iterator<String> i = list.iterator();

for(String local:list)
{
System.out.println(local);
}




Q & A

Q)Are all the methods in Vector class are synchronized?
Ans:-No. Few are synchronized and few are not.
Ex:- add(int index, E element)- NotSYnchronized but add(E e) is synchronized.
remove(Object o) is not synchronized but remove(int index) is synchronized.

Q) How can I sort a List ?
Ans:- There are two ways to sort a list.
1)Use TreeSet. Accordiong to the property of TreeSet the values will be inserted to the list in the sorted order.
2)By using the static method sort(List<T> list) Collections class.

List<Test> li =new LinkedList<Test>();
Collections.sort(li);
Note:- Element of the List should Implement Comparable Interface. Here Test class should Implement Comparable Interface.

Q) Can I add a Object to a List<String> . i.e.List of String 

Ans:-
Whenever this kind question comes we should keep one thing in mind i.e. Java does not do downcasting automatically but it does upcasting. We have to do downcasting mannually.So when we add an Object to List<String> it throws compilation error. Because it tries to cast Object to String. Since downcasting in java is not a default property it will not let us add an Object to List<String>. But if we will add a String to List<Object> it will compile successfully.

List<String> list = new ArrayList<String>();
list.add(new Object());// Compilation error thrown at this line
Compilation error is thrown at 2nd line in above code.

List<Object> list = new ArrayList<Object>();
list.add(new String());

The above code compliles successfully.