Java Date API

java.util.
Class Date

java.lang.Object
extended by java.util.Date

All Implemented Interfaces:
Cloneable, Comparable, Serializable

Direct Known Subclasses:
Date, Time, Timestamp

public class Date extends Object
implements Serializable, Cloneable, Comparable

The class Date represents a specific instant in time, with millisecond precision.

Java Date Source Code

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtility {

/* Add Day/Month/Year to a Date
add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/

public static final String DATE_FORMAT = "dd-MM-yyyy";
//See Java DOCS for different date formats
// public static final String DATE_FORMAT = "yyyy-MM-dd";

public static void addToDate() {
System.out.println("1. Add to a Date Operation\n");
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
//Gets a calendar using the default time zone and locale.
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
// System.out.println("Todays date in Calendar Format : "+c1);
System.out.println("c1.getTime() : " + c1.getTime());
System.out.println("c1.get(Calendar.YEAR): "+ c1.get(Calendar.YEAR));
System.out.println("Todays date in Date Format : " + d1);
c1.set(1999, 0, 20); //(year,month,date)
System.out.println("c1.set(1999,0 ,20) : " + c1.getTime());
c1.add(Calendar.DATE, 20);
System.out.println("Date + 20 days is : "+ sdf.format(c1.getTime()));
System.out.println();
System.out.println("-------------------------------------");
}

/*Substract Day/Month/Year to a Date

roll() is used to substract values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument.
roll() does the same thing except you specify if you want to roll up (add 1)
or roll down (substract 1) to the specified Calendar field. The operation only
affects the specified field while add() adjusts other Calendar fields.
See the following example, roll() makes january rolls to december in the same
year while add() substract the YEAR field for the correct result. Hence add()
is preferred even for subtraction by using a negative element.

*/

public static void subToDate() {

System.out.println("2. Subtract to a date Operation\n");
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0, 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
// roll down, substract 1 month
c1.roll(Calendar.MONTH, false);
System.out.println("Date roll down 1 month : "+ sdf.format(c1.getTime()));
c1.set(1999, 0, 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : "+ sdf.format(c1.getTime()));
System.out.println();
System.out.println("-------------------------------------");
}

public static void daysBetween2Dates() {

System.out.println("3. No of Days between 2 dates\n");
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 0, 20);
c2.set(1999, 0, 22);
System.out.println("Days Between " + c1.getTime() + " and "
+ c2.getTime() + " is");
System.out.println((c2.getTime().getTime() - c1.getTime()
.getTime()) / (24 * 3600 * 1000));
System.out.println();
System.out.println("-------------------------------------");
}

public static void daysInMonth() {

System.out.println("4. No of Days in a month for a given date\n");
Calendar c1 = Calendar.getInstance(); // new GregorianCalendar();
c1.set(1999, 6, 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
// int days = c1.get(Calendar.DATE);
int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 };
daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
System.out.println(”Days in ” + month + “th month for year” + year
+ “is ” + daysInMonths[c1.get(Calendar.MONTH)]);
System.out.println();
System.out.println(”————————————-”);
}

public static void validateAGivenDate() {

System.out.println(”5. Validate a given date\n”);
String dt = “20011223″;
String invalidDt = “20031315″;
String dateformat = “yyyyMMdd”;
Date dt1 = null, dt2 = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
sdf.setLenient(false);
dt1 = sdf.parse(dt);
dt2 = sdf.parse(invalidDt);
System.out.println(”Date is ok = ” + dt1 + “(” + dt + “)”);
} catch (ParseException e) {
System.out.println(e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println(”Invalid date”);
}
System.out.println();
System.out.println(”————————————-”);
}

public static void compare2Dates() {

System.out.println(”6. Comparision of 2 dates\n”);
SimpleDateFormat fm = new SimpleDateFormat(”dd-MM-yyyy”);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.set(2000, 02, 15);
c2.set(2001, 02, 15);
System.out.print(fm.format(c1.getTime()) + ” is “);
if (c1.before(c2)) {
System.out.println(”less than ” + fm.format(c2.getTime()));
} else if (c1.after(c2)) {
System.out.println(”greater than ” + fm.format(c2.getTime()));
} else if (c1.equals(c2)) {
System.out.println(”is equal to ” + fm.format(c2.getTime()));
}
System.out.println();
System.out.println(”————————————-”);
}

public static void getDayofTheDate() {

System.out.println(”7. Get the day for a given date\n”);
Date d1 = new Date();
String day = null;
DateFormat f = new SimpleDateFormat(”EEEE”);
try {
day = f.format(d1);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(”The day for ” + d1 + ” is ” + day);
System.out.println();
System.out.println(”————————————-”);
}

//Utility Method to find whether an Year is a Leap year or Not
public static boolean isLeapYear(int year) {

if ((year % 100 != 0) || (year % 400 == 0)) {
return true;
}
return false;
}

public static void main(String args[]) {
addToDate(); //Add day, month or year to a date field.
subToDate(); //Subtract day, month or year to a date field.
daysBetween2Dates();
//The “right” way would be to compute the Julian day number of
//both dates and then do the subtraction.
daysInMonth();//Find the number of days in a month for a date
validateAGivenDate();//Check whether the date format is proper
compare2Dates(); //Compare 2 dates
getDayofTheDate();
}


}

Output

1. Add to a Date Operation

c1.getTime() : Sat Mar 31 10:47:54 IST 2007
c1.get(Calendar.YEAR): 2007
Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007
c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999
Date + 20 days is : 09-02-1999

——————————————————-
2. Subtract to a date Operation

Date is : 20-01-1999
Date roll down 1 month : 20-12-1999
Date is : 20-01-1999
Date minus 1 month : 20-12-1998

——————————————————-
3. No of Days between 2 dates

Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is
2

——————————————————-
4. No of Days in a month for a given date

Days in 6th month for year 1999 is 31

——————————————————-
5. Validate a given date

Unparseable date: “20031315″

——————————————————-
6. Comparision of 2 dates

15-03-2000 is less than 15-03-2001

——————————————————-
7. Get the day for a given date

The day for Sat Mar 31 10:47:54 IST 2007 is Saturday

Java Collections Framework

A collection represents a group of objects, known as its elements. This framework is provided in the java.util package. Objects can be stored, retrieved, and manipulated as elements of collections. Collection is a Java Interface. Collections can be used in various scenarios like Storing phone numbers, Employee names database etc. They are basically used to group multiple elements into a single unit. Some collections allow duplicate elements while others do not. Some collections are ordered and others are not.

A Collections Framework mainly contains the following 3 parts

A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. In addition, the framework also provides several abstract implementations, which are designed to make it easier for you to create new and different implementations for handling collections of data.

Core Collection Interfaces

The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation.
The 6 core Interfaces used in the Collection framework are:

  • Collection
  • Set
  • List
  • Iterator (Not a part of the Collections Framework)
  • SortedSet
  • Map
  • SortedMap

Note: Collection and Map are the two top-level interfaces.

Collection Interface

Map Interface

Concrete Classes

The concrete classes that are specific implementations of the core interfaces, providing data structures that a java program can use.

Note: Concrete Classes for the Map is shown in the previous section.
Standard utility methods and algorithms

Standard utility methods and algorithms

that can be used to perform various operations on collections, such as sorting, searching or creating customized collections.

How are Collections Used

  • The collections stores object references, rather than objects themselves. Hence primitive values cannot be stored in a collection directly. They need to be encapsulated (using wrapper classes) into an Object prior to storing them into a Collection (such as HashSet, HashMap etc).
  • The references are always stored as type Object. Thus, when you retrieve an element from a collection, you get an Object rather then the actual type of the collection stored in the database. Hence we need to downcast it to the Actual Type while retrieving an element from a collection.
  • One of the capabilities of the Collection Framework is to create a new Collection object and populate it with the contents of an existing Collection object of a same or different actual type.

Below is an example program showing the storing and retrieving of a few Collection Types

import java.util.*;

public class CollectionsDemo {

public static void main(String[] args) {
List a1 = new ArrayList();
a1.add(”Beginner”);
a1.add(”Java”);
a1.add(”tutorial”);
System.out.println(” ArrayList Elements”);
System.out.print(”\t” + a1);
List l1 = new LinkedList();
l1.add(”Beginner”);
l1.add(”Java”);
l1.add(”tutorial”);
System.out.println();
System.out.println(” LinkedList Elements”);
System.out.print(”\t” + l1);
Set s1 = new HashSet(); // or new TreeSet() will order the elements;
s1.add(”Beginner”);
s1.add(”Java”);
s1.add(”Java”);
s1.add(”tutorial”);
System.out.println();
System.out.println(” Set Elements”);
System.out.print(”\t” + s1);
Map m1 = new HashMap(); // or new TreeMap() will order based on keys
m1.put(”Windows”, “98″);
m1.put(”Win”, “XP”);
m1.put(”Beginner”, “Java”);
m1.put(”Tutorial”, “Site”);
System.out.println();
System.out.println(” Map Elements”);
System.out.print(”\t” + m1);
}
}

Output

ArrayList Elements
[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}

Thread States


A Java thread is always in one of several states which could be running, sleeping, dead, etc.

A thread can be in any of the following states:

  • New Thread state (Ready-to-run state)
  • Runnable state (Running state)
  • Not Runnable state
  • Dead state
A thread is in this state when the instantiation of a Thread object creates a new thread but does not
start it running. A thread starts life in the Ready-to-run state. You can call only the start() or stop()
methods when the thread is in this state. Calling any method besides start() or stop() causes an
IllegalThreadStateException.

Runnable

When the start() method is invoked on a New Thread() it gets to the runnable state or running state by
calling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.

Not Runnable

A thread becomes Not Runnable when one of the following four events occurs:

  • When sleep() method is invoked and it sleeps for a specified amount of time
  • When suspend() method is invoked
  • When the wait() method is invoked and the thread waits for notification of a free resource or waits for
    the completion of another thread or waits to acquire a lock of an object.
  • The thread is blocking on I/O and waits for its completion

Example: Thread.currentThread().sleep(1000);

Note: Thread.currentThread() may return an output like Thread[threadA,5,main]

The output shown in bold describes

  • the name of the thread,
  • the priority of the thread, and
  • the name of the group to which it belongs.

Here, the run() method put itself to sleep for one second and becomes Not Runnable during that period.
A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object or at the end of the period of time for sleep is over. Whether or not it will actually start running depends on its priority and the availability of the CPU.

Hence I hereby list the scenarios below to describe how a thread switches form a non runnable to a runnable state:


  • If a thread has been put to sleep, then the specified number of milliseconds must elapse (or it must be interrupted).
  • If a thread has been suspended, then its resume() method must be invoked
  • If a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by calling
    either notify() or notifyAll().
  • If a thread is blocked on I/O, then the I/O must complete.
  • Java Threads Tutorial

    Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.

    Multithreading has several advantages over Multiprocessing such as;

    • Threads are lightweight compared to processes
    • Threads share the same address space and therefore can share both data and code
    • Context switching between threads is usually less expensive than between processes
    • Cost of thread intercommunication is relatively low that that of process intercommunication
    • Threads allow different tasks to be performed concurrently.

    The following figure shows the methods that are members of the Object and Thread Class.

    Thread Creation

    There are two ways to create thread in java;

    • Implement the Runnable interface (java.lang.Runnable)
    • By Extending the Thread class (java.lang.Thread)

    Implementing the Runnable Interface

    The Runnable Interface Signature

    public interface Runnable {

    void run();

    }

    One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.

    The procedure for creating threads based on the Runnable interface is as follows:

    1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.

    2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.

    3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.

    4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.

    Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.

    class RunnableThread implements Runnable {
    

    Thread runner;
    public RunnableThread() {
    }
    public RunnableThread(String threadName) {
    runner = new Thread(this, threadName); // (1) Create a new thread.
    System.out.println(runner.getName());
    runner.start(); // (2) Start the thread.
    }
    public void run() {
    //Display info about this particular thread
    System.out.println(Thread.currentThread());
    }
    }

    public class RunnableExample {

    public static void main(String[] args) {
    Thread thread1 = new Thread(new RunnableThread(), “thread1″);
    Thread thread2 = new Thread(new RunnableThread(), “thread2″);
    RunnableThread thread3 = new RunnableThread(”thread3″);
    //Start the threads
    thread1.start();
    thread2.start();
    try {
    //delay for one second
    Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
    }
    //Display info about the main thread
    System.out.println(Thread.currentThread());
    }
    }

    Output

    thread3
    Thread[thread1,5,main]
    Thread[thread2,5,main]
    Thread[thread3,5,main]
    Thread[main,5,main]private


    This approach of creating a thread by implementing the Runnable Interface must be used whenever the class being used to instantiate the thread object is required to extend some other class.

    Extending Thread Class

    The procedure for creating threads based on extending the Thread is as follows:

    1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.

    2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.

    3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.

    Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

    class XThread extends Thread {
    

    XThread() {
    }
    XThread(String threadName) {
    super(threadName); // Initialize thread.
    System.out.println(this);
    start();
    }
    public void run() {
    //Display info about this particular thread
    System.out.println(Thread.currentThread().getName());
    }
    }

    public class ThreadExample {

    public static void main(String[] args) {
    Thread thread1 = new Thread(new XThread(), “thread1″);
    Thread thread2 = new Thread(new XThread(), “thread2″);
    // The below 2 threads are assigned default names
    Thread thread3 = new XThread();
    Thread thread4 = new XThread();
    Thread thread5 = new XThread(”thread5″);
    //Start the threads
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    try {
    //The sleep() method is invoked on the main thread to cause a one second delay.
    Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
    }
    //Display info about the main thread
    System.out.println(Thread.currentThread());
    }
    }

    Output

    Thread[thread5,5,main]
    thread1
    thread5
    thread2
    Thread-3
    Thread-2
    Thread[main,5,main]


    When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:

    • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface
      has this option.
    • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.

    An example of an anonymous class below shows how to create a thread and start it:

    ( new Thread() {

    public void run() {

    for(;;) System.out.println(”Stop the world!”);

    }

    }

    ).start();



    Thread Synchronization

    With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.

    In non synchronized multithreaded application, it is possible for one thread to modify a shared object while

    another thread is in the process of using or updating the object’s value. Synchronization prevents such type
    of data corruption which may otherwise lead to dirty reads and significant errors.
    Generally critical sections of the code are usually marked with synchronized keyword.

    Examples of using Thread Synchronization is in “The Producer/Consumer Model”.

    Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource.
    Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.
    At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.
    A lock thus implements mutual exclusion.

    The object lock mechanism enforces the following rules of synchronization:

  • A thread must acquire the object lock associated with a shared resource, before it can enter the shared
    resource. The runtime system ensures that no other thread can enter a shared resource if another thread
    already holds the object lock associated with the shared resource. If a thread cannot immediately acquire
    the object lock, it is blocked, that is, it must wait for the lock to become available.
  • When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.
    If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain access
    to the shared resource.
  • Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a
    lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class
    denotes this unique Class object. The class lock can be used in much the same way as an object lock to
    implement mutual exclusion.

    There can be 2 ways through which synchronized can be implemented in Java:

    • synchronized methods
    • synchronized blocks

    Synchronized statements are same as synchronized methods. A synchronized statement can only be
    executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.

    Synchronized Methods

    Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. .If the lock is already held by another thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when two or more threads simultaneously update the same value, and as a consequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.

    Below is an example shows how synchronized methods and object locks are used to coordinate access to a common object by multiple threads. If the ’synchronized’ keyword is removed, the message is displayed in random fashion.

    public class SyncMethodsExample extends Thread {
    

    static String[] msg = { “Beginner”, “java”, “tutorial,”, “.,”, “com”,
    “is”, “the”, “best” };
    public SyncMethodsExample(String id) {
    super(id);
    }
    public static void main(String[] args) {
    SyncMethodsExample thread1 = new SyncMethodsExample(”thread1: “);
    SyncMethodsExample thread2 = new SyncMethodsExample(”thread2: “);
    thread1.start();
    thread2.start();
    boolean t1IsAlive = true;
    boolean t2IsAlive = true;
    do {
    if (t1IsAlive && !thread1.isAlive()) {
    t1IsAlive = false;
    System.out.println(”t1 is dead.”);
    }

    if (t2IsAlive && !thread2.isAlive()) {
    t2IsAlive = false;
    System.out.println(”t2 is dead.”);
    }
    } while (t1IsAlive || t2IsAlive);
    }
    void randomWait() {
    try {
    Thread.currentThread().sleep((long) (3000 * Math.random()));
    } catch (InterruptedException e) {
    System.out.println(”Interrupted!”);
    }
    }
    public synchronized void run() {
    SynchronizedOutput.displayList(getName(), msg);
    }
    }

    class SynchronizedOutput {

    // if the ’synchronized’ keyword is removed, the message
    // is displayed in random fashion
    public static synchronized void displayList(String name, String list[]) {
    for (int i = 0; i < list.length; i++) {
    SyncMethodsExample t = (SyncMethodsExample) Thread
    .currentThread();
    t.randomWait();
    System.out.println(name + list[i]);
    }
    }
    }

    Output

    thread1: Beginner
    thread1: java
    thread1: tutorial,
    thread1: .,
    thread1: com
    thread1: is
    thread1: the
    thread1: best
    t1 is dead.
    thread2: Beginner
    thread2: java
    thread2: tutorial,
    thread2: .,
    thread2: com
    thread2: is
    thread2: the
    thread2: best
    t2 is dead.

    Download Synchronized Methods Thread Program Example

    Class Locks

    Synchronized Blocks

    Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A thread acquires the class lock before it can proceed with the execution of any static synchronized method in the class, blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
    The general form of the synchronized block is as follows:

    synchronized () {

    }

    A compile-time error occurs if the expression produces a value of any primitive type. If execution of the block completes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released.
    A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statements with identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, a NullPointerException is thrown.

    The code block is usually related to the object on which the synchronization is being done. This is the case with synchronized methods, where the execution of the method is synchronized on the lock of the current object:

    public Object method() {
    synchronized (this) { // Synchronized block on current object
    // method block
    }
    }

    Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be able to execute the code block, or any other code requiring the same object lock, until the lock is relinquished. This happens when the execution of the code block completes normally or an uncaught exception is thrown.

    Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of a part of a method, by using the this reference and putting the relevant part of the method in the synchronized block. The braces of the block cannot be left out, even if the code block has just one statement.

    class SmartClient {
    BankAccount account;
    // …
    public void updateTransaction() {
    synchronized (account) { // (1) synchronized block
    account.update(); // (2)
    }
    }
    }

    In the previous example, the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object. If several threads were to concurrently execute the method updateTransaction() on an object of SmartClient, the statement at (2) would be executed by one thread at a time, only after synchronizing on the BankAccount object associated with this particular instance of SmartClient.

    Inner classes can access data in their enclosing context. An inner object might need to synchronize on its associated outer object, in order to ensure integrity of data in the latter. This is illustrated in the following code where the synchronized block at (5) uses the special form of the this reference to synchronize on the outer object associated with an object of the inner class. This setup ensures that a thread executing the method setPi() in an inner object can only access the private double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associated outer object. If another thread has the lock of the associated outer object, the thread in the inner object has to wait for the lock to be relinquished before it can proceed with the execution of the synchronized block at (5). However, synchronizing on an inner object and on its associated outer object are independent of each other, unless enforced explicitly, as in the following code:

    class Outer { // (1) Top-level Class
    private double myPi; // (2)
    protected class Inner { // (3) Non-static member Class
    public void setPi() { // (4)
    synchronized(Outer.this) { // (5) Synchronized block on outer object
    myPi = Math.PI; // (6)
    }
    }
    }
    }

    Below example shows how synchronized block and object locks are used to coordinate access to shared objects by multiple threads.

    public class SyncBlockExample extends Thread {
    

    static String[] msg = { “Beginner”, “java”, “tutorial,”, “.,”, “com”,
    “is”, “the”, “best” };
    public SyncBlockExample(String id) {
    super(id);
    }
    public static void main(String[] args) {
    SyncBlockExample thread1 = new SyncBlockExample(”thread1: “);
    SyncBlockExample thread2 = new SyncBlockExample(”thread2: “);
    thread1.start();
    thread2.start();
    boolean t1IsAlive = true;
    boolean t2IsAlive = true;
    do {
    if (t1IsAlive && !thread1.isAlive()) {
    t1IsAlive = false;
    System.out.println(”t1 is dead.”);
    }
    if (t2IsAlive && !thread2.isAlive()) {
    t2IsAlive = false;
    System.out.println(”t2 is dead.”);
    }
    } while (t1IsAlive || t2IsAlive);
    }
    void randomWait() {
    try {
    Thread.currentThread().sleep((long) (3000 * Math.random()));
    } catch (InterruptedException e) {
    System.out.println(”Interrupted!”);
    }
    }
    public void run() {
    synchronized (System.out) {
    for (int i = 0; i < msg.length; i++) {
    randomWait();
    System.out.println(getName() + msg[i]);
    }
    }
    }
    }

    Output

    thread1: Beginner
    thread1: java
    thread1: tutorial,
    thread1: .,
    thread1: com
    thread1: is
    thread1: the
    thread1: best
    t1 is dead.
    thread2: Beginner
    thread2: java
    thread2: tutorial,
    thread2: .,
    thread2: com
    thread2: is
    thread2: the
    thread2: best
    t2 is dead.

    Synchronized blocks can also be specified on a class lock:

    synchronized (.class) { }

    The block synchronizes on the lock of the object denoted by the reference .class. A static synchronized method
    classAction() in class A is equivalent to the following declaration:

    static void classAction() {

    synchronized (A.class) { // Synchronized block on class A

    // …

    }

    }

    In summary, a thread can hold a lock on an object

    • by executing a synchronized instance method of the object
    • by executing the body of a synchronized block that synchronizes on the object
    • by executing a synchronized static method of a class

    Understanding Java Exceptions

    Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.
    Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment

    An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.

    A Program Showing How the JVM throws an Exception at runtime

    public class DivideException {

    public static void main(String[] args) {
    division(100,4); // Line 1
    division(100,0); // Line 2
    System.out.println(”Exit main().”);
    }

    public static void division(int totalSum, int totalNumber) {
    System.out.println(”Computing Division.”);
    int average = totalSum/totalNumber;
    System.out.println(”Average : “+ average);
    }
    }

    Download DivideException.java

    An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method

    Output

    Computing Division.
    java.lang.ArithmeticException: / by zero
    Average : 25
    Computing Division.
    at DivideException.division(DivideException.java:11)
    at DivideException.main(DivideException.java:5)

    Exception in thread “main”

    Exceptions in Java

    Throwable Class

    The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

    The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.

    Syntax

    String getMessage()

    void printStackTrace()

    String toString()

    Class Exception

    The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

    Class RuntimeException

    Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.

    Class Error

    Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

    Checked and Unchecked Exceptions

    Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller

    Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

    Exception Statement Syntax

    Exceptions are handled using a try-catch-finally construct, which has the Syntax

    try {

    } catch ( ) { // 0 or more

    }
    } finally { // finally block

    }

    try Block
    The java code that you think may produce an exception is placed within a try block for a
    suitable catch block to handle the error.

    If no exception occurs the execution proceeds with the finally block else it will look for the
    matching catch block to handle the error. Again if the matching catch handler is not found execution
    proceeds with the finally block and the default exception handler throws an exception.. If an exception is
    generated within the try block, the remaining statements in the try block are not executed.

    catch Block
    Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed
    (Though the catch block throws an exception).

    finally Block
    A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
    statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.

    The following program illustrates the scenario.

    try {

    } catch ( ) { // 0 or more


    }
    } finally { // finally block

    }



    Output

    Computing Division.
    Exception : / by zero
    Finally Block Executes. Exception Occurred
    result : -1

    Below is a program showing the Normal Execution of the Program.

    Please note that no NullPointerException is generated as was expected by most people

    public class DivideException2 {

    public static void main(String[] args) {
    int result = division(100,0); // Line 2
    System.out.println(”result : “+result);
    }

    public static int division(int totalSum, int totalNumber) {
    int quotient = -1;
    System.out.println(”Computing Division.”);
    try{
    quotient = totalSum/totalNumber;

    }
    catch(Exception e){
    System.out.println(”Exception : “+ e.getMessage());
    }
    finally{
    if(quotient != -1){
    System.out.println(”Finally Block Executes”);
    System.out.println(”Result : “+ quotient);
    }else{
    System.out.println(”Finally Block Executes. Exception Occurred”);
    return quotient;
    }

    }
    return quotient;
    }

    }

    Output

    null (And not NullPointerException)


    Rules for try, catch and finally Blocks


    1. For each try block there can be zero or more catch blocks, but only one finally block.


    2. The catch blocks and finally block must always appear in conjunction with a try block.

    Java exception handling mechanism enables you to catch exceptions in java using try, catch, finally block. be An exception consists of a block of code called a try block, a block of code called a catch block, and the finally block. Let’s examine each of these in detail.

    public class DivideException1 {

    public static void main(String[] args) {
    division(100,0); // Line 2
    System.out.println(”Main Program Terminating”);
    }

    public static void division(int totalSum, int totalNumber) {
    int quotient = -1;
    System.out.println(”Computing Division.”);
    try{
    quotient = totalSum/totalNumber;
    System.out.println(”Result is : “+quotient);
    }
    catch(Exception e){
    System.out.println(”Exception : “+ e.getMessage());
    }
    finally{
    if(quotient != -1){
    System.out.println(”Finally Block Executes”);
    System.out.println(”Result : “+ quotient);
    }else{
    System.out.println(”Finally Block Executes. Exception Occurred”);
    }

    }
    }
    }


    Output

    Computing Division.
    Exception : / by zero
    Finally Block Executes. Exception Occurred
    Main Program Terminating

    As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and program execution is transferred to the catch statement. Because the exception is thrown from the try block, the remaining statements of the try block
    are skipped. The finally block executes.

    Defining new EXCEPTIONS!!
    We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked).
    The super() call can be used to set a detail message in the throwable. Below is an example that shows the use of Custom exception’s along with how the throw and throws clause are used.

    class BadTemperature extends Exception{
    BadTemperature( String reason ){
    super ( reason );
    }
    }

    class TooHot extends BadTemperature{

    TooHot(){
    super (”Default messaeg : Hot”);
    }

    TooHot(String message){
    super (message);
    }
    }

    class TooCold extends BadTemperature{

    TooCold(){
    super (”Default messaeg : Cold”);
    }

    TooCold(String message){
    super (message);
    }
    }

    class TempertureObject{

    int temperature;

    TempertureObject( int temp ) {
    temperature = temp;
    }

    void test() throws TooHot, TooCold {
    if ( temperature < 70 ) throw new TooCold(”Very Cold”);
    if ( temperature > 80 ) throw new TooHot(”Very Hot”);
    }
    }

    public class ExceptionExample1{

    private static void temperatureReport( TempertureObject batch ){
    try{ batch.test();
    System.out.println( “Perfect Temperature” );
    }
    catch ( BadTemperature bt ){
    System.out.println( bt.getMessage( ) );
    }
    }

    public static void main( String[] args ){
    temperatureReport( new TempertureObject( 100 ) );
    temperatureReport( new TempertureObject( 50 ) );
    temperatureReport( new TempertureObject( 75 ) );
    }
    }


    Output

    Very Hot
    Very Cold
    Perfect Temperature

    throw, throws statement

    A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.

    The general format of the throw statement is as follows:

    throw ;

    The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed to the constructor when the exception object is created.

    throw new TemperatureException(”Too hot”);

    A throws clause can be used in the method prototype.

    Method() throws ,…, {

    }

    Each can be a checked or unchecked or sometimes even a custom Exception. The exception type specified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. Also an overriding method cannot allow more checked exceptions in its throws clause than the inherited method does.

    When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. Any associated finally block of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, execution resumes with the code in its catch block. Below is an example to show the use of a throws and a throw statement.

    public class DivideException3 {

    public static void main(String[] args) {
    try{
    int result = division(100,10);
    result = division(100,0);
    System.out.println(”result : “+result);
    }
    catch(ArithmeticException e){
    System.out.println(”Exception : “+ e.getMessage());
    }
    }

    public static int division(int totalSum, int totalNumber) throws ArithmeticException {
    int quotient = -1;
    System.out.println(”Computing Division.”);
    try{
    if(totalNumber == 0){
    throw new ArithmeticException(”Division attempt by 0″);
    }
    quotient = totalSum/totalNumber;

    }
    finally{
    if(quotient != -1){
    System.out.println(”Finally Block Executes”);
    System.out.println(”Result : “+ quotient);
    }else{
    System.out.println(”Finally Block Executes. Exception Occurred”);
    }

    }
    return quotient;
    }
    }


    Output

    Computing Division.
    Finally Block Executes
    Result : 10
    Computing Division.
    Finally Block Executes. Exception Occurred
    Exception : Division attempt by 0

    Using break and return with Exceptions

    This example demonstrates the use of the break, continue and return statements with exceptions. Note that the finally block is executed always except when the return statement is executed.

    public class ExceptionExample6 {

    public static void main(String[] args) {

    int x = 10, y = 2;
    int counter = 0;
    boolean flag = true;
    while (flag) {
    start:
    try {
    if ( y > 1 )
    break start;
    if ( y < 0 )
    return;
    x = x / y;
    System.out.println ( “x : ” + x + ” y : “+y );
    }
    catch ( Exception e ) {
    System.out.println ( e.getMessage() );
    }
    finally {
    ++counter;
    System.out.println ( “Counter : ” + counter );
    }
    –y;
    }
    }
    }


    Output

    Counter : 1
    x : 10 y : 1
    Counter : 2
    / by zero
    Counter : 3
    Counter : 4

    Handling Multiple Exceptions

    It should be known by now that we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that can be generated. Below is a program to demonstrate the use of multiple catch blocks.

    import java.io.DataInputStream;
    import java.io.IOException;

    import javax.swing.JOptionPane;
    public class ExceptionExample7{
    static int numerator, denominator;

    public ExceptionExample7( int t, int b ){
    numerator = t;
    denominator = b;
    }

    public int divide( ) throws ArithmeticException{
    return numerator/denominator;
    }

    public static void main( String args[] ){

    String num, denom;

    num = JOptionPane.showInputDialog(null, “Enter the Numerator”);
    denom = JOptionPane.showInputDialog(null, “Enter the Denominator”);

    try{
    numerator = Integer.parseInt( num );
    denominator = Integer.parseInt( denom );
    }
    catch ( NumberFormatException nfe ){
    System.out.println( “One of the inputs is not an integer” );
    return;
    }
    catch ( Exception e ){
    System.out.println( “Exception: ” + e.getMessage( ) );
    return;
    }

    ExceptionExample7 d = new ExceptionExample7( numerator, denominator );
    try{
    double result = d.divide( );
    JOptionPane.showMessageDialog(null, “Result : ” + result);
    }
    catch ( ArithmeticException ae ){
    System.out.println( “You can’t divide by zero” );
    }
    finally{
    System.out.println( “Finally Block is always Executed” );
    }
    }
    }


    Java Method Overriding

    Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass, following which the new method implementation in the subclass that is executed.
    The new method definition must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen it. The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class

    A program to explain the different concepts of Java Method Overridding

    class CustomException extends Exception {

    }

    class SuperClassWithDifferentMethods {

    protected int field1 = 10;
    protected static int field2 = 20;
    public void method1() {
    System.out.println("SuperClassWithDifferentMethods.method1()");
    }
    public final void method2() {
    System.out.println("SuperClassWithDifferentMethods.method2()");
    }
    private void method3() {
    System.out.println("SuperClassWithDifferentMethods.method3()");
    }
    private final void method4() {
    System.out.println("SuperClassWithDifferentMethods.method4()");
    }
    public static void method5() {
    System.out.println("SuperClassWithDifferentMethods.method5()");
    }
    public void method6() throws Exception {
    System.out.println("SuperClassWithDifferentMethods.method6()");
    }
    private void method7() {
    System.out.println("SuperClassWithDifferentMethods.method7()");
    }
    private void method8(int x) {
    System.out.println("SuperClassWithDifferentMethods.method8()");
    }
    public static void method9() {
    System.out.println("SuperClassWithDifferentMethods.method9()");
    }
    }

    class OverridingClass extends SuperClassWithDifferentMethods {

    public int field1 = 30;
    public static int field2 = 40;
    public void method1() {
    System.out.println("OverridingClass.method1()");
    }
    //We can't override a public final method
    /* public final void method2(){

    System.out.println("OverridingClass.method2()");

    }*/
    private void method3() {
    System.out.println("OverridingClass.method3()");
    }
    private final void method4() {
    System.out.println("OverridingClass.method4()");
    }
    public static void method5() {
    System.out.println("OverridingClass.method5()");
    }
    public void method6() throws CustomException {
    System.out.println("OverridingClass.method6()");
    }
    public void method7() {
    System.out.println("OverridingClass.method7()");
    }
    public void method8(final int x) {
    System.out.println("OverridingClass.method8()");
    }
    //A static method cannot be overridden to be non-static instance method
    /*public void method9() {

    System.out.println("OverridingClass.method9()");

    }*/
    }

    public class MethodOverridingDemo {

    public static void main(String[] args) {
    OverridingClass oc1 = new OverridingClass();
    SuperClassWithDifferentMethods sc3 = new OverridingClass();
    oc1.method1();
    oc1.method2();
    // Since its private, the below 2 methods are not visible
    /* oc1.method3();

    oc1.method4();*/
    oc1.method5();
    try {
    oc1.method6();
    } catch (CustomException e) {
    e.printStackTrace();
    }
    oc1.method7();
    oc1.method8(100);
    System.out.println(”oc1.field1 : ” + oc1.field1);
    System.out.println(”oc1.field2 : ” + oc1.field2);
    System.out.println(”sc3.field1 : ” + sc3.field1);
    System.out.println(”sc3.field2 : ” + sc3.field2);
    sc3.method5();
    OverridingClass overClass = new OverridingClass();
    SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass;
    supClass.method5();
    supClass.method1();
    }
    }


    Output

    OverridingClass.method1()
    SuperClassWithDifferentMethods.method2()
    OverridingClass.method5()
    OverridingClass.method6()
    OverridingClass.method7()
    OverridingClass.method8()
    oc1.field1 : 30
    oc1.field2 : 40
    sc3.field1 : 10
    sc3.field2 : 20
    SuperClassWithDifferentMethods.method5()
    SuperClassWithDifferentMethods.method5()
    OverridingClass.method1()

    Download MethodOverridingDemo.java

    The new method definitions in the subclass OverridingClass have the same signature and the same return type as the methods in the superclass SuperClassWithDifferentMethods. The new overridden method6 definition specifies a subset of the exceptions (CustomException). The new overridden method7 definition also widens the accessibility to public from private. The overriding method8 also declares the parameter to be final, which is not a part of the method signature and Method Overriding holds good. A static method cannot be overridden to be non-static instance method as shown in the overridden method declaration of method9. A static method is class-specific and not part of any object, while overriding methods are invoked on behalf of objects of the subclass. There are no such restrictions on the fields, as for fields only the field names matter. A final method cannot be overridden, an attempt to which will result in a compile-time error. A private method is not accessible outside the class in which it is defined; therefore, a subclass cannot override it.

    A subclass must use the ‘super’ keyword in order to invoke an overridden method in the superclass. A subclass cannot override fields of the superclass, but it can hide them. Code in the subclass can use the keyword super to access members, including hidden fields.

    The following distinction between invoking instance methods on an object and accessing fields of an object must be noted. When an instance method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference, that determines which method implementation will be executed. When a field of an object is accessed using a reference, it is the type of the reference, not the class of the current object denoted by the reference, that determines which field will actually be accessed. This is demonstrated in the above program

    AddThis

    Java Abstract class and Interface

    Abstract Class in java

    Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

    Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

    Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.

    A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.

    abstract class Vehicle {

    int numofGears;
    String color;
    abstract boolean hasDiskBrake();
    abstract int getNoofGears();
    }

    Example of a shape class as an abstract class

    abstract class Shape {

    public String color;
    public Shape() {
    }
    public void setColor(String c) {
    color = c;
    }
    public String getColor() {
    return color;
    }
    abstract public double area();
    }

    We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

    public class Point extends Shape {

    static int x, y;
    public Point() {
    x = 0;
    y = 0;
    }
    public double area() {
    return 0;
    }
    public double perimeter() {
    return 0;
    }
    public static void print() {
    System.out.println("point: " + x + "," + y);
    }
    public static void main(String args[]) {
    Point p = new Point();
    p.print();
    }
    }

    Output

    point: 0, 0

    Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methods of the Shape class must be implemented by the Point class.

    The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.

    A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

    Java Interface

    In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated.

    Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.

    If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class.

    Example 1: Below is an example of a Shape interface

    interface Shape {

    public double area();
    public double volume();
    }

    Below is a Point class that implements the Shape interface.

    public class Point implements Shape {

    static int x, y;
    public Point() {
    x = 0;
    y = 0;
    }
    public double area() {
    return 0;
    }
    public double volume() {
    return 0;
    }
    public static void print() {
    System.out.println(”point: ” + x + “,” + y);
    }
    public static void main(String args[]) {
    Point p = new Point();
    p.print();
    }
    }

    Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface.

    Example 2: Below is a java interfaces program showing the power of interface programming in java

    Listing below shows 2 interfaces and 4 classes one being an abstract class.
    Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the implemented interface I2, the class D1 is declared abstract.
    Also,
    i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.

    When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as every interface or class extends Object and any class can override the default toString() to suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they are “siblings”. You can’t cast siblings into one another.

    When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and overridden methods.

    interface I1 {

    void methodI1(); // public static by default
    }

    interface I2 extends I1 {

    void methodI2(); // public static by default
    }

    class A1 {

    public String methodA1() {
    String strA1 = "I am in methodC1 of class A1";
    return strA1;
    }
    public String toString() {
    return "toString() method of class A1";
    }
    }

    class B1 extends A1 implements I2 {

    public void methodI1() {
    System.out.println("I am in methodI1 of class B1");
    }
    public void methodI2() {
    System.out.println("I am in methodI2 of class B1");
    }
    }

    class C1 implements I2 {

    public void methodI1() {
    System.out.println("I am in methodI1 of class C1");
    }
    public void methodI2() {
    System.out.println("I am in methodI2 of class C1");
    }
    }

    // Note that the class is declared as abstract as it does not
    // satisfy the interface contract
    abstract class D1 implements I2 {

    public void methodI1() {
    }
    // This class does not implement methodI2() hence declared abstract.
    }

    public class InterFaceEx {

    public static void main(String[] args) {
    I1 i1 = new B1();
    i1.methodI1(); // OK as methodI1 is present in B1
    // i1.methodI2(); Compilation error as methodI2 not present in I1
    // Casting to convert the type of the reference from type I1 to type I2
    ((I2) i1).methodI2();
    I2 i2 = new B1();
    i2.methodI1(); // OK
    i2.methodI2(); // OK
    // Does not Compile as methodA1() not present in interface reference I1
    // String var = i1.methodA1();
    // Hence I1 requires a cast to invoke methodA1
    String var2 = ((A1) i1).methodA1();
    System.out.println(”var2 : ” + var2);
    String var3 = ((B1) i1).methodA1();
    System.out.println(”var3 : ” + var3);
    String var4 = i1.toString();
    System.out.println(”var4 : ” + var4);
    String var5 = i2.toString();
    System.out.println(”var5 : ” + var5);
    I1 i3 = new C1();
    String var6 = i3.toString();
    System.out.println(”var6 : ” + var6); // It prints the Object toString() method
    Object o1 = new B1();
    // o1.methodI1(); does not compile as Object class does not define
    // methodI1()
    // To solve the probelm we need to downcast o1 reference. We can do it
    // in the following 4 ways
    ((I1) o1).methodI1(); // 1
    ((I2) o1).methodI1(); // 2
    ((B1) o1).methodI1(); // 3
    /*
    *
    * B1 does not have any relationship with C1 except they are “siblings”.
    *
    * Well, you can’t cast siblings into one another.
    *
    */
    // ((C1)o1).methodI1(); Produces a ClassCastException
    }
    }

    Output

    I am in methodI1 of class B1
    I am in methodI2 of class B1
    I am in methodI1 of class B1
    I am in methodI2 of class B1
    var2 : I am in methodC1 of class A1
    var3 : I am in methodC1 of class A1
    var4 : toString() method of class A1
    var5 : toString() method of class A1
    var6 : C1@190d11
    I am in methodI1 of class B1
    I am in methodI1 of class B1
    I am in methodI1 of class B1

    Java Object Typecasting

    Object Reference Type Casting

    In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.

    How to Typecast Objects with a dynamically loaded Class ? - The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.
    There can be 2 casting java scenarios

    · Upcasting
    · Downcasting

    When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case.

    The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to.

    Below is an example showing when a ClassCastException can occur during object casting

    //X is a supper class of Y and Z which are sibblings.
    public class RunTimeCastDemo {

    public static void main(String args[]) {
    X x = new X();
    Y y = new Y();
    Z z = new Z();
    X xy = new Y(); // compiles ok (up the hierarchy)
    X xz = new Z(); // compiles ok (up the hierarchy)
    // Y yz = new Z(); incompatible type (siblings)
    // Y y1 = new X(); X is not a Y
    // Z z1 = new X(); X is not a Z
    X x1 = y; // compiles ok (y is subclass of X)
    X x2 = z; // compiles ok (z is subclass of X)
    Y y1 = (Y) x; // compiles ok but produces runtime error
    Z z1 = (Z) x; // compiles ok but produces runtime error
    Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
    Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
    // Y y3 = (Y) z; inconvertible types (siblings)
    // Z z3 = (Z) y; inconvertible types (siblings)
    Object o = z;
    Object o1 = (Y) o; // compiles ok but produces runtime error
    }
    }



    Casting Object References: Implicit Casting using a Compiler

    In general an implicit cast is done when an Object reference is assigned (cast) to:

    * A reference variable whose type is the same as the class from which the object was instantiated.
    An Object as Object is a super class of every Class.
    * A reference variable whose type is a super class of the class from which the object was instantiated.
    * A reference variable whose type is an interface that is implemented by the class from which the object was instantiated.
    * A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated.

    Consider an interface Vehicle, a super class Car and its subclass Ford. The following example shows the automatic conversion of object references handled by the compiler

    interface Vehicle {
    }
    class Car implements Vehicle {
    }

    class Ford extends Car {
    }

    Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign the Ford reference to the Car variable:
    I.e. we can do the following

    Example 1
    c = f; //Ok Compiles fine

    Where c = new Car();
    And, f = new Ford();
    The compiler automatically handles the conversion (assignment) since the types are compatible (sub class - super class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.

    Example 2
    v = c; //Ok Compiles fine
    c = v; // illegal conversion from interface type to class type results in compilation error

    Where c = new Car();
    And v is a Vehicle interface reference (Vehicle v)

    The compiler automatically handles the conversion (assignment) since the types are compatible (class – interface relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car is a Vehicle).

    Casting Object References: Explicit Casting

    Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a particular scenario. The explicit cast is nothing but the name of the new “type” inside a pair of matched parentheses. As before, we consider the same Car and Ford Class

    class Car {
    void carMethod(){
    }
    }

    class Ford extends Car {
    void fordMethod () {
    }
    }

    We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input parameter.
    The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is a Ford object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run time.

    public void breakingSystem (Car obj) {
    obj.carMethod();
    if (obj instanceof Ford)

    ((Ford)obj).fordMethod ();
    }

    To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if it is a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod() cannot be found in the Car definition.


    The following program shown illustrates the use of the cast operator with references.

    Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class will automatically extends the Object by default. This code instantiates an object of the class Ford and assigns the object’s reference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford. In order to use a reference of a class type to invoke a method, the method must be defined at or above that class in the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method fordMethod is not present in Class Car or any of its superclasses. Hence this problem can be colved by a simple downcast by casting the Car object reference to the Ford Class Object reference as done in the program. Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime, although compilation happens without any error.


    class Car extends Object {

    void carMethod() {
    }
    }

    class HeavyVehicle extends Object {
    }

    class Ford extends Car {

    void fordMethod() {
    System.out.println(”I am fordMethod defined in Class Ford”);
    }
    }

    class Honda extends Car {

    void fordMethod() {
    System.out.println(”I am fordMethod defined in Class Ford”);
    }
    }

    public class ObjectCastingEx {

    public static void main(String[] args) {
    Car obj = new Ford();
    // Following will result in compilation error
    // obj.fordMethod(); //As the method fordMethod is undefined for the Car Type
    // Following will result in compilation error
    // ((HeavyVehicle)obj).fordMethod();
    //fordMethod is undefined in the HeavyVehicle Type
    // Following will result in compilation error
    ((Ford) obj).fordMethod();
    //Following will compile and run
    // Honda hondaObj = (Ford)obj; Cannot convert as they are sibblings
    }
    }

    Code

    One common casting that is performed when dealing with collections is, you can cast an object reference into a String.

    import java.util.Vector;

    public class StringCastDemo {

    public static void main(String args[]) {
    String username = “asdf”;
    String password = “qwer”;
    Vector v = new Vector();
    v.add(username);
    v.add(password);
    // String u = v.elementAt(0); Cannot convert from object to String
    Object u = v.elementAt(0); //Cast not done
    System.out.println(”Username : ” + u);
    String uname = (String) v.elementAt(0); // cast allowed
    String pass = (String) v.elementAt(1); // cast allowed
    System.out.println();
    System.out.println(”Username : ” + uname);
    System.out.println(”Password : ” + pass);
    }
    }



    Output

    Username : asdf
    Username : asdf
    Password : qwer

    instanceof Operator

    The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a specific class, or implements a specific interface. It returns true if an object is an instance of the class or if the object implements the interface, otherwise it returns false.

    Below is an example showing the use of instanceof operator

    class Vehicle {

    String name;
    Vehicle() {
    name = "Vehicle";
    }
    }

    class HeavyVehicle extends Vehicle {

    HeavyVehicle() {
    name = "HeavyVehicle";
    }
    }

    class Truck extends HeavyVehicle {

    Truck() {
    name = "Truck";
    }
    }

    class LightVehicle extends Vehicle {

    LightVehicle() {
    name = "LightVehicle";
    }
    }

    public class InstanceOfExample {

    static boolean result;
    static HeavyVehicle hV = new HeavyVehicle();
    static Truck T = new Truck();
    static HeavyVehicle hv2 = null;
    public static void main(String[] args) {
    result = hV instanceof HeavyVehicle;
    System.out.print(”hV is an HeavyVehicle: ” + result + “\n”);
    result = T instanceof HeavyVehicle;
    System.out.print(”T is an HeavyVehicle: ” + result + “\n”);
    result = hV instanceof Truck;
    System.out.print(”hV is a Truck: ” + result + “\n”);
    result = hv2 instanceof HeavyVehicle;
    System.out.print(”hv2 is an HeavyVehicle: ” + result + “\n”);
    hV = T; //Sucessful Cast form child to parent
    T = (Truck) hV; //Sucessful Explicit Cast form parent to child
    }
    }

    Download instanceof operator Source Code

    Output

    hV is an HeavyVehicle: true
    T is an HeavyVehicle: true
    hV is a Truck: false
    hv2 is an HeavyVehicle: false

    Note: hv2 does not yet reference an HeavyVehicle object, instanceof returns false. Also we can’t use instanceof operator with siblings

    Java Inheritance

    Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.

    For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.

    class Box {

    double width;
    double height;
    double depth;
    Box() {
    }
    Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
    }
    void getVolume() {
    System.out.println("Volume is : " + width * height * depth);
    }
    }

    public class MatchBox extends Box {

    double weight;
    MatchBox() {
    }
    MatchBox(double w, double h, double d, double m) {
    super(w, h, d);
    weight = m;
    }
    public static void main(String args[]) {
    MatchBox mb1 = new MatchBox(10, 10, 10, 10);
    mb1.getVolume();
    System.out.println(”width of MatchBox 1 is ” + mb1.width);
    System.out.println(”height of MatchBox 1 is ” + mb1.height);
    System.out.println(”depth of MatchBox 1 is ” + mb1.depth);
    System.out.println(”weight of MatchBox 1 is ” + mb1.weight);
    }
    }

    Output

    Volume is : 1000.0
    width of MatchBox 1 is 10.0
    height of MatchBox 1 is 10.0
    depth of MatchBox 1 is 10.0
    weight of MatchBox 1 is 10.0


    What is not possible using java class Inheritance?

    1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
    2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
    3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
    4. A subclass can extend only one superclass

    class Vehicle {

    // Instance fields
    int noOfTyres; // no of tyres
    private boolean accessories; // check if accessorees present or not
    protected String brand; // Brand of the car
    // Static fields
    private static int counter; // No of Vehicle objects created
    // Constructor
    Vehicle() {
    System.out.println("Constructor of the Super class called");
    noOfTyres = 5;
    accessories = true;
    brand = "X";
    counter++;
    }
    // Instance methods
    public void switchOn() {
    accessories = true;
    }
    public void switchOff() {
    accessories = false;
    }
    public boolean isPresent() {
    return accessories;
    }
    private void getBrand() {
    System.out.println("Vehicle Brand: " + brand);
    }
    // Static methods
    public static void getNoOfVehicles() {
    System.out.println("Number of Vehicles: " + counter);
    }
    }

    class Car extends Vehicle {

    private int carNo = 10;
    public void printCarInfo() {
    System.out.println("Car number: " + carNo);
    System.out.println("No of Tyres: " + noOfTyres); // Inherited.
    // System.out.println("accessories: " + accessories); // Not Inherited.
    System.out.println("accessories: " + isPresent()); // Inherited.
    // System.out.println("Brand: " + getBrand()); // Not Inherited.
    System.out.println("Brand: " + brand); // Inherited.
    // System.out.println("Counter: " + counter); // Not Inherited.
    getNoOfVehicles(); // Inherited.
    }
    }

    public class VehicleDetails { // (3)

    public static void main(String[] args) {
    new Car().printCarInfo();
    }
    }

    Output

    Constructor of the Super class called
    Car number: 10
    No of Tyres: 5
    accessories: true
    Brand: X
    Number of Vehicles: 1


    this and super keywords

    The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.

    The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

    class Counter {

    int i = 0;
    Counter increment() {
    i++;
    return this;
    }
    void print() {
    System.out.println("i = " + i);
    }
    }

    public class CounterDemo extends Counter {

    public static void main(String[] args) {
    Counter x = new Counter();
    x.increment().increment().increment().print();
    }
    }

    Output

    Volume is : 1000.0
    width of MatchBox 1 is 10.0
    height of MatchBox 1 is 10.0
    depth of MatchBox 1 is 10.0
    weight of MatchBox 1 is 10.0