Category: Java

#1 Class Access Types

Class can be declared with public and default access-modifiers and abstract, final non-access-modifiers.

Where as inner classes can include all access modifiers public, private, default and protected.

Singleton – Creational Design Pattern

Singleton Design Pattern is one of the creational design pattern which creates only one instance of the class. Only one instance of the class is created per Java Virtual Machine. Singleton pattern is used for logging, drivers object and thread pool. There are different ways to create singleton design pattern, but all of them follow three concepts

  1. private constructor to restrict access to other classes.
  2. private static variable of the same class that is only instance of the class.
  3. public static method to return the instance of the class.
class SingletonPattern {
   private static SingletonPattern defaultInstance;
   private SingletonPattern() { }
   public static SingletonPattern getInstance() {
      if(defaultInstance == null) {
         System.out.println("Singleton Pattern Default Instance Created");
         defaultInstance = new SingletonPattern();
      return defaultInstance;

The above singleton class is not thread-safe and may not be useful in multi-thread environment. Need to take necessary steps to make it thread safe. The below method of creating singleton pattern is the most widely used and doesn’t require any synchronization techniques.

class SingletonPattern {
    private SingletonPattern() { }	
    private static class SingletonHelper {
        private static final SingletonPattern INSTANCE = new SingletonPattern();
    public static SingletonPattern getInstance() {
        return SingletonHelper.INSTANCE;

Design Patterns – Introduction

Design Patterns are proven solutions provided to commonly occurred problems while designing software solution. They evolved over years to resolve most common problems, so we can follow them blindly without any hesitation.

Are Design Patterns dependent on any programming language? No, Design Pattern is an approach, it is not tied to any programming language. Once understood can be applied in any programming language.

Little History from wiki-

Patterns originated as an architectural concept by Christopher Alexander (1977/79). In 1987, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming – specifically pattern languages – and presented their results at the OOPSLA conference that year. In the following years, Beck, Cunningham and others followed up on this work.

Design patterns gained popularity in computer science after the book Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994 by the so-called “Gang of Four” (Gamma et al.), which is frequently abbreviated as “GoF”.

GoF Design Patterns are foundation for all the design patterns out there. They are 23 in number divided into three categories.

  1. Creational Patterns – Different ways of creating objects.
    • Singleton
    • Factory
    • Abstract Factory
    • Prototype
    • Builder
  2. Structural Patterns – Different ways of orgainising classes and objects, using associations and aggregations to form complex structures.
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  3. Behavioural Patterns – Interaction/Communication b/w objects, they help to keep communication loosely coupled.
    • Chain of responsibility
    • Command
    • Interceptor
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template method
    • Visitor

We will discuss each one of these patterns in details in the subsequent posts.

SwingUtilites – invokeAndWait() and invokeLater()

In Java after swing components displayed on the screen they should be operated by only one thread called “Event Handling Thread or Event Thread”. We have an another alternative to make changes to Swing components. We can write our code in a separate block and can give this block reference to Event thread.

The SwingUtilitiesclass has a static invokeAndWait() and invokeLater() method available to use to put references to blocks of code onto the event queue

                    public static void invokeAndWait (Runnable target)
                           throws InterruptedException, InvocationTargetException

                    public static void invokeLater (Runnable target)

The parameter target is a reference to an instance of Runnable. In this case the Runnable will not be passed to the constructor of Thread. The Runnable interface is simply being used as a means to identify the entry point for the event thread. Just as a newly spawned thread will invoke run(), the event thread will invoke run() when it has processed all the other events pending in the queue. An InterruptedExceptionis thrown if the thread that called invokeAndWait() or invokeLater() is interrupted before the block of code referred to by target completes. An InvocationTargetException is thrown if an uncaught exception is thrown by the code inside run().

New thread is not created when we place runnable in SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() event thread will call run method of runnable when it trun comes up on event queue.

SwingUtilites.invokeAndWait() example:

import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class InvokeAndWaitMain {
	public static void main(String[] args) {
		final JButton button = new JButton("Not Changed");
		JPanel panel = new JPanel();
		JFrame f = new JFrame("InvokeAndWaitMain");
		f.setSize(300, 100);
		System.out.println(Thread.currentThread().getName()+" is going into sleep for 3 sec");
		}catch(Exception e){

		//Preparing code for label change
		Runnable r = new Runnable(){
			public void run() {
				System.out.println(Thread.currentThread().getName()+" is going into sleep for 10 sec");
				}catch(Exception e){

				button.setText("Button Text Changed by "+Thread.currentThread().getName());
				System.out.println("Button changes ended");

		//putting the component change on to event thread using SwingUtilties.invokeAndWait()
		System.out.println("Component changes put on the event thread by main thread");
		try {
		} catch (InvocationTargetException | InterruptedException e) {
		System.out.println("Main thread reached end");
                //output for invokeAndWait()
		/*main is going into sleep for 3 sec
		Component changes put on the event thread by main thread
		AWT-EventQueue-0 is going into sleep for 10 sec
		After 10sec Button changes ended
		Main thread reached end*/

		//output for invokeLater()
		/*main is going into sleep for 3 sec
		Component changes put on the event thread by main thread
		Main thread reached end
		AWT-EventQueue-0 is going into sleep for 10 sec
		After 10sec Button changes ended*/

Replace try/catch block from line 40-44 with SwingUtilites.invokeLater(r) for invokeLater() example.

Main difference between invokeAndWait() and invokeLater() is invokeAndWait() keeps the code on to event thread and waits till the execution of run method is completed whereas invokeLater() keeps the code on event thread and runs the rest of code in the thread.


Java’s Void (‘V’ capital)

Yesterday when I was searching for something related to ProgressBar came across something called “Void”. I know about “void” which we use as a return type of method but I have never heard of “Void”.

So what is this “Void” ? when it is used ? Let’s have a look into it.

“Void” was there in java since JDK1.1. There are 8 predefined objects to represent eight primitive types and one more object to represent primitive type “void(‘v’ small)”. These objects can only be accessed via  public static final variables like INTEGER.TYPE, BOOLEAN.TYPE, VOID.TYPE etc.. Please see the

/*Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.*/

package java.lang;
public final class Void {
     * The {@code Class} object representing the pseudo-type corresponding to
     * the keyword {@code void}.
    public static final Class<Void> TYPE = Class.getPrimitiveClass("void");

     * The Void class cannot be instantiated.
    private Void() {}

As the class is final and constructor is private it can’t be instantiated nor extented to create a sub class. Therefore only value that can be assigned to variable of type Void is null. So you can think “Void” as an wrapper for primitive type “void” like “Integer” for “int”.

Void.TYPE is an object that represents void type and is returned by java.lang.reflect.Method.getReturnType() see the example below

public class VoidExample {
	public static void main(String[] args) throws Exception {
		Class testClass = VoidClass.class.getMethod("VoidMethod", null).getReturnType();
		System.out.println(testClass == Void.TYPE);
class VoidClass {
	public void VoidMethod() {}

After introduction of generics concepts this Void object is used more often in cases like Generic structure requires a class name but you didn’t want to use any class to use the structure. Generics accept only objects but not primitive types

Example: List<int>          // compilation error
List<Integer> //no compilation error

There are lot of examples where we can use them. The one which I have came across is SwingWorker<Void, Void>. This is used to create a background thread which completes defined job without freezing the actual thread on which program runs. You can have lot of examples on SwingWorker<Void, Void> you can have a look at them.

Pass By Reference in Java

Pass-By-Value: Pass-By-Value means to pass value from calling function to called function. The value passed will be local to function called and any changes to the passed value will not be reflected in original value passed.

Pass-By-Reference: Pass-by-reference means to pass the reference of value in the calling function to the called function. The called function can modify the value by using the reference passed in.

Java is strictly Pass-By-Value. But it do support a kind of Pass-By-Reference through java objects. When java objects are passed it doesn’t actually pass the object, it makes a copy of object’s reference value and passes it. It means both the original and copied object references will point to common reference which means any changes to object’s value in called method will reflect in original object.

Let’s see an example

public class PassByRefExample {
	public static void main(String args[]){
		ObjectReference reference = new ObjectReference();
		reference.value="Value assigned !!!";
		ReferenceClass referenceClass = new ReferenceClass();

class ReferenceClass{
	public void ChangeValue(ObjectReference objectReference){
		objectReference.value = "Value Changed !!!";

class ObjectReference{
	public Object value;


String Vs String Buffer in Java

String: String is immutable means we can’t modify a string object once it is created. We can replace it by another instance of String.

StringBuffer: StringBuffer is mutable means it’s value can be changed.

Taking into consideration that your string operations are not in any thread. StringBuffer is more efficient way than using String if your string contains more computations . If string is modified in a thread then it is better to use String class because immutable classes are thread safe.

Let’s see an example

public class StringVsStringBuffer {
	public static void main(String args[]){
		long startTime = System.currentTimeMillis();
		String message = "append to";
		for(int i=0; i<1000;i++){
			message = message + i + " ";
			//Here String objects are created and destroyed immediately.
			// Creating instances involves more effort
		long stopTime = System.currentTimeMillis();
		System.out.println("Run time for String.."+(stopTime-startTime));
		// Output on Average : 12ms
		startTime = System.currentTimeMillis();
		StringBuffer messageBuffer = new StringBuffer();
		for(int i=0; i<1000;i++){
			//Here only one object is created and is used through out the loop
			messageBuffer = messageBuffer.append(i + " ");
		stopTime = System.currentTimeMillis();
		System.out.println("Run time for String Buffer.."+(stopTime-startTime));
		//Output on Average : 4ms