Saturday, 28 December 2013

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>();

hashset.add("Sachin");
System.out.println(hashset);//[Sachin]

hashset.add("Dravid");
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>();

treeSet.add("Sachin");
System.out.println(treeSet);//[Sachin]

Notice that the list is sorted after inserting Dravid.

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

Notice that the list is sorted after inserting Ganguly.

treeSet.add("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>();
numbersTreeSet.add(55);
numbersTreeSet.add(25);
numbersTreeSet.add(35);
numbersTreeSet.add(5);
numbersTreeSet.add(45);

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
System.out.println(numbersTreeSet.lower(25));//5

//Find the highest number which is lower than or equal to 25
System.out.println(numbersTreeSet.floor(25));//25

//Find the lowest number higher than 25
System.out.println(numbersTreeSet.higher(25));//35

//Find the lowest number higher than or equal to 25
System.out.println(numbersTreeSet.ceiling(25));//25

4.2 NavigableSet subSet,headSet,tailSet Methods in TreeSet

TreeSet<Integer> exampleTreeSet = new TreeSet<Integer>();
exampleTreeSet.add(55);
exampleTreeSet.add(25);
exampleTreeSet.add(105);
exampleTreeSet.add(35);
exampleTreeSet.add(5);

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
        .headSet(55);
System.out.println(headTreeSet);//[5, 25, 35]

//Get sub set with values >=35
SortedSet<Integer> tailTreeSet = exampleTreeSet
        .tailSet(35);
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);
System.out.println(subTreeSetNotIncl);//[35]

//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.

exampleTreeSet.add(30);

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
exampleTreeSet.add(65);

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>();
treeSetOrig.add(55);
treeSetOrig.add(25);
treeSetOrig.add(35);
treeSetOrig.add(5);

System.out.println(treeSetOrig);//[5, 25, 35, 55]
//descendingSet method returns the tree set in reverse order
TreeSet<Integer> treeSetDesc = (TreeSet<Integer>) treeSetOrig
        .descendingSet();
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.pollFirst());//5
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.pollLast());//55
System.out.println(treeSetOrig);//[25, 35]

5. Java Set Interface Pdf Tutorial

Set Interface Interview Questions

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
arraylist.add("Sachin");//[Sachin]

//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]

System.out.println(arraylist.size());//4
System.out.println(arraylist.contains("Dravid"));//true

2.2 Iterating around a list

Iterator<String> arraylistIterator = arraylist
        .iterator();
while (arraylistIterator.hasNext()) {
    String str = arraylistIterator.next();
    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
System.out.println(arraylist.indexOf("Dravid"));//2
//example2 - value is not present
System.out.println(arraylist.indexOf("Bradman"));//-1

get() function - get value at specified index.

System.out.println(arraylist.get(1));//Sachin

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>();
numbers.add("one");
numbers.add("two");
numbers.add("three");
numbers.add("four");
System.out.println(numbers);//[one, two, three, four]

//Strings - By Default - are sorted alphabetically
Collections.sort(numbers);

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();
        this.name = name;
        this.runs = runs;
    }

    @Override
    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));
System.out.println(cricketers);
//[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
    @Override
    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.

Collections.sort(cricketers);
System.out.println(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
    @Override
    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:

Collections
        .sort(cricketers, new DescendingSorter());

System.out.println(cricketers);
//[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>();
numbers1.add("one");
numbers1.add("two");
numbers1.add("three");
numbers1.add("four");
String[] numbers1Array = new String[numbers1.size()];
numbers1Array = numbers1.toArray(numbers1Array);
System.out.println(Arrays.toString(numbers1Array));
//prints [one, two, three, four]

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

Object[] numbers1ObjArray = numbers1.toArray();
System.out.println(Arrays
        .toString(numbers1ObjArray));
//[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

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();

  //A NUMBER OF OTHER METHODS AS WELL..
}

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

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

System.out.println(NumberFormat.getInstance().format(321.24f));//321.24        

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

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

4. Formatting a Currency using Default locale

System.out.println(NumberFormat.getCurrencyInstance().format(40324.31f));//$40,324.31

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();
System.out.println(numberFormat.getMaximumFractionDigits());//3
numberFormat.setMaximumFractionDigits(5);
System.out.println(numberFormat.format(321.24532f));//321.24533

6. Parsing using NumberFormat

Parsing a float value using number format

System.out.println(numberFormat.parse("9876.56"));//9876.56

Parsing only number value using number format

numberFormat.setParseIntegerOnly(true);
System.out.println(numberFormat.parse("9876.56"));//9876

7. Java Number Format Pdf Tutorial

Number Format Interview Questions

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.get(Calendar.YEAR));//2010
System.out.println(calendar.get(Calendar.MONTH));//8
System.out.println(calendar.get(Calendar.DATE));//24
System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));//4
System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));//39
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//267
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.

System.out.println(DateFormat.getInstance().format(
        calendar.getTime()));//3/29/12 11:39 AM

8. Java Calendar Pdf Tutorial

Calendar Interview Questions

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();
System.out.println(now.getTime());

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);
System.out.println(date);

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

4. Formatting Dates

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

//Formatting Dates
System.out.println(DateFormat.getInstance().format(
        date));//10/16/12 5:18 AM

Formatting Dates with a locale

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

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

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

System.out.println(DateFormat.getDateInstance()
        .format(date));//Oct 16, 2012
System.out.println(DateFormat.getDateInstance(
        DateFormat.SHORT).format(date));//10/16/12
System.out.println(DateFormat.getDateInstance(
        DateFormat.MEDIUM).format(date));//Oct 16, 2012

System.out.println(DateFormat.getDateInstance(
        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")
        .format(date));//12-10-16
System.out
        .println(new SimpleDateFormat("yy-MMM-dd")
                .format(date));//12-Oct-16
System.out.println(new SimpleDateFormat(
        "yyyy-MM-dd").format(date));//2012-10-16

//Parse Dates using DateFormat
Date date2 = DateFormat.getDateInstance(
        DateFormat.SHORT).parse("10/16/12");
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")
        .parse("12-10-16");
System.out.println(date1);//Tue Oct 16 00:00:00 GMT+05:30 2012

6. Default Locale

Locale defaultLocale = Locale.getDefault();

System.out.println(defaultLocale
        .getDisplayCountry());//United States
System.out.println(defaultLocale
        .getDisplayLanguage());//English

7. Java Date Pdf Tutorial

Date Interview Questions

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");
stringbuffer.append("6789");
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()
System.out.println(sb2.reverse());//hgfedcba

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