Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Java Swings Tutorial


Java Swings Tutorial

What is Swings in java ?
  • A part of The JFC
  • Swing Java consists of
    Look and feel
    Accessibility
    Java 2D
    Drag and Drop, etc
  • Compiling & running programs
  • ‘javac <program.java>’ && ‘java <program>’ Or JCreator / IDE
  • if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen.
  • Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT.
Swing Model/view design: The “view part” of the MV design is implemented with a component object and the UI object. The “model part” of the MV design is implemented by a model object and a change listener object.


Swing is built on top of AWT and is entirely written in Java, using AWT’s lightweight component support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.
  • 100% Java implementation of components
  • Pluggable Look & Feel
  • Lightweight components
  • Uses MVC ArchitectureModel represents the data
    View as a visual representation of the data
    Controller takes input and translates it to changes in data
  • Three parts 
    Component set (subclasses of JComponent)
    Support classes
    Interfaces
In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing — twice as many as in AWT.
Java Swing class hierarchy
The class JComponent, descended directly from Container, is the root class for most of Swing’s user interface components.

Swing contains components that you’ll use to build a GUI. I am listing you some of the commonly used Swing components. To learn and understand these swing programs, AWT Programming knowledge is not required.

Java Swing Examples

Below is a java swing code for the traditional Hello World program.
Basically, the idea behind this Hello World program is to learn how to create a java program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.
import javax.swing.JFrame;
import javax.swing.JLabel;

//import statements
//Check if window closes automatically. Otherwise add suitable code
public class HelloWorldFrame extends JFrame {

 public static void main(String args[]) {
  new HelloWorldFrame();
 }
 HelloWorldFrame() {
  JLabel jlbHelloWorld = new JLabel("Hello World");
  add(jlbHelloWorld);
  this.setSize(100, 100);
  // pack();
  setVisible(true);
 }
}
Output
Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing.
  • JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent.
  • JFrame is Swing’s version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead.
  • JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized and layered.
  • JWindow is Swing’s version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default.
  • JDialog is Swing’s version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow,
    JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current
    thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some
    of the most common dialogs are provided through static methods in the class JOptionPane.
  • JLabel, descended from JComponent, is used to create text labels.
  • The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including
    JButton.
  • JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font.
  • JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character.
    This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *.
  • JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar;
    JButton is a component the user clicks to trigger a specific action.
  • JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only
    one button at a time can be selected.
  • JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state.
  • JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus,
    pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.
  • JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not
    support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined
    border. JList actions are handled using ListSelectionListener.
  • JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image.
  • JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components
    within the toolbar.
  • FlowLayout when used arranges swing components from left to right until there’s no more space available. Then it begins a new row below it and moves
    from left to right again. Each component in a FlowLayout gets as much space as it needs and no more.
  • BorderLayout places swing components in the North, South, East, West and center of acontainer. You can add horizontal and vertical gaps between
    the areas.
  • GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles,
    and one component is placed in each rectangle.
  • GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells,
    called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size.
  • JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ’s that you can select. Swing provides support for
    pull-down and popup menus.
  • Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in a popup menu that exceeds the screen visible height.

    Java Swing Projects

  • Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java program source code.
  • Java Swing Address Book demonstrates how to create a simple free address book program using java swing and jdbc. Also you will learn to use
    the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).

Java Date API


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
——————————————————-
Download Date Utility Source Code
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.

Core Collection Interfaces


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

How are Collections Used

  • The collections stores object references, rather than objects themselves. Hence primitive values cannot bestored 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}
Download CollectionsDemo.java

Java Collections Source Code Examples

On the following pages in this tutorial I have described how elements can be manipulated by different collectionsnamely;

Introduction to Threads


Introduction to Threads

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 manythreads, 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
Download Runnable Thread Program Example
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]
Download Java Thread Program Example
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 theThread 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();

Implementing Singleton Pattern


Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton patternbelongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.
The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makesthis method a class level method that can be accessed without creating an object.
One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications.
Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.

Implementing Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:



Step 1: Provide a default Private constructor
public class SingletonObjectDemo {

 // Note that the constructor is private
 private SingletonObjectDemo() {
  // Optional Code
 }
}
Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonObjectDemo {

 private static SingletonObject singletonObject;
 // Note that the constructor is private
 private SingletonObjectDemo() {
  // Optional Code
 }
 public static SingletonObjectDemo getSingletonObject() {
  if (singletonObject == null) {
   singletonObject = new SingletonObjectDemo();
  }
  return singletonObject;
 }
}
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.
Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized SingletonObjectDemo getSingletonObject()
It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration
Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class SingletonClass {

 private static SingletonClass singletonObject;
 /** A private Constructor prevents any other class from instantiating. */
 private SingletonClass() {
  //  Optional Code
 }
 public static synchronized SingletonClass getSingletonObject() {
  if (singletonObject == null) {
   singletonObject = new SingletonClass();
  }
  return singletonObject;
 }
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException();
 }
}

public class SingletonObjectDemo {

 public static void main(String args[]) {
  //  SingletonClass obj = new SingletonClass();
//Compilation error not allowed
  SingletonClass obj = SingletonClass.getSingletonObject();
  // Your Business Logic
  System.out.println("Singleton object obtained");
 }
}

Download
 SingletonObjectDemo.java
Another approach
We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass {

 private static SingletonClass ourInstance = new SingletonClass();
 public static SingletonClass getInstance() {
  return singletonObj;
 }
 private SingletonClass() {
 }
}
In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the class when theapplication is running.

Exceptions in java are any abnorma


Exceptions in java are any abnorma
l, 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 neverescape 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. CheckedExceptions 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 {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}
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 {
    <code>
} catch (<exception type1> <parameter1>) { // 0 or more
    <statements>

}
} finally {                               // finally block
    <statements>
}

Download
 DivideException2.java
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)