Saturday 31 March 2012

instanceof operator in Java

The instanceof operator compares an object to a specified type. You can use it to test at run-time if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The syntax of the instanceof operator is
Object_reference instanceof ClassName/InterfaceName

The instanceof operation returns boolean value ,either true or false.

The instanceof returns true, if the object referred to by the variable on the left side of the operator passes the IS-A test for the class or interface type on the right side.
Even if the object being tested is not an actual instantiation of the class type on
the right side of the operator, instanceof will still return true if the object being
compared is assignment compatible with the type on the right.


At compile time it checks whether the type of reference variable on the left and the class or interface on the left are in the same inheritance hierarchy.Else compile-time error occurs.For example

Thursday 29 March 2012

ClassCastException in Java

public class ClassCastException
extends RuntimeException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. i.e.Thrown when attempting to cast a reference variable to a type that fails the IS-A test.

Before discussing more about ClassCastException let us go through reference variable casting.

Reference Variable Casting

Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.The compatible data types means they should follow the following contracts.

1. Both the reference variables types should be in the same inheritance hierarchy.Else compile-time error occurs.
2. When attempting to cast a reference variable to a type that should pass the IS-A test.Else run-time error occurs ,i.e. throws ClassCastException.

Sunday 25 March 2012

How and Why to override the toString() method in Java

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a super class so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of toString() method. We will discuss why it is necessary to override toString method and how we can override it.

The toString() method in the Object class is used to display some information regarding any object.The toString method is widely implemented. It provides a simple, convenient mechanism for debugging classes during development.When debugging, you want to be able to print a human readable representation of your object.It is widely used for logging.
The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.



Friday 23 March 2012

How HashMap works in Java ?

In computer science, a hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys (e.g., a person's name), to their associated values (e.g., their telephone number). Thus, a hash table implements an associative array. The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought.

Ideally, the hash function should map each possible key to a unique slot index, but this ideal is rarely achievable in practice (unless the hash keys are fixed; i.e. new entries are never added to the table after it is created). Instead, most hash table designs assume that hash collisions—different keys that map to the same hash value—will occur and must be accommodated in some way.The Java uses

Separate chaining collision resolution strategy to handle such events.

Wednesday 21 March 2012

Overriding hashCode() method in Java or Why always override hashcode() if overriding equals()?

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a superclass so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of hashCode() method. We will discuss why it is necessary to override hashCode method,Why always override hashCode() if overriding equals() and how we can override them.

Default implementation of hashCode() in Object class

The signature of hashCode is:

public int hashCode()

How and Why to override the equals and hashCode methods in Java

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a superclass so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of equals() and hashCode() method. We will discuss why it is necessary to override these methods and how we can override them.

Default implementation of equals() in Object class

The default version of equals method present in the Object class has the same behavior as the == operator which in turn simply checks if two reference variables are referring the same objects.Consider x and y, two object references, then x.equals(y) comparing the memory addresses of the objects referenced by x and y (i.e. not the data of the objects).

Monday 19 March 2012

NullPointerException in Java with Examples


public class NullPointerException
 extends RuntimeException

Thrown when an application attempts to use null in a case where an object is required. These include:
  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object.

Examples for NullPointerException

1) Calling the instance method of a null object.

Sunday 18 March 2012

Difference between HashSet, LinkedHashSet and TreeSet in java

All three classes implement the Set interface and offer mostly the same functionality. The most important difference is the order in which iteration through the elements will happen:

HashSet makes absolutely not guarantees about the iteration order. It can (and will) even change completely when new elements are added.

TreeSet will iterate according to the "natural ordering" of the elements according to their compareTo()method (or an externally supplied Comparator). Additionally, it implements the SortedSet and NavigableSet interfaces.
SortedSet provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order. 
Several additional operations (first,last,subSet,headSet and tailSet) are provided to take advantage of the ordering.

Difference between HashMap, LinkedHashMap and TreeMap in java

All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:

HashMap makes absolutely not guarantees about the iteration order. It can (and will) even change completely when new elements are added.

TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo()method (or an externally supplied Comparator). Additionally, it implements the SortedMap and Navigable interfaces.

SortedMap interface provides a total ordering of Map keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySetkeySet and values methods). 

Saturday 17 March 2012

Which is Faster - LinkedList or ArrayList? or When to use LinkedList over ArrayList?

This article compares LinkedList and ArrayList and describes which is faster and when to use one over another with examples.

LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array.

Let us see the performance of ArrayList and LinkedList in different scenarios.

1) Retrieve an element from the list


     a)Retrieve elements at the beginning

import java.util.*;

public class Main {

public static void main(String args[]) {

ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < 100000; i++) {
arrayList.add(i);
}

Wednesday 14 March 2012

Use of LinkedHashMap or LRU(Least-Recently-Used) Caches using LinkedHashMap in Java

LinkedHashMap is a combination of hash table and linked list.This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.

The main applications of LinkedHashMap are given below

  • To produce a copy of a map that has the same order as the original.
  • LinkedHashMap is more efficient than TreeMap.
  • To build LRU(Least Recently Used) Caches.

Let us discuss about it one by one.

1) To produce a copy of a map that has the same order as the original.

 It can be used to produce a copy of a map that has the same order as the original, regardless of the original map's implementation:

Monday 12 March 2012

keySet(), entrySet() and values() in Java Map

java.util.Map<K,V> interface provides three methods keySet(), values() and entrySet() for retrieving keys, values and key-value pairs respectively.Let us discuss about it one by one.

public Set<K> keySet()

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

public Collection<V> values()

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support theadd or addAll operations.

Sunday 11 March 2012

Use of java.util.LinkedList or LinkedList as Stack, Queue and Double-Ended Queue

The java.util.LinkedList<E> class implements Collection<E>, Deque<E>, List<E> and Queue<E> interfaces .The LinkedList can be used as
  • stack 
  • queue
  • double-ended queue
Let us discuss about it one by one.

LinkedList as stack

The LinkedList provides the following methods to implement LIFO(Last-In-First-Out) stacks.

public void push(E e)

Pushes an element onto the stack represented by this list. In other words, inserts the element at the front of this list.If the element cannot be added at this time due to capacity restrictions, throws IllegalStateException(NOTE:LinkedList has no capacity restrictions).

Friday 9 March 2012

Why override equals() and hashCode() methods of HashMap keys in Java

The equals and hashCode methods are declared within the Object class.
Every Java class has Object as a superclass so by default equals and hashCode methods are provided in every java class.The Object class implementation of the equals method returns true only if both the reference variables are referring the same object. I.e. obj1.equals(obj2) returns true only if the objects obj1 and obj2 are referring the same object ,means here simply comparing the memory addresses of the objects not the state of it.The hashCode implementation of the Object class returns an integer value for each objects.But the problem here is that the returning hash code value is not depends on the state of the object.This is typically implemented by converting the internal address of the object into an integer.

In order to implement the hash-based collections we have to override both equals and hashCode methods else it might produce some unexpected and inefficient results.

We have to override the equals method in such a way that is is comparing the states of the objects not the memory addresses.

We have to override the hashCode method in such a way that the hash code value depends on the state of the object i.e. not simply on the memory address.