Saturday, 28 December 2013

Java Set Interface - A Tutorial

HashSet, LinkedHashSet and TreeSet implement the Set interface. Let’s look at examples of these collection classes.

1. Set Interface - Java Video Tutorial

Video Coming Soon..

2. HashSet

HashSet implements set interface. Sets do not allow duplicates. HashSet does not support ordering.

2.1 HashSet Example

Set<String> hashset = new HashSet<String>();


System.out.println(hashset);//[Sachin, Dravid]

Let’s try to add Sachin to the Set now. Sachin is Duplicate. So will not be added. returns false.

hashset.add("Sachin");//returns false since element is not added
System.out.println(hashset);//[Sachin, Dravid]

3. LinkedHashSet

LinkedHashSet implements set interface and exposes similar operations to a HashSet. Difference is that LinkedHashSet maintains insertion order. When we iterate a LinkedHashSet, we would get the elements back in the order in which they were inserted.

4. TreeSet

TreeSet implements Set, SortedSet and NavigableSet interfaces.TreeSet is similar to HashSet except that it stores element’s in Sorted Order.

Set<String> treeSet = new TreeSet<String>();


Notice that the list is sorted after inserting Dravid.

//Alphabetical order
System.out.println(treeSet);//[Dravid, Sachin]

Notice that the list is sorted after inserting Ganguly.

System.out.println(treeSet);//[Dravid, Ganguly, Sachin]

//Sachin is Duplicate. So will not be added. returns false.
treeSet.add("Sachin");//returns false since element is not added
System.out.println(treeSet);//[Dravid, Ganguly, Sachin]

Objects that are inserted into a TreeSet should be comparable.

4.1 TreeSet - NavigableSet interface examples 1

TreeSet implements this interface. Let's look at an example with TreeSet. Note that elements in TreeSet are sorted.

TreeSet<Integer> numbersTreeSet = new TreeSet<Integer>();

NavigableSet interface has following methods.

Lower method finds the highest element lower than specified element. Floor method finds the highest element lower than or equal to specified element. Corresponding methods for finding lowest number higher than specified element are higher and ceiling. A few examples using the Set created earlier below.

//Find the highest number which is lower than 25

//Find the highest number which is lower than or equal to 25

//Find the lowest number higher than 25

//Find the lowest number higher than or equal to 25

4.2 NavigableSet subSet,headSet,tailSet Methods in TreeSet

TreeSet<Integer> exampleTreeSet = new TreeSet<Integer>();

System.out.println(exampleTreeSet);//[5, 25, 35, 55, 105]

All the three methods - subSet,headSet,tailSet - are inclusive with Lower Limit and NOT inclusive with higher limit.

In the sub set below, Lower Limit is inclusive - 25 included. Higher limit is not inclusive - 55 excluded.

//Get sub set with values >=25 and <55
SortedSet<Integer> subTreeSet = exampleTreeSet
        .subSet(25, 55);
System.out.println(subTreeSet);//[25, 35]

In the sub set below, Higher limit not inclusive - 55 excluded.

//Get sub set with values <55
SortedSet<Integer> headTreeSet = exampleTreeSet
System.out.println(headTreeSet);//[5, 25, 35]

//Get sub set with values >=35
SortedSet<Integer> tailTreeSet = exampleTreeSet
System.out.println(tailTreeSet);//[35, 55, 105]
//In the sub set, Lower limit inclusive - 35 included.

//Get sub set with value >=25 and <=55 (both inclusive parameters - true)
SortedSet<Integer> subTreeSetIncl = exampleTreeSet
        .subSet(25, true, 55, true);
System.out.println(subTreeSetIncl);//[25, 35, 55]

//Get sub set with value >25 and <55 (both inclusive parameters - false)
SortedSet<Integer> subTreeSetNotIncl = exampleTreeSet
        .subSet(25, false, 55, false);

//Get sub set with values <=55. Inclusive set to true.
SortedSet<Integer> headTreeSetIncl = exampleTreeSet
        .headSet(55, true);
System.out.println(headTreeSetIncl);//[5, 25, 35, 55]

//Get sub set with values >35. Inclusive set to false.
SortedSet<Integer> tailTreeSetNotIncl = exampleTreeSet
        .tailSet(35, false);
System.out.println(tailTreeSetNotIncl);//[55, 105]

All the sub set methods - subSet,headSet,tailSet - return dynamic sub sets. When original set is modified (addition or deletion), corresponding changes can affect the sub sets as well.

System.out.println(exampleTreeSet);//[5, 25, 35, 55, 105]
System.out.println(subTreeSet);//[25, 35]
System.out.println(headTreeSet);//[5, 25, 35]
System.out.println(tailTreeSet);//[35, 55, 105]

Let's now insert a value 30 into the exampleTreeSet. Remember that subTreeSet, headTreeSet, tailTreeSet are sub sets of exampleTreeSet.


System.out.println(exampleTreeSet);//[5, 25, 30, 35, 55, 105]
System.out.println(subTreeSet);//[25, 30, 35]
System.out.println(headTreeSet);//[5, 30, 25, 35]
System.out.println(tailTreeSet);//[35, 55, 105]

30 is in the range of subTreeSet and headTreeSet. So, it is printed as part of exampleTreeSet, subTreeSet and headTreeSet.

//Let’s now add 65 to the set

System.out.println(exampleTreeSet);//[5, 25, 30, 35, 55, 65, 105]
System.out.println(subTreeSet);//[25, 30, 35]
System.out.println(headTreeSet);//[5, 30, 25, 35]
System.out.println(tailTreeSet);//[35, 55, 65, 105]

65 is printed as part of exampleTreeSet and tailTreeSet.

Key thing to remember is that all the sub sets are dynamic. If you modify the original set,the sub set might be affected.

4.3 TreeSet - NavigableSet interface methods - pollFirst, pollLast and more

TreeSet<Integer> treeSetOrig = new TreeSet<Integer>();

System.out.println(treeSetOrig);//[5, 25, 35, 55]
//descendingSet method returns the tree set in reverse order
TreeSet<Integer> treeSetDesc = (TreeSet<Integer>) treeSetOrig
System.out.println(treeSetDesc);//[55, 35, 25, 5]

pollFirst returns the first element and removes it from the set.

System.out.println(treeSetOrig);//[5, 25, 35, 55]
System.out.println(treeSetOrig);//[25, 35, 55]
//In above example element 5 is removed from the set and also removed from the tree set.

pollLast returns the last element and removes it from the set.

System.out.println(treeSetOrig);//[25, 35, 55]
System.out.println(treeSetOrig);//[25, 35]

5. Java Set Interface Pdf Tutorial

Set Interface Interview Questions

Java Collections - A Tutorial

Collections can only hold Objects - not primitives.

1. Collections - Java Video Tutorial

Video Coming Soon..

2. ArrayList

ArrayList implements the list interface. So, ArrayList stores the elements in insertion order (by default). Element’s can be inserted into and removed from ArrayList based on their position.

Let’s look at how to instantiate an ArrayList of integers.

List<Integer> integers = new ArrayList<Integer>();

Code like below is permitted because of auto boxing. 5 is auto boxed into Integer object and stored in ArrayList.

integers.add(5);//new Integer(5)

Add method (by default) adds the element at the end of the list.

2.1 ArrayList of String Example

Below example shows how to create and use a String ArrayList. ArrayList can have duplicates (since List can have duplicates). size() method gets number of elements in the ArrayList. contains(Object) method checks if an element is present in the arraylist.

List<String> arraylist = new ArrayList<String>();

//adds at the end of list

//adds at the end of list
arraylist.add("Dravid");//[Sachin, Dravid]

//adds at the index 0
arraylist.add(0, "Ganguly");//[Ganguly, Sachin, Dravid]

//List allows duplicates - Sachin is present in the list twice
arraylist.add("Sachin");//[ Ganguly, Sachin, Dravid, Sachin]


2.2 Iterating around a list

Iterator<String> arraylistIterator = arraylist
while (arraylistIterator.hasNext()) {
    String str =;
    System.out.println(str);//Prints the 4 names in the list on separate lines.

2.3 Other ArrayList (List) methods

indexOf() function - returns index of element if element is found. Negative number otherwise.

//example1 - value is present
//example2 - value is not present

get() function - get value at specified index.


2.4 remove() function

remove() function has two variations.

//Using the object as parameter
//Dravid is removed from the list
arraylist.remove("Dravid");//[Ganguly, Sachin, Sachin]

//Using index as argument. 
//Object at index 1 (Sachin) is removed
arraylist.remove(1);//[Ganguly, Sachin]

3. Sorting Collections

List<String> numbers = new ArrayList<String>();
System.out.println(numbers);//[one, two, three, four]

//Strings - By Default - are sorted alphabetically

System.out.println(numbers);//[four, one, three, two]

4. List of Objects of a Custom Class

Consider the following class Cricketer.

class Cricketer{
    int runs;
    String name;

    public Cricketer(String name, int runs) {
        super(); = name;
        this.runs = runs;

    public String toString() {
        return name + " " + runs;

Let’s now try to sort a list containing objects of Cricketer class.

List<Cricketer> cricketers = new ArrayList<Cricketer>();
cricketers.add(new Cricketer("Bradman", 9996));
cricketers.add(new Cricketer("Sachin", 14000));
cricketers.add(new Cricketer("Dravid", 12000));
cricketers.add(new Cricketer("Ponting", 11000));
//[Bradman 9996, Sachin 14000, Dravid 12000, Ponting 11000]

//Cricketer class does not implement Comparable Interface 
//Collections.sort(cricketers); //COMPILER ERROR

We get a compiler error since Cricketer class does not implement Comparable interface. We were able to sort numbers in earlier example because String class implements Comparable.

Let’s make the Cricketer class implement the Comparable Interface.

class Cricketer implements Comparable<Cricketer> {
    //OTHER CODE/PROGRAM same as previous

    //compareTo takes an argument of the same type of the class
    //compareTo returns -1 if this < that
    //                   1 if this > that
    //                   0 if this = that
    public int compareTo(Cricketer that) {
        if (this.runs > that.runs) {
            return 1;
        if (this.runs < that.runs) {
            return -1;
        return 0;


Now let’s try to sort the cricketers.

//[Bradman 9996, Ponting 11000, Dravid 12000, Sachin 14000]

Other option to sort collections is by creating a separate class which implements Comparator interface.

Example below:

class DescendingSorter implements Comparator<Cricketer> {

    //compareTo returns -1 if cricketer1 < cricketer2
    //                   1 if cricketer1 > cricketer2
    //                   0 if cricketer1 = cricketer2

    //Since we want to sort in descending order, 
    //we should return -1 when runs are more
    public int compare(Cricketer cricketer1,
            Cricketer cricketer2) {
        if (cricketer1.runs > cricketer2.runs) {
            return -1;
        if (cricketer1.runs < cricketer2.runs) {
            return 1;
        return 0;


Let’s now try to sort the previous defined collection:

        .sort(cricketers, new DescendingSorter());

//[Sachin 14000, Dravid 12000, Ponting 11000, Bradman 9996]

5. Convert List to Array

There are two ways. First is to use toArray(String) function. Example below. This creates an array of String's

List<String> numbers1 = new ArrayList<String>();
String[] numbers1Array = new String[numbers1.size()];
numbers1Array = numbers1.toArray(numbers1Array);
//prints [one, two, three, four]

Other is to use toArray() function. Example below. This creates an array of Objects.

Object[] numbers1ObjArray = numbers1.toArray();
//[one, two, three, four]

6. Convert Array to List

String values[] = { "value1", "value2", "value3" };
List<String> valuesList = Arrays.asList(values);
System.out.println(valuesList);//[value1, value2, value3]

7. Other List interface implementations

Other classes that implement List interface are Vector and LinkedList.

7.1 Vector

Vector has the same operations as an ArrayList. However, all methods in Vector are synchronized. So, we can use Vector if we share a list between two threads and we would want to them synchronized.

7.2 LinkedList

Linked List extends List and Queue.Other than operations exposed by the Queue interface, LinkedList has the same operations as an ArrayList. However, the underlying implementation of Linked List is different from that of an ArrayList.

ArrayList uses an Array kind of structure to store elements. So, inserting and deleting from an ArrayList are expensive operations. However, search of an ArrayList is faster than LinkedList.

LinkedList uses a linked representation. Each object holds a link to the next element. Hence, insertion and deletion are faster than ArrayList. But searching is slower.

8. Java Collections Pdf Tutorial

Collections Interview Questions

Java Collection Interfaces - A Tutorial

Arrays are not dynamic. Once an array of a particular size is declared, the size cannot be modified. To add a new element to the array, a new array has to be created with bigger size and all the elements from the old array copied to new array. Collections are used in situations where data is dynamic. Collections allow adding an element, deleting an element and host of other operations. There are a number of Collections in Java allowing to choose the right Collection for the right context. Before looking into Collection classes, let’s take a quick look at all the important collection interfaces and the operations they allow.

1. Collection Interfaces - Java Video Tutorial

Video Coming Soon..

2. Collection Interface

Most important methods declared in the collection interface are the methods to add and remove an element. add method allows adding an element to a collection and delete method allows deleting an element from a collection.

size() methods returns number of elements in the collection. Other important methods defined as part of collection interface are shown below.

interface Collection<E> extends Iterable<E>
  boolean add(E paramE);
  boolean remove(Object paramObject);

  int size();
  boolean isEmpty();
  void clear();

  boolean contains(Object paramObject);
  boolean containsAll(Collection<?> paramCollection);
  boolean addAll(Collection<? extends E> paramCollection);
  boolean removeAll(Collection<?> paramCollection);
  boolean retainAll(Collection<?> paramCollection);

  Iterator<E> iterator();


3. List Interface

List interface extends Collection interface. So, it contains all methods defined in the Collection interface. In addition, List interface allows operation specifying the position of the element in the Collection.

Any implementation of the List interface would maintain the insertion order. When a new element is inserted, it is inserted at the end of the list of elements. We can also use the void add(int paramInt, E paramE); method to insert an element at a specific position. We can also set and get the elements at a particular index in the list using corresponding methods.

Other important methods are listed below:

interface List<E> extends Collection<E>
  boolean addAll(int paramInt, Collection<? extends E> paramCollection);

  E get(int paramInt);
  E set(int paramInt, E paramE);

  void add(int paramInt, E paramE);
  E remove(int paramInt);

  int indexOf(Object paramObject);
  int lastIndexOf(Object paramObject);

  ListIterator<E> listIterator();
  ListIterator<E> listIterator(int paramInt);
  List<E> subList(int paramInt1, int paramInt2);

4. Map Interface

First and foremost, Map interface does not extend Collection interface. So, it does not inherit any of the methods from the Collection interface.

A Map interface supports Collections that use a key value pair. A key-value pair is a set of linked data items: a key, which is a unique identifier for some item of data, and the value, which is either the data or a pointer to the data. Key-value pairs are used in lookup tables, hash tables and configuration files. A key value pair in a Map interface is called an Entry.

Put method allows to add a key, value pair to the Map.

  V put(K paramK, V paramV);

Get method allows to get a value from the Map based on the key.

  V get(Object paramObject);

Other important methods are shown below:

interface Map<K, V>
  int size();
  boolean isEmpty();

  boolean containsKey(Object paramObject);
  boolean containsValue(Object paramObject);

  V get(Object paramObject);
  V put(K paramK, V paramV);
  V remove(Object paramObject);

  void putAll(Map<? extends K, ? extends V> paramMap);
  void clear();

  Set<K> keySet();
  Collection<V> values();
  Set<Entry<K, V>> entrySet();

  boolean equals(Object paramObject);
  int hashCode();

  public static abstract interface Entry<K, V>
    K getKey();
    V getValue();
    V setValue(V paramV);
    boolean equals(Object paramObject);
    int hashCode();

5. Set Interface

Set Interface extends Collection Interface. Set interface only contains the methods from the Collection interface with added restriction that it cannot contain duplicates.

// Unique things only - Does not allow duplication.
// If obj1.equals(obj2) then only one of them can be in the Set.
interface Set<E> extends Collection<E>

6. SortedSet Interface

SortedSet Interface extends the Set Interface. So, it does not allow duplicates.

In addition, an implementation of SortedSet interface maintains its elements in a sorted order. It adds operations that allow getting a range of values (subSet, headSet, tailSet).

Important Operations listed below:

public interface SortedSet<E> extends Set<E> {
    SortedSet<E> subSet(E fromElement, E toElement);
    SortedSet<E> headSet(E toElement);
    SortedSet<E> tailSet(E fromElement);
    E first();
    E last();

    Comparator<? super E> comparator();

7. SortedMap Interface

SortedMap interface extends the Map interface. In addition, an implementation of SortedMap interface maintains keys in a sorted order.

Methods are available in the interface to get a ranges of values based on their keys.

public interface SortedMap<K, V> extends Map<K, V> {
    Comparator<? super K> comparator();

    SortedMap<K, V> subMap(K fromKey, K toKey);

    SortedMap<K, V> headMap(K toKey);

    SortedMap<K, V> tailMap(K fromKey);

    K firstKey();

    K lastKey();

8. Queue Interface

Queue Interface extends Collection interface. Queue Interface is typically used for implementation holding elements in order for some processing.

Queue interface offers methods peek() and poll() which get the element at head of the queue. The difference is that poll() method removes the head from queue also. peek() would keep head of the queue unchanged.

interface Queue<E> extends Collection<E>
  boolean offer(E paramE);
  E remove();
  E poll();
  E element();
  E peek();

9. Iterator interface

Iterator interface enables us to iterate (loop around) a collection. All collections define a method iterator() that gets an iterator of the collection.

hasNext() checks if there is another element in the collection being iterated. next() gets the next element.

public interface Iterator<E> {
    boolean hasNext();

    E next();

10. Java Collection Interfaces Pdf Tutorial

Collection Interfaces Interview Questions

Saturday, 21 December 2013

Java Number Format - A Tutorial

Number format is used to format a number to different locales and different formats.

1. Number Format - Java Video Tutorial

Video Coming Soon..

2. Format number Using Default locale


3. Format number using locale

Formatting a number using Netherlands locale

System.out.println(NumberFormat.getInstance(new Locale("nl")).format(4032.3f));//4.032,3

Formatting a number using Germany locale


4. Formatting a Currency using Default locale


5. Format currency using locale

Formatting a Currency using Netherlands locale
System.out.println(NumberFormat.getCurrencyInstance(new Locale("nl")).format(40324.31f));//? 40.324,31

Setting maximum fraction digits for a float

NumberFormat numberFormat = NumberFormat.getInstance();

6. Parsing using NumberFormat

Parsing a float value using number format


Parsing only number value using number format


7. Java Number Format Pdf Tutorial

Number Format Interview Questions

Java Calendar - A Tutorial

Calendar class is used in Java to manipulate Dates. Calendar class provides easy ways to add or reduce days, months or years from a date. It also provide lot of details about a date (which day of the year? Which week of the year? etc.)

1. Calendar - Java Video Tutorial

Video Coming Soon..

2. Calendar is abstract

Calendar class cannot be created by using new Calendar. The best way to get an instance of Calendar class is by using getInstance() static method in Calendar.

//Calendar calendar = new Calendar(); //COMPILER ERROR
Calendar calendar = Calendar.getInstance();

3. Calendar set day, month and year

Setting day, month or year on a calendar object is simple. Call the set method with appropriate Constant for Day, Month or Year. Next parameter is the value.

calendar.set(Calendar.DATE, 24);
calendar.set(Calendar.MONTH, 8);//8 - September
calendar.set(Calendar.YEAR, 2010);

4. Calendar get method

Let’s get information about a particular date - 24th September 2010. We use the calendar get method. The parameter passed indicates what value we would want to get from the calendar – day or month or year or .. Few examples of the values you can obtain from a calendar are listed below.

System.out.println(calendar.getFirstDayOfWeek());//1 -> Calendar.SUNDAY

5. Calendar - Modify a Date

We can use the calendar add and roll methods to modify a date. Calendar add method can be used to find a date 5 days or 5 months before the date by passing a –5 i.e. a negative 5.

calendar.add(Calendar.DATE, 5);
System.out.println(calendar.getTime());//Wed Sep 29 2010
calendar.add(Calendar.MONTH, 1);
System.out.println(calendar.getTime());//Fri Oct 29 2010
calendar.add(Calendar.YEAR, 2);
System.out.println(calendar.getTime());//Mon Oct 29 2012

5.1 Roll method

Roll method will only the change the value being modified. YEAR remains unaffected when MONTH is changed, for instance.

calendar.roll(Calendar.MONTH, 5);
System.out.println(calendar.getTime());//Mon Mar 29 2012

6. Creating calendar: Example 2

Calendar gregorianCalendar = new GregorianCalendar(
        2011, 7, 15);

7. Formatting Calendar object.

Done by getting the date using calendar.getTime() and using the usual formatting of dates.

        calendar.getTime()));//3/29/12 11:39 AM

8. Java Calendar Pdf Tutorial

Calendar Interview Questions

Java Date - A Tutorial

Date is no longer the class Java recommends for storing and manipulating date and time. Most of methods in Date are deprecated. Use Calendar class instead. Date internally represents date-time as number of milliseconds (a long value) since 1st Jan 1970.

1. Date - Java Video Tutorial

Video Coming Soon..

2. Creating Date Object

//Creating Date Object
Date now = new Date();

3. Manipulating Date Object

Lets now look at adding a few hours to a date object. All date manipulation to date needs to be done by adding milliseconds to the date. For example, if we want to add 6 hour, we convert 6 hours into millseconds. 6 hours = 6 * 60 * 60 * 1000 milliseconds. Below examples shows specific code.

Date date = new Date();

//Increase time by 6 hrs
date.setTime(date.getTime() + 6 * 60 * 60 * 1000);

//Decrease time by 6 hrs
date = new Date();
date.setTime(date.getTime() - 6 * 60 * 60 * 1000);

4. Formatting Dates

Formatting Dates is done by using DateFormat class. Let’s look at a few examples.

//Formatting Dates
        date));//10/16/12 5:18 AM

Formatting Dates with a locale

        DateFormat.FULL, new Locale("it", "IT"))
        .format(date));//marted“ 16 ottobre 2012

        DateFormat.FULL, Locale.ITALIAN)
        .format(date));//marted“ 16 ottobre 2012

//This uses default locale US
        DateFormat.FULL).format(date));//Tuesday, October 16, 2012

        .format(date));//Oct 16, 2012
        DateFormat.MEDIUM).format(date));//Oct 16, 2012

        DateFormat.LONG).format(date));//October 16, 2012

5. Format Date’s using SimpleDateFormat

Let’s look at a few examples of formatting dates using SimpleDateFormat.

System.out.println(new SimpleDateFormat("yy-MM-dd")
        .println(new SimpleDateFormat("yy-MMM-dd")
System.out.println(new SimpleDateFormat(

//Parse Dates using DateFormat
Date date2 = DateFormat.getDateInstance(
System.out.println(date2);//Tue Oct 16 00:00:00 GMT+05:30 2012

//Creating Dates using SimpleDateFormat
Date date1 = new SimpleDateFormat("yy-MM-dd")
System.out.println(date1);//Tue Oct 16 00:00:00 GMT+05:30 2012

6. Default Locale

Locale defaultLocale = Locale.getDefault();

        .getDisplayCountry());//United States

7. Java Date Pdf Tutorial

Date Interview Questions

Java String Buffer &#38; String Builder - A Tutorial

StringBuffer and StringBuilder are used when you want to modify values of a string frequently. String Buffer class is thread safe where as String Builder is NOT thread safe.

1. String Buffer & String Builder - Java Video Tutorial

Video Coming Soon..

2. String Buffer Examples

StringBuffer stringbuffer = new StringBuffer("12345");
System.out.println(stringbuffer); //123456789
//All StringBuffer methods modify the value of the object.

3. String Builder Examples

StringBuilder sb = new StringBuilder("0123456789");

//StringBuilder delete(int startIndex, int endIndexPlusOne)
System.out.println(sb.delete(3, 7));//012789

StringBuilder sb1 = new StringBuilder("abcdefgh");

//StringBuilder insert(int indext, String whatToInsert)
System.out.println(sb1.insert(3, "ABCD"));//abcABCDdefgh

StringBuilder sb2 = new StringBuilder("abcdefgh");
//StringBuilder reverse()

Similar functions exist in StringBuffer also.

4. Method Chaining

All functions also return a reference to the object after modifying it.This allows a concept called method chaining.

StringBuilder sb3 = new StringBuilder("abcdefgh");
System.out.println(sb3.reverse().delete(5, 6).insert(3, "---"));//hgf---edba

5. Java String Buffer & String Builder Pdf Tutorial

String Buffer & String Builder Interview Questions