Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Questions Answers

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

001 public static void main(String args[]) - Explanation.

public - public means everyone can access it.That means it's in global
scope. As, main method is called by JVM [Java Virtual Machine],
which is actually out of the project scope, the access specifier of this
method is public. static - Java environment should be able to call this
method without creating an instance of the class , so this method must be
declared asstatic. void - the return type of this method is void means
there's no return value. main( ) - the name of the method, main because
it's the main method. String args[] - arguments to this method. This
method must be given an array of Strings, and the array will be called
'args'.

002 What if the main method is declared as private?

The program compiles properly but at run-time it will give "Main method
not public." message

003 What is meant by pass by reference and pass by value in


Java?

Pass by reference means, passing the address itself rather than passing
the value. While, on the other hand, pass by value means passing a copy
of the value. Java, actually works as pass by value. Let’s check this with the
help of 2 examples. Examples: 1. By passing primitive data type: In
the below code, we have written a method called doInt(), which takes a int
value and decrease the value by one and printing it there. Now, from
main() method, we are passing the int i of value 10, then we are printing
from main(). public static void main(String[] args) { int i= 10;
System.out.print("OUTPUT: "); doInt(i); System.out.print(i); } public
static void doInt(int i) { i--; System.out.print(i+", "); } Output: And the
output of the above code is, 9 is printed from the doInt() method, whereas,
it is not reflected in main method, because, it is still printing 10. OUTPUT:
9, 10 Therefore, the conclusion over here is, it is passing the value, instead
of reference. 2. By Passing Object: Now, the second example, by passing
an object. Say, we have a class named, Employee, which has 2 fields
strName and intAge.

class Employee{ private String strName; private int intAge; public


String getStrName() { return strName; } public void setStrName(String
strName) { this.strName = strName; } public int getIntAge() { return
intAge; } public void setIntAge(int intAge) { this.intAge = intAge; }
@Override public String toString() { return "Employee [strName=" +
strName + ", intAge=" + intAge + "]"; } } Now, we will create a method
(with return type void), which will set the name and age of an employee
object. public static void setEmployee(Employee objEmployee)
{ objEmployee.setStrName("James"); objEmployee.setIntAge(22); } Then
we will call this from a main method to test it, we public static void
main(String[] args) { Employee objEmployee = new Employee();
setEmployee(objEmployee); System.out.println(objEmployee); } Output:
And, in the output we can see the value of the attributes of employee
object, is what we set in the setEmployee() method. Employee
[strName=James, intAge=22] Therefore, it looks like the reference has
been passed. Yes, but still, it follows the concept of pass by value, because,
the value of objEmployee is, the memory reference of the actual object.
Therefore, we can say, Java only supports, Pass By Value, not, Pass By
Reference.

004 What is the difference between an Interface and an Abstract


class?

An abstract class can have instance methods that implement a default


behavior. AnInterface can only declare constants and instance methods,
but cannot implement default behavior and all methods are implicitly
abstract. An interface has all public members and no implementation. An
abstract class is a class which may have the usual flavors of class
members (private, protected, etc.), but has some abstract methods.

005 What is the purpose of garbage collection in Java, and when


is it used?

The purpose of garbage collection is to identify and discard objects that are
no longer needed by a program so that their resources can be reclaimed
and reused. A Java object is subject to garbage collection when it becomes
unreachable to the program in which it is used.

006 Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control


the access of multiple threads to shared resources. synchronization, it is
possible for one thread to modify a shared variable while another thread is
in the process of using or updating same shared variable. This usually leads
to significant errors. So, its the mechanism that ensures that only one
thread is accessed the resources at a time.

How to achieve synchronization in java?

In java, synchronization can be achieved by using the synchronized


keyword.

It can be used in 2 ways.

1. on a method signature: We can declare synchronized keyword in


method signature, therefore, that method will be thread safe in multi-
threaded environment. That means, only, one thread at a time can access
this method.

Below, method execute() is synchronized, so it is can be accessed by one


thread at a time.

synchronized void execute(){ // do something }


2. Write synchronized block: Secondly, we can write a synchronized
block, and that block will be synchronized.

synchronized(this){ // do something }

The above code, will lock the object itself, when this piece of code has been
executed by a thread.

007 What is the Java API?

An application programming interface (API) is a library of functions


that Java provides for programmers for common tasks like file transfer,
networking, and data structures.

List of Java APIs:

There are three types of APIs in Java.

· the official core Java API, contained in the JDK or JRE, of one of the
editions of the Java Platform. The three editions of the Java Platform are
Java ME (Micro edition), Java SE (Standard edition), and Java EE
(Enterprise edition).

· optional official APIs that can be downloaded separately. The


specification of these APIs are defined according to a Java Specification
Request (JSR), and sometimes some of these APIs are later included in the
core APIs of the platform (the most notable example of this kind is Swing).

· unofficial APIs, developed by third parties, but not related to any JSRs.

008 Explain different way of using thread?

There are 2 ways of using thread -

1. By implementing runnable interface.

2. By extending the Thread class.


009 Difference between Runnable Interface and Thread class
while using threads.

1. If you want to extend the Thread class then it will make your class unable
to extend other classes as java is having single inheritance feature whereas
If you implement runnable interface, you can gain better object-oriented
design and consistency and also avoid the single inheritance problems.

2. Extending the thread will give you simple code structure in comparison
to Runnable Interface.

3. Using Runnable Interface, you can run class several times whereas
Thread have the start() method that can be called only once.

010 What is HashMap and Map?

Map is Interface and Hashmap is class that implements that.

011 Difference between HashMap and HashTable.

The HashMap class is roughly equivalent to Hashtable, except that it is


unsynchronized and permits nulls. (HashMap allows null values as key
and value whereas Hashtable doesnt allow). HashMap does not
guarantee that the order of the map will remain constant over time.
HashMap is unsynchronized and Hashtable is synchronized.

012 Difference between Vector and ArrayList.

Vector :

1. It's synchronized.http://3.bp.blogspot.com/-
ig4JY8fk2Hc/UUdSPhrsxfI/AAAAAAAAAk8/1cnbnoePofs/s200/Java3.pn
g

2. It's slower than ArrayList.

3. It's generally used in multithreading programs.


ArrayList :

1. It's unsynchronized.

2. It's faster than Vector.

3. It's generally used in single-thread programs.

013 Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally
accessible variables due to following reasons:

 The global variables breaks the referential transparency

 Global variables creates collisions in namespace.

014 What is the difference between a constructor and method?

A constructor is a member function of a class that is used to create


objects of that class. It has the same name as the class itself, has no return
type, and is invoked using the new operator. A method is an ordinary
member function of a class. It has its own name, a return type (which may
be void), and is invoked using the dot operator.

015 What is the difference between a while statement and a do


statement?

A while statement (pre test) checks at the beginning of a loop to see


whether the next loop iteration should occur. A do while statement (post
test) checks at the end of a loop to see whether the next iteration of a loop
should occur. The do statement will always execute the loop body at least
once.

016 What is an Iterator? How is it differ from enumerations?


Some of the collection classes provide traversal of their contents via a
java.util.Iterator interface. This interface allows you to walk through a
collection of objects, operating on each object in turn. Remember when
using Iterators that they contain a snapshot of the collection at the time the
Iterator was obtained; generally it is not advisable to modify the collection
itself while traversing an Iterator. Iterators differ from enumerations in
two ways:

 Iterators allow the caller to remove elements from the underlying


collection during the iteration with well-defined semantics.

 Method names have been improved.

017 Access Specifiers in Java

public access

Fields, methods and constructors declared public (least restrictive) within


a public class are visible to any class inthe Java program, whether these
classes are in the same package or in another package.

private access

The private (most restrictive) fields or methods cannot be used for classes
and Interfaces. It also cannot be used for fields and methods within an
interface. Fields, methods or constructors declared private are strictly
controlled, which means they cannot be accesses by anywhere outside the
enclosing class. A standard design strategy is to make all fields private and
provide public getter methods for them.

protected access

The protected fields or methods cannot be used for classes and Interfaces.
It also cannot be used for fields and methods within an interface. Fields,
methods and constructors declared protected in a superclass can be
accessed only by subclasses in other packages. Classes in the same package
can also access protected fields, methods and constructors as well, even if
they are not a subclass of the protected member’s class.

default access

Java provides a default specifier which is used when no access modifier is


present. Any class, field, method or constructor that has no declared access
modifier is accessible only by classes in the same package. The default
modifier is not used for fields and methods within an interface.

018 What is static in java?

Static means one per class, not one for each object no matter how many
instance of a class might exist. This means that you can use them without
creating an instance of a class.Static methods are implicitly final, because
overriding is done based on the type of the object, and static methods are
attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original
method was not declared final. However, you can't override a static method
with a nonstatic method. In other words, you can't change a static method
into an instance method in a subclass.

019 What is final?

 A final class can't be extended ie., final class may not be subclassed.

 A final method can't be overridden when its class is inherited.

 You can't change value of a final variable (is a constant).

020 What if the static modifier is removed from the signature of


the main method?

Program compiles. But at runtime throws an error “NoSuchMethodError”.


021 What if I write static public void instead of public static
void?

Program compiles and runs properly.

022 What if I do not provide the String array as the argument to


the method?

Program compiles but throws a runtime error


"NoSuchMethodError".

023 What is implicit casting?

Implicit casting is the process of simply assigning one entity to another


without any transformation guidance to the compiler. This type of casting
is not permitted in all kinds of transformations and may not work for all
scenarios.

Example

byte i = 1; short j = i; //Implicit casting

024 Can an application have multiple classes having main


method?

Yes it is possible. While starting the application we mention the class name
to be run. The JVM will look for the Main method only in the class whose
name you have mentioned. Hence there is not conflict amongst the
multiple classes having main method.

025 What if we have multiple main methods in the same class?

No the program fails to compile. The compiler says that the main method is
already defined in the class.

026 What is Method Overriding?


When a method in subclass has the same name and type signature as a
method in its superclass, the the method in the subclass is called to
override the method in the superclass. When an overridden method is
called from within a subclass, it will always refer to the version of that
method defined by the subclass. The version of the method defined by the
superclass will be hidden.

027 What is serialization?

Serialization is the process of writing the state of an object to a byte


stream. It's useful when you want to save the state of your program to a
persistent storage area, such as a file.

028 How to serialize an object to a file?

By implementing an interface Serializable in the class whose instances


are to be serialized.Then passing the instance to the
ObjectOutputStream which is connected to a fileoutputstream. This
will save the object to a file. Example: Now, we will see a practical
implementation of serialization on an object and we will store the
serialized data in a file. Class SampleClass is a pojo class which
implementsjava.io.Serializable . It contains four String fields, one of
which is declared as transient. That means, we can't serialized this field.

Class SampleClass :

package com.interview.question.java; public class SampleClass


implements java.io.Serializable{ /** * * Sample serialized class. * *
@author http://interviewquestionjava.blogspot.com * **/ private static
final long serialVersionUID = 1L; private String strName; private
String strAddress; private String strUsername; /** * * we declared the
variable strPassword as transient. * So, it will be shield from serialization. *
**/ private transient String strPassword; public String getStrName() {
return strName; } public void setStrName(String strName) {
this.strName = strName; } public String getStrAddress() { return
strAddress; } public void setStrAddress(String strAddress) {
this.strAddress = strAddress; } public String getStrUsername() { return
strUsername; } public void setStrUsername(String strUsername) {
this.strUsername = strUsername; } public String getStrPassword() {
return strPassword; } public void setStrPassword(String strPassword) {
this.strPassword = strPassword; } }

Now, Class SerializeObjectToFile, is used to create an object of


SampleClass with some values. Then we serialized that object to a file name
sampleClass.ser. Class SerializeObjectToFile :

package com.interview.question.java; import


java.io.FileNotFoundException; import java.io.FileOutputStream;
import java.io.IOException; import java.io.ObjectOutputStream; public
class SerializeObjectToFile { /** * * This class serialized an Object of
SampleClass * to a file named sampleClass.ser * * @author
http://interviewquestionjava.blogspot.com * **/ public static void
main(String[] args) { SampleClass objSampleClass = new SampleClass();
objSampleClass.setStrName("Ashoka Maurya");
objSampleClass.setStrAddress("Magadha");
objSampleClass.setStrUsername("Chakravartin");
objSampleClass.setStrPassword("Ashokavadana"); try { FileOutputStream
objFileOutputStream = new
FileOutputStream("src/com/interview/question/java/sampleClass.ser");
ObjectOutputStream objOutputStream = new
ObjectOutputStream(objFileOutputStream);
objOutputStream.writeObject(objSampleClass); objOutputStream.close();
objFileOutputStream.close(); System.out.println("SampleClass is serialized
successfully.."); } catch (IOException e) { e.printStackTrace(); } } }

029 Deserializing an Object from File


To deserialize an object from file, first get the serialized data from the
file using FileInputStream. In case if you want to know how to serialize
an object to file please check this article serialize an object to a file.
Pass the FileInputStream object through ObjectInputStream. Now, get
the object from ObjectInputStream using the API readObject().

Example:

Suppose we have a file named sampleClass.ser which contains the data


of a serialized object of class SampleClass. Please check this post to
create this file. Where SampleClass is a normal pojo class with 4 variables,
among which 1 is declared as transient, that means, protected
fromserialization.

Class SampleClass :

package com.interview.question.java; public class SampleClass


implements java.io.Serializable{ /** * * Sample serialized class. * *
@author http://interviewquestionjava.blogspot.com * **/ private static
final long serialVersionUID = 1L; private String strName; private
String strAddress; private String strUsername; /** * * we declared the
variable strPassword as transient. * So, it will be shield from serialization. *
**/ private transient String strPassword; public String getStrName() {
return strName; } public void setStrName(String strName) {
this.strName = strName; } public String getStrAddress() { return
strAddress; } public void setStrAddress(String strAddress) {
this.strAddress = strAddress; } public String getStrUsername() { return
strUsername; } public void setStrUsername(String strUsername) {
this.strUsername = strUsername; } public String getStrPassword() {
return strPassword; } public void setStrPassword(String strPassword) {
this.strPassword = strPassword; } }
Now, during serialization of the object of this SampleClass, we set the
following values.

objSampleClass.setStrName("Ashoka Maurya");
objSampleClass.setStrAddress("Magadha");
objSampleClass.setStrUsername("Chakravartin");
objSampleClass.setStrPassword("Ashokavadana");

Now, we execute the DeserializeFileToObject class, to deserialize the


object of SampleClass.

Class DeserializeFileToObject :

package com.interview.question.java; import java.io.FileInputStream;


import java.io.ObjectInputStream; public class DeserializeFileToObject
{ /** * * This class deserializes data from a file * sampleClass.ser to an
Object of SampleClass * * @author
http://interviewquestionjava.blogspot.com * **/ public static void
main(String[] args) { SampleClass objSampleClass = null; try
{ FileInputStream objFileInputStream =
newFileInputStream("src/com/interview/question/java/sampleClass.ser"
); ObjectInputStream objInputStream =
newObjectInputStream(objFileInputStream); objSampleClass =
(SampleClass)objInputStream.readObject(); objInputStream.close();
objFileInputStream.close();
System.out.println("======================= Deserialized Data
======================="); System.out.println("strName :
"+objSampleClass.getStrName()); System.out.println("strAddress :
"+objSampleClass.getStrAddress()); System.out.println("strUsername :
"+objSampleClass.getStrUsername()); System.out.println("strPassword :
"+objSampleClass.getStrPassword());
System.out.println("=====================================
============================"); } catch (Exception e)
{ e.printStackTrace(); } } }

Output :

======================= Deserialized Data


======================= strName : Ashoka Maurya strAddress :
Magadha strUsername : Chakravartin strPassword : null
===================================================
==============

Here, we can see, we get all the data from the deserialized object except
strPassword, as it is decleared astransient.

030 What are the methods of interface Serializable?

Interface Serializable has no methods, it's empty.

031 Serialization-Common usage.

1. An object needs to be serialized, when it's need to be sent over the


network.

2. If the state of an object is to be saved, objects need to be serialized.

032 Externalizable interface - uses. 1. Interface Externalizable


gives a control over the serialization mechanism.

2. It has two methods readExternal and writeExternal, which are use


to customize the serialization process.

033 Wrapper class

Wrapper class is a special type of class that's used to make primitive


variables into objects, so that the primitives can be included in activities
reserved for objects, like as being added to Collections, or returned from a
method with an object return value. It simply wraps or encapsulates a
single value for the primitive data types. These classes contain methods
that provide basic functions such as class conversion, value testing &
equality checks and the constructors of wrapper classes, allow objects can
create and convert primitives to and from String objects.

LIST OF WRAPPER CLASS

Primitive type

Wrapper class

boolean

Java.lang.Boolean

byte

Java.lang.Byte

char

Java.lang.Char

double

Java.lang.Double

float

Java.lang.Float
6

int

Java.lang.Int

long

Java.lang.Long

short

Java.lang.Short

034 Checked and UnChecked Exception

In Java, there are lots of sub-classes under java.lang.Exception class. we


can divide these sub-classes into 2 types on the basis of compile-time
checking.The types are - Checked Exception & Unchecked
Exception. Checked Exception:

 Except RuntimeException( java.lang.RuntimeException)


class, all sub-classes of Exception arechecked exception.

 These exceptions need to include in a method's throws list, because


these are checked by thecompiler during compile time if a method
handles or throws these exception.

Unckecked Exception:

 RuntimeException and its sub-classes are called as unchecked


exception.
 We don't need to include in a method's throws list, because these
are not checked by the compilerduring compile time.

035 What is a Container?

 Container is a component which can contain other components


inside itself. It is also an instance of a subclass of java.awt.Container,
which extends java.awt.Component.

 An applet is a container.

 Containers include windows, frames, dialogs, and panels.

 As a Container itself is a component, it can contain


othercontainers.

 Every container has a LayoutManager which helps to determines how


different components are placed within the container.

036 What is the difference between error and an exception?

In Java, under Throwable class, there are 2 sub-classes named


Exception and Error.

Exception class:

 It is used for exceptional conditions that user programs should catch.

 It's also the class that you will sub-class to create your own custom
exception types.

 For example, NullPointerException will be thrown if you try


using a null reference.

Error class:

 It indicates serious problems that a reasonable application should


not try to catch.
 It's used by the Java run-time system to indicate errors having to do
with the run-time environment, itself.

 For example, stack overflow is an error.

037 What is the super class of all classes?

The class Object(java.lang.Object), is the super class of all classes in


Java.

038 What are the differences between the String and


StringBuffer classes?

String class :

1. Once an object is created and initialized, it can't be changed because


it is Immutable.

2. String object can be created Implicitly and Explicitly.

StringBuffer class :

1. StringBuffer class is mutable(can be modified), length and


content can be changed through certain method calls.

2. It creates object Explicitly.

039 Difference between throw & throws throw is used to throw an


exception in a program, explicitly. Whereas, throws is included in the
method's declaration part, with a list of exceptions that the method can
possible throw. It is necessary for all exceptions(except for Error &
RuntimeException & their sub-classes).

040 Nested Class

The class which is defined within another class is called nested class.

It can be divided into 2 types. They are -   static nested class & non-static nested class
Static Nested Class: 
 Nested class which is declared static is static nested class.
 Its methods & variables are associated with is mother/outer class.
 It can be used only through object reference.
 It is accessed using enclosing class name.
Example:MotherClass.StaticNestedClass
 It interacts with enclosing class or other class like any other top-level class.

Non-Static Nested Class/Inner Class:


 It has access to the other members of the mother class, even they are private.
 It can't define any static member itself.
 Instance of inner class only valid within the instance of the enclosed class, &
has direct access to the methods & fields of the enclosing instance.
 To instantiate innerclass, 1st we need to instantiate the mother class. Example:
MotherClass.InnerClass iObj = MotherObject.new InnerClass();

Types of Inner Class


1.                 Local Inner Class 
2.                 Anonymous Inner Class
 
Local Inner Class: 
·         The inner class which is declared within the body of a method is known as
local inner class. 
·         It is not a member the enclosing class, hence doesn’t have any access specifies.
·         It has access to all the members of the enclosing class, even any final
variable 
within the scope.
 
Anonymous Inner Class:
·         The inner class which is declared within the body of a method and has no
name 
is known as anonymous inner class.
·         It is accessible only at the point of its declaration.
041 FileInputStream vs FileReader
Class FileInputStream:

 It is use for reading stream of data from a file in the form of raw bytes(8-bit).
 Very useful to read image.
 It can also read character files.
Hierarchy of Class FileInputStream: 

Class FileReader: 

 It is use to read stream of character data.


 It can only read character data, so its the best way of reading character files.

 Hierarchy of Class FileReader:

042 Why can't enum extends any other class?

By default, all enums implicitly extend java.lang.Enum. And as we know, Java doesn't support multiple

inheritance, an enum cannot extend any other class.

043 Why Errors are Unchecked?

Error is unpredictable. It can occur at any point and recover is also quite impossible. So it is meaningless to

declare such exception. That’s why, in java, error is unchecked.

044 What is the superclass of Exception?

java.lang.Throwable is the superclass of all the errors and exceptions in java.

045 Parse String to Double.


Paser String to Double:

You can parse a double value in string format to double in 4 ways.


1. Double.valueof(String s) :  This method returns a double object containing the value invoked in it in string
format.
o It can trim white-space in start or end of the string argument, by usingString.trim().
o It throws NumberFormatException if the string argument is not in proper form.
2.  Double.parseDouble(String s) : This method also returns a double instance containing the invoked string
value.
o It can also trim white space in start and end of the input value, using String.trim().
o It also throws NumberFormatException if the string argument is not in proper form.
3. new Double(String paramString) : You a also parse a string argument containing float value by invoking it
on the constructor of the Class Double. its internally using the valueof(String s) method and returns a new Double
instance containing the parsed double value. So it is also using 
String.trim() and throws NumberFormatException.
4. Fourth one, the last one is the very important one, actually its been used by all the above 3
APIs.sun.misc.FloatingDecimal.readJavaFormatString(String paramString). Its the original method used to parse
a String value to decimal value. This is the actual methods, which is trimming the white space of the string,
usingString.trim(). It returns value in FloatingDecimal instance, so you need to cast it to double by
using doubleValue(), which is another method of Class FloatingDecimal.
Below is an example which explains the above discussion:

Code: 
package com.interview.question.java;

public class PaserStringToDouble {

      /**
       *
       * Sample class that shows how to parse a String to double.
       *
       * @author http://interviewquestionjava.blogspot.com
       *
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            // set a decimal value in a string with
            // white space on both end.
            String strValue = " 12.329 ";

            // parse the string to double using


            //Double.valueof(String s)
            double dblValue = Double.valueOf(strValue);

            // parse the string to double using


            // Double.parseDouble(String s)
            double dblValue2 = Double.parseDouble(strValue);

            // parse the string to double using


      //Double(String paramString)
            Double dblValue3 = new Double(strValue);

            // parse the string to double using new


            // FloatingDecimal.readJavaFormatString
            //(String paramString)
            Double dblValue4 = new Double(sun.misc.FloatingDecimal
                        .readJavaFormatString(strValue).doubleValue());

            // printing the outputs


            System.out.println("dblValue: " + dblValue +
       "\ndblValue2: " + dblValue   + "\ndblValue3: " +
       dblValue3 + "\ndblValue4: " + dblValue4);

      }

Output:
dblValue: 12.329
dblValue2: 12.329
dblValue3: 12.329
dblValue4: 12.329

046 Keyword: abstract

abstract:
     This is used to define a class or a method as an abstract operation. When a method is
declared as abstract, that means, the method where it is declared (within the class) have
no body of the method rather the method can be overridden, through inheritance and
define it's body.
     When a class  contains any abstract method, it must be declared as abstract.
An abstract class cannot be final.
An abstract method cannot be final, static nor native.

Code:
package com.interview.question.java;

abstract class SampleAbstractClass {
  /**
    *
    * Sample abstract class.
    *
    * @author http://interviewquestionjava.blogspot.com
    *
    */
     
      // Sample abstract method.
      public abstract void sampleabstractmethod() ;
     
      public void sampleNormalMethod(){
           
System.out.println("SampleAbstractClass.sampleNormalMethod()");
      }
     
}

public class TestAbstractClass{
     
      /**
    *
    * Sample class to call SampleAbstractClass.
    *
    * @author http://interviewquestionjava.blogspot.com
    *
    */
      public static void main(String[] args) {
           
            SampleAbstractClass objSampleAbstractClass
= newSampleAbstractClass() {
                 
                  @Override
                  public void sampleabstractmethod() {
                       
                        System.out
                                   
.println("TestAbstractClass.main(...).new SampleAbstractClass()
{...}.sampleabstractmethod()");
                       
                  }
            };
           
            objSampleAbstractClass.sampleabstractmethod();
      }
     
}

Output:

TestAbstractClass.main(...).new SampleAbstractClass() {...}.sampleabstractmethod()


047 Overloading and Overriding

Overloading:  

  Overloading is a popular technique of object oriented programming. It allows you to define


a method with same name but with different parameters list.

  

 Java identifies method by its name and signature. So, if the combination of method name and signature is
unique, the compiler doesn’t have any issue to identify it. When you use overloaded methods,
the java compile will automatically identifies the right version of the method by number and/or types
of passing parameters. But you can’t declare more than one method with same name and passing
parameters. The compiler doesn’t consider return types when validating uniqueness of a method. That
means you can’t have two methods with same name and passing parameters with different return type.

   Java allows both method and constructor overloading. Let’s see this with an example.

Code:
package com.interview.question.java;

public class OverloadingDemo {

     

  /**

    *

    * This class demonstrates overloading in java

    *

    * @author http://interviewquestionjava.blogspot.com
    *

    **/

     

      private int a;

     

      /* constructor overloading */

      public OverloadingDemo(){

           

      }

      public OverloadingDemo(int a){

           

            this.a = a;

           

      }

     

     

      /* method overloading */

      public int add(int num){

           

            a +=num;

           

            return a;

      }

      public int add(String str){
           

            a+= Integer.valueOf(str);

           

            return a;

      }

      public int add(int num1, int num2){

                 

                  a += num1;

                  a += num2;

                 

                  return a;

            }

      /* test overloading */

      public static void main(String[] args) {

     

            OverloadingDemo objOverloadingDemo1 = new OverloadingDemo();

            OverloadingDemo objOverloadingDemo2


= new OverloadingDemo(5);

           

            System.out.println(objOverloadingDemo1.add(5));

            System.out.println(objOverloadingDemo1.add("3"));

            System.out.println(objOverloadingDemo1.add(3, 5));

           
            System.out.println("-----");

           

            System.out.println(objOverloadingDemo2.add(5));

            System.out.println(objOverloadingDemo2.add("3"));

            System.out.println(objOverloadingDemo2.add(3, 5));

           

     

    }

Output:
5

16

-----

10

13

21

   Here, in this class OverloadingDemo we defined two constructors with different signatures, and


three methodswith same name but different number and/or types of passing parameters.
Overriding:

     Overriding is the technique of inheriting a class and redefining the behaviors of the super class. That
means, when you define a method in subclass with the same signature (name, plus the number and the type
of its parameters) and return type as in the superclass, then you are overriding the method of the superclass
in your subclass, and the technique is known as method overriding.

    

           In method overriding, method name, method input parameters and return types in subclass should
be same in superclass.  It can only modify the behaviors. It can return a subtype of the original return
type defined in superclass, and this technique is known as covariant return type [Java 1.5 or above
support this]. For example, suppose the return type in superclass is java.util.Map, you can change it
to java.util.HashMap in subclass, as HashMap is a subtype of Map.

           You can also use @Override annotation [which is available in Java 1.5 or above] to tell
the compiler that you are trying to override a method in the superclass. And, fof any reason, if the compile
is unable to detect that method, it will generate an error.

            In method overriding in java, you can level up the access level but you can’t level it down. That
means, if amethod is declared as protected in superclass, it can be set as public is subclass but not
as private.

             If a method is declared as final, it can’t be overridden.

Now let’s see with an example.

Code:
Super Class :
package com.interview.question.java;

import java.util.HashMap;

import java.util.Map;

public class SuperClass {

     

      /**

    *

    * This is a sample class

    *

    * @author http://interviewquestionjava.blogspot.com

    *

    **/

     

      /* the return type of this method is Map and in subclass it will
be changed to HashMap */

      public Map methodForcovariant(){

            Map map = new HashMap();

            return map;

      }

     

      /* sample method which willbe overridden in subclass */


    public void sampleMethod(){

      System.out.println("SuperClass.sampleMethod()");

    }

   

    /* the specifier of this method willbe changed to public from


protected in its subclass */

    protected void protectedMethod(){

      System.out.println("SuperClass.protectedMethod()");

    }

   

    /* this method can't be overridden as it's declare as final */

    public final void finalMethod(){

      System.out.println("SuperClass.finalMethod()");

    }

Sub Class:

package com.interview.question.java;

import java.util.HashMap;

import java.util.Map;
            public class OverridingDemo extends SuperClass{

                  /**

                *

                * This class demonstrates overriding by extending


SuperClass

                *

                * @author http://interviewquestionjava.blogspot.com

                *

                **/

                 

                  /* Overriding with covariant return type :

                   * the return type of this method is modified to


itssubtype which is allowed in method overriding */

                  @Override

                public HashMap methodForcovariant(){

                        HashMap hmp = new HashMap();

                        return hmp;

                  }

                 

                  /* Overriding:

                   * overriding the method SuperClass.sampleMethod() */

                  @Override

                  public void sampleMethod(){

                  System.out.println("OverridingDemo.sampleMethod()");


                }

                 

                 

                  /* Overriding access specifier:

                   * the specifier of this method is changed to public


from protected */

                  @Override

                public void protectedMethod(){

                 
System.out.println("OverridingDemo.protectedMethod()");

                }

                 

           

            public static void main(String[] args) {

                 

                  SuperClass objSuperClass = new SuperClass();

                  SuperClass objOverridingDemo = new OverridingDemo();

                  objSuperClass.sampleMethod();

                  objOverridingDemo.sampleMethod();

                 

            }

                 
     

Output:
SuperClass.sampleMethod()

OverridingDemo.sampleMethod()

Here, we have used 4 methods:

methodForcovariant() – it shows the change of return type to its subtype during method overriding.

sampleMethod() – it shows method overriding in normal way.

protectedMethod() – it shows method overriding by leveling up access specifiers.

finalMethod() – it shows we can’t override methods declared as final.

048 Data Types Conversion Chart


 In Java Programming Language, we must declare a variable name and type, before using it. The data
type of a variable defines the the type of value it will contain. Java supports total 8 types of primitive data
types. The name of this data types are all reserved as keywords.
Among which, 1) byte, 2) short, 3) int & 4) long can store integer values of different range.
5) float and 6) double can store floating numbers of different range.
7) boolean  can store only true/false. It is used as flag, to perform boolean operation.
8) char can store a single 16-bit Unicode character of range from '\u0000' (0) to '\uffff' (65,535).
Apart from these, Java also provides a String data type which is defined as a Class (java.lang.String). It can
contains alpha numeric values.
byte

 Type: Integer (8-bit signed two's complement integer).


 Range:  from -128 [-2^(8-1)] to 127 [(2^(8-1))-1].
 Memory: 1 byte
 Default Value : 0
 Example: byte b = 0;

short

 Type: Integer (16-bit signed two's complement integer).


 Range:  from -32768 [-2^(16-1)] to 32767 [(2^(16-1))-1].
 Memory: 2 bytes
 Default Value : 0
 Example: short s  = 0;
int

 Type: Integer (32-bit signed two's complement integer).


 Range:  from -2147483648 [-2^(32-1)] to 2147483647 [(2^(32-1))-1].
 Memory: 4 bytes
 Default Value : 0
 Example: int i = 0;

long

 Type: Integer (64-bit signed two's complement integer).


 Range:  from -9223372036854775808 [-2^(64-1)] to 9223372036854775807 [(2^(64-1))-1].
 Memory: 8 bytes
 Default Value : 0L
 Example: long l = 0L;

float

 Type: Float (Single precision 32-bit IEEE 754 floating point).


 Range:  from 1.4E-45F to 3.4028235E+38F.
 Memory: 4 bytes
 Default Value : 0.0f
 Example: float f = 0f;

double

 Type: Float (Single precision 64-bit IEEE 754 floating point).


 Range:  from 4.9E-324D to 1.7976931348623157E+308D.
 Memory: 8 bytes
 Default Value : 0.0d
 Example: double d = 0d;

boolean

 Type: boolean (boolean flag - true / false).


 Range:  NA.
 Memory: virtual machine dependent
 Default Value : false
 Example: boolean b = false;

char

 Type: Character (a single 16-bit Unicode character).


 Range:  from '\u0000' (0) to '\uffff' (65535).
 Memory: 2 bytes
 Default Value : '\u0000'
 Example: char c = '\u0000';

String

 Type: String Character (a class can store alpha numeric value).


 Range:  NA
 Memory: NA
 Default Value : null
 Example: String s = "Hello World";
049 Singleton Pattern - Concept and 7 Most Popular
Implementation Style

   Singleton in one of the most popular yet controversial design pattern, in the world of object oriented
programming. It's one of those patterns, that every developer comes to know first and again it's one of of
those patterns, that even experience developers get confused with it's proper implementation style. So,
over here, we will first take a deeper look on the concept of Singleton design pattern and then we will
discuss all the popular implementation styles  of Singleton in java with suitable examples. 
This post is a little bit bigger than usual. So please be patient, because it's worth reading.

Concept

   Singleton is a software design pattern to limit the instantiation of a class to one, which will be globally
accessible.  That means it’s a technique by which a class only have one instance/object and this object
can be accessed globally. It is a part of Gang of Four design pattern and it comes under creational
design patterns.

   Applications, often needs to create single instance of a class, and that instance will be used throughout
the application. Examples like logging, database access, etc. We could pass such an instance from method
to method, or we can also assign it to each object in the application. But, that will create lots of
complexity. On the other hand, we could use a single instance to communicate with a class. Hence, the
class could create and manage a single instance of its own. And when needed, just talk to that class.

Principles of Singleton
Therefore, the principles of Singleton design pattern are -
1. The implementing class should have only one instance.
2. Access point of this single instance should be global.

Example of Singleton class in Java: One of the most popular singleton examples


is java.lang.Runtime class. It’s a singleton class, you can’t initialize this class, but you can get the
instance by calling getRuntime()method.
Structure
So, what will be the structure of a singleton class?

Well, it should contain the following properties:

1. It should have a private static member of the class.

2. The constructor should be private, so that, no one from outside can initialize this class.

3. A public static method which will expose the private member of the class to the outer world.

What if we use static class instead of Singleton?


Now, question may come, what if we use a static class instead of a Singleton class?

   Well, there are some advantages of using Singleton over static class.
1. Static class can only have static members, where in Singleton pattern implemented class can
have non-static members.
2. A Singleton class can implement interfaces as well as extend classes but a static class
can extend classes, without inheriting their instance members. 
3. A static class can’t be a top level class. It should be always nested class. That means, under some non-
static class. Because, by definition static means that it belongs to a class it is in.
4. We can clone an object of a Singleton class, but in static class, that is not possible.
5. Again, Singleton supports the features like polymorphism while, for a static class it’s not possible.
6. Singleton classes can also supports the lazy loading facility, which is not supported in a static class.
Implementation Styles

   In Java programming language, Singleton pattern can be archive by different implementation style.
Each has some pros and corns. One single style is not suitable for every situation. So I think you should
know, all of them, and use it as per your requirement.   

   Now, we are going to discuss about some of the most popular implementation style.

7 most popular implementation style of singleton


design pattern in java:
1. Simple Lazy Initialization
2. Thread Safe Lazy Initialization
3. Double Check Locking
4. Eager Initialization
5. Static Block Initialization
6. Demand Holder Idiom by Bill Pugh
7. Using enum by Joshua Bloch
Simple Lazy Initialization:
   The lazy initialization singleton implementation style initializes the instance of a singleton class when
it’s first being used. That means, the private static instance, (that is described in Structure) is initialized
not during the class load, but during its first use. Lazy initialization is very helpful, when is object cost of
a singleton class is high, i.e., it may take lots of time or memory.
It's only loaded, when it's actually being used.

   Simple Lazy Initialization is the most basic style for lazy loading. It's good for the newbies to
understand the concept and structure of Singleton pattern.The concept of this style is to declare the
private static instance of the class by setting the initial value as null during class load, keeping the actual
initialization for the first call. That means, the actual initialization of the single instance of the class is
only happening when for the first time the class has been called.

   Let’s take a look on the below example. The class LazyInitializationThreadUnsafe is a singleton class,
which contains a counter, every time called gives you a sequential incremental number.
Example: Class LazyInitializationThreadUnsafe

package interview.question.java.singleton;

/**

 *

 * The class LazyInitializationThreadUnsafe is Singleton Class suitable for

 * single thread application. This class also provides a public method named

 * counter() which will always returns integer type sequenced counter value

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class LazyInitializationThreadUnsafe {

        /*

         * The integer type counter will hold the value of the counter. The scope of

         * this field is private, so its only accessible via the counter method.

         * It's static so that only one copy of this variable will be available

         * within the memory.

         */

        private static int counter = 0;


        /*

         * The static private member instance of type LazyInitializationThreadUnsafe

         * Class will hold the single instance of this class.

         */

        private static LazyInitializationThreadUnsafe instance = null;

        /*

         * The constructor of the LazyInitializationThreadUnsafe class is in private

         * scope so that, no one can initialize this class.

         */

        private LazyInitializationThreadUnsafe() {

                System.out

                       

.println("LazyInitializationThreadUnsafe.LazyInitializationThreadUnsafe()");

        }

        /*

         * The method getInstance() will return the only instance of the class

         * LazyInitializationThreadUnsafe. It will initialize the object if the

         * instance is null by accessing the private constructor of this class.

         */

        public static LazyInitializationThreadUnsafe getInstance() {

                if (instance == null) {
                        instance = new LazyInitializationThreadUnsafe();

                }

                return instance;

        }

        /*

         * This sample method will increase the counter by 1 and returns its value.

         */

        public int counter() {

                counter++;

                System.out.println("LazyInitializationThreadUnsafe.counter()");

                return counter;

        }

Here, we are first declaring the class instance as null. 

private static LazyInitializationThreadUnsafe instance = null;

Now, when globally accessible getInstance() is called, 


1. it will check if the instance is null or not.
2. if null initialize it.
3. return the instance.

if (instance == null) {

                        instance = new LazyInitializationThreadUnsafe();
                }

So, it will be initialize only for the first time the getInstance() method has been called.

But, this style is not thread safe. Its only good for single threaded environment.

Life cycle:
• Initializes during first use.

• Destroyed at application shutdown.

Pros:
• It supports lazy initialization, so it will only been loaded to the memory when it’s actually needed for
the first time.

Corns:
• It’s preferable only on single thread environment.

Thread Safe Lazy Initialization:


   The concept of this style is same as other lazy initialization style; the only difference with the previous
lazy initialization style is its thread safe.

   Let’s take a look on an example. The below class LazyInitializationThreadSafe is a thread safe lazy
initialization style.
Example: Class LazyInitializationThreadSafe 

package interview.question.java.singleton;

/**

 *

 * The class LazyInitializationThreadSafe is Singleton Class suitable for

 * multithreaded application.

 * This class also provides a public method named counter()

 * which will always returns integer type sequenced counter value


 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class LazyInitializationThreadSafe {

        /*

         * The integer type counter will hold the

         * value of the counter.

         * The scope of this field is private, so its

         * only accessible via the counter method.

         * It's static so that only one copy of this variable

         * will be available within the memory.

         */

        Private static int counter = 0;

       

        /*

         * The static private member instance of type LazyInitializationThreadSafe

         * Class will hold the single instance of this class.

         *

         */

        private static LazyInitializationThreadSafe instance = null;

        /*
         * The constructor of the LazyInitializationThreadSafe class is in

         * private scope so that, no one can initialize this class.

         */

        private LazyInitializationThreadSafe() {

                System.out

                               

.println("LazyInitializationThreadSafe.LazyInitializationThreadSafe()");

        }

        /*

         * The static method getInstance() will return the only instance

         * of the  class LazyInitializationThreadSafe.

         * It will initialize the object if the

         * instance is null by accessing the private constructor

         * of this class.

         * The method getInstance() is synchronized to make it thread safe.

         */

        public static synchronized LazyInitializationThreadSafe getInstance() {

                if (instance == null) {

                        instance = new LazyInitializationThreadSafe();

                }

                return instance;

        }
        /*

         * This sample method will increase the counter

         * by 1 and returns its value.

         */

        public int counter() {

                counter++;

                System.out.println("LazyInitializationThreadSafe.counter()");

                return counter;

        }

Now, in this class you will find only one difference from the previous example (Class
LazyInitializationThreadUnsafe), that is, I use the synchronized Now, in this class getInstance() method.
That means, concurrent threads will use this method in atomic way. Thus, it’s safe from concurrent usage
of this method by multiple threads. And it becomes thread safe.

Life cycle:
• Initializes during first use.
• Destroyed at application shutdown.

Pros:
• Thread safe
• It uses lazy loading so it’s been initialized during its actual usage.

Corns:
• A bit slower that not thread safe style, the getInstance() goes through synchronized method. So it’s
locking the resource every time you call it.

 
Double Check Locking:
   Another technique to implement thread safe lazy initialization is double check locking. This concept
will work fine in Java 5 or above.  This concept is introduced to optimize the thread safe lazy
initialization styleof the Singleton pattern, which locks the resources, every time you try to get the
instance of the class using a public scoped method.

   Let’s see in details by the example class DoubleCheckLock.


Example: Class DoubleCheckLock 

package interview.question.java.singleton;

/**

 *

 * The class DoubleCheckLock is Singleton Class which implements the double

 * check lock style. This class also provides a public method named counter()

 * which will always returns integer type sequenced counter value

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class DoubleCheckLock {

        /*

         * The static private member instance of type DoubleCheckLock Class will

         * hold the single instance of this class.

         */

        private static volatile DoubleCheckLock instance = null;

        /*
         * The integer type counter will hold the value of the counter. The scope of

         * this field is private, so its only accessible via the counter method.

         * It's static so that only one copy of this variable will be available

         * within the memory.

         */

        private static int counter = 0;

        /*

         * The constructor of the DoubleCheckLock class is in private

         * scope so that, no one can initialize this class.

         */

        private DoubleCheckLock() {

                System.out.println("DoubleCheckLock.DoubleCheckLock()");

        }

        /*

         * The method getInstance() will return the only instance of the class

         * DoubleCheckLock. It will initialize the object if the instance is null by

         * accessing the private constructor of this class.

         */

        public static DoubleCheckLock getInstance() {

                if (instance == null) {

                        synchronized (DoubleCheckLock.class) {

                                if (instance == null) {
                                        instance = new DoubleCheckLock();

                                }

                        }

                }

                return instance;

        }

        /*

         * This sample method will increase the counter by 1 and returns its value.

         */

        public int counter() {

                counter++;

                System.out.println("DoubleCheckLock.counter()");

                returncounter;

        }

Now, over here if you see, you will find the difference is in technique of initializing the instance
insidegetInstance() method.

if (instance == null) {

                        synchronized (DoubleCheckLock.class) {

                                if (instance == null) {

                                        instance = new DoubleCheckLock();

                                }

                        }
                }

 Here, what we are doing is, 

1. Checking if the instance has been initialized or not.

2. If not, creating locks by using synchronized.

3. Again checking if the instance is already initialized or not.

4. If still not, then initializing the instance of the class.

   This is been introduced as in previous example (class LazyInitializationThreadSafe), we always locking


the method getInstance(), every time it’s been called. While, it’s only need when its initializing the
instance.

You can also see that, we use the volatile keyword, when declaring the instance of the class. That’s, to
inform the JVM that writes to the field should always be synchronously flushed to memory, and that reads
of the field should always read from memory.

Life cycle: 
• Initializes during first use.

• Destroyed at application shutdown.

Pros:
• Thread safe style.

• Doing lazy loading.

• Performance wise it’s faster than Thread safe lazy initialization as its only locking during initialization.

Corns:
• Code complexity.
• Should only use in java 5 or above.

Early or Eager Initialization


   Early or eager initialization style is to initialize the instance of a singleton class during class loading.
This style is very effective, if the instance is not that costly. In this technique, the instance of the class
has been initialized during its declaration and marked with final keyword, so that it can’t be modified.
One more benefit of using this style is, it’s totally thread safe.

   Let us see by using an example singleton class EagerInitialization.


Example: Class EagerInitialization 

package interview.question.java.singleton;

/**

 *

 * The class EagerInitialization is Singleton Class which implements

 * the Eager Initialization style suitable for both single

 * threaded  or multithreaded application.

 * This class also provides a public method named counter()

 * which will always returns integer type sequenced counter value

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class EagerInitialization {

        /*

         * The integer type counter will hold the

         * value of the counter.

         * The scope of this field is private, so its


         * only accessible via the counter method.

         * It's static so that only one copy of this variable

         * will be available within the memory.

         */

        private static int counter = 0;

       

        /*

         * The static private member instance of type EagerInitialization

         * Class will hold the single instance of this class.

         *

         */

        private static final EagerInitialization INSTANCE = new EagerInitialization();

        /*

         * The constructor of the EagerInitialization class is in

         * private scope so that, no one can initialize this class.

         */

        private EagerInitialization() {

                System.out.println("EagerInitialization.EagerInitialization()");

        }

        /*

         * The static method getInstance() will return the only instance

         * of the  class EagerInitialization.


         */

        public static EagerInitialization getInstance() {

                return INSTANCE;

        }

        /*

         * This sample method will increase the counter

         * by 1 and returns its value.

         */

        public int counter() {

                counter++;

                System.out.println("EagerInitialization.counter()");

                return counter;

        }

In this example, you can see its simply initializing the instance during declaration under private static
final clause. And returns it via a public static method getInstance().

Life cycle:
• Initializes during class load.
• Destroyed at application shutdown.

Pros:
• Thread safe.
• Performance wise, faster than lazy initialization, as it’s not locking any resource by synchronized.
• The instance is final, so scope of redefining, thus, no scope of multiple instance. 
Corns:
• Initializes during class load, so it is occupying memory, even when it’s not required. 

Static block initialization


   Static block initializing is another style of early initialization. The only difference is you are initializing
the instance of the class under a static block with error checking.

   Now, try it with this example class StaticBlockInitialization.


Example: Class StaticBlockInitialization 

package interview.question.java.singleton;

/**

 *

 * The class StaticBlockInitialization is Singleton Class which implements the

 * Static Block Initialization style. This class also provides a public method

 * named counter() which will always returns integer type sequenced counter

 * value

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class StaticBlockInitialization {

        /*

         * The integer type counter will hold the value of the counter. The scope of

         * this field is private, so its only accessible via the counter method.
         * It's static so that only one copy of this variable will be available

         * within the memory.

         */

        private static int counter;

        /*

         * The static private member instance of type StaticBlockInitialization

         * Class will hold the single instance of this class.

         */

        private static final StaticBlockInitialization INSTANCE;

        /*

         * Initializing static members under static block

         */

        static {

                try {

                        INSTANCE = new StaticBlockInitialization();

                        counter = 0;

                } catch (Exception e) {

                        throw new RuntimeException(e.getMessage(), e);

                }

        }

        /*
         * The constructor of the StaticBlockInitialization class is in private

         * scope so that, no one can initialize this class.

         */

        private StaticBlockInitialization() {

                System.out

                                .println("StaticBlockInitialization.StaticBlockInitialization()");

        }

        /*

         * The static method getInstance() will return the only instance of the

         * classStaticBlockInitialization.

         */

        public static StaticBlockInitialization getInstance() {

                return INSTANCE;

        }

        /*

         * This sample method will increase the counter by 1 and returns its value.

         */

        public int counter() {

                counter++;

                System.out.println("StaticBlockInitialization.counter()");

                return counter;

        }
}

Here, you can see we are initializing the instance of the class under a static block. And we are also doing
it under try catch block, to provide an error check during initialization.

Life cycle:
• Initializes during class load.
• Destroyed at application shutdown.

Pros:
• Thread safe.
• Performance wise, faster than lazy initialization, as it’s not locking any resource by synchronized.
• The instance is final, so scope of redefining, thus, no scope of multiple instance. 
• Initializing under try catch block for error check.

Corns:
• Initializes during class load, so it is occupying memory, even when it’s not required. 

Demand Holder Idiom by Bill Pugh


   Again back to lazy initialization style, but this time, back with a better way of use lazy
implementation.Demon holder idiom is written by an American computer scientist Bill Pugh. The
concept with this pattern is to declare and initialize the instance as private static final under a
static inner class.

   Let’s see with the example class DemandHolderIdiom.


Example: Class DemandHolderIdiom 

package interview.question.java.singleton;

/**

 *
 * The class DemandHolderIdiom is Singleton Class which implements the Demand

 * Holder Idiom style. This class also provides a public method named counter()

 * which will always returns integer type sequenced counter value.

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class DemandHolderIdiom {

        /*

         * The integer type counter will hold the value of the counter. The scope of

         * this field is private, so its only accessible via the counter method.

         * It's static so that only one copy of this variable will be available

         * within the memory.

         */

        private static int counter = 0;

        /*

         * The constructor of the DemandHolderIdiom class is in private scope so

         * that, no one can initialize this class.

         */

        private DemandHolderIdiom() {

                System.out.println("DemandHolderIdiom.DemandHolderIdiom()");

        }
        /*

         * The class SingletonInstanceHolder is a private class which only contains

         * single instance of the class DemandHolderIdiom

         */

        private static class SingletonInstanceHolder {

                /*

                 * The static private member instance of type SingletonInstanceHolder

                 * Class will hold the single instance of this class.

                 */

                public static final DemandHolderIdiom INSTANCE = new DemandHolderIdiom();

        }

        /*

         * The static method getInstance() will return the only instance of the

         * classDemandHolderIdiom, which is declared under SingletonInstanceHolder

         * class.

         */

        public static DemandHolderIdiom getInstance() {

                returnSingletonInstanceHolder.INSTANCE;

        }

        /*
         * This sample method will increase the counter by 1 and returns its value.

         */

        publicint counter() {

                counter++;

                System.out.println("DemandHolderIdiom.counter()");

                returncounter;

        }

Over here, you can see, the instance of the singleton class has been declared and initialized under a
static inner class SingletonInstanceHolder. And when getInstance() is called, it’s the return the instance
under the inner class.

Now, the question is, how is Domain Holder Idiom working as lazy initialization style?

   The answer is, when the class DemandHolderIdiom is loaded, it goes through initialization of only the
static fields. Since it doesn’t have any static variable to initialize, SingletonInstanceHolder is not
loaded during class loading. So, when it will initialize? Well, it will only loaded when the JVM thinks that
SingletonInstanceHolder must be executed. And that is only when this inner class has been called from
the getInstance() method for the first time. Now, when this inner class is loaded, all its static variables
are also loaded. So the instance is also initialized by executing the private constructor of the outer class.
You can also read Java Language Specification (JLS) for more details about class loading and
initialization. As the class initialization phase is guaranteed by the JLS to be serial, i.e., non-concurrent,
so no further synchronization is required in the static getInstance() method during loading and
initialization.

Life cycle:
• Initializes during first use.

• Destroyed at application shutdown.


Pros:
• Thread safe.

• Lazy loading.

• No need of resource locking to make it thread safe. Thus, performance is also good.

Corns:
• No such disadvantage as far. Still, it should be used when you need the lazy loading facility. Else, early
loading is simple to understand and use.

Using enum by Joshua Bloch


Another technique to create singleton is by using Enum. Well Enum is introduced in Java 5, so it’s
applicable in java 5 or higher versions. A computer scientist Joshua Bloch claims that "a single-element
enum type is the best way to implement a singleton" in his book Effective Java [2nd edition]. Enum is
thread safe and serialization.
Let’s see an implementation with an enum UsingEnum.
Example: Enum UsingEnum

package interview.question.java.singleton;

/**

 *

 * The enumUsingEnum is defined to behave as Singleton . It also provides a

 * public method named counter() which will always returns integer type

 * sequenced counter value.

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com]

 *

 **/

public enum UsingEnum {
       Instance;

       /*

        * The integer type counter will hold the value of the counter. The scope of

        * this field is private, so its only accessible via the counter method.

        * It's static so that only one copy of this variable will be available

        * within the memory.

        */

       private static int counter = 0;

       /*

        * This sample method will increase the counter by 1 and returns its value.

        */

       public int counter() {

              counter++;

              System.out.println("UsingEnum.counter()");

              return counter;

       }

Here, you can see the code is very simple.

public enum UsingEnum {

       Instance;

}
By this only your singleton is created. So, don’t even need any locking for thread safety. Enum also
supports serialization. But it is unable to extend any class [read more for details].

Life cycle:
• Initializes during first use.
• Destroyed at application shutdown.

Pros:
• Thread safe.
• Supports serialization.
• No locking is needed, so performance is better.
• Code simplicity.

Corns:
• Available from java 5
• Unable to extend any class.

Test Class to execute all Singleton Examples

Now, it’s time to test the all above singleton classes. For that, we have a Test class, which simple calls all
the above classes twice, to see if its initializing once or more, by using a loop.

package interview.question.java.singleton;

/**

 *

 * The class Test will call all the singleton classes to test.

 *

 * @author Java Interview Questions [http://interviewquestionjava.blogspot.com ]

 *

 **/

public class Test {
        public static void main(String[] args) {

                for (int i = 0; i< 2; i++) {

                        //LasyInitializationThreadUnsafe

                        LasyInitializationThreadUnsafelasyInitializationSingleThread =

LasyInitializationThreadUnsafe

                                        .getInstance();

                        System.out.println(lasyInitializationSingleThread.counter());

                        //LasyInitializationThreadSafe

                        LasyInitializationThreadSafelasyInitializationThreadSafe =

LasyInitializationThreadSafe

                                        .getInstance();

                        System.out.println(lasyInitializationThreadSafe.counter());

                       

                        //DoubleCheckLock

                        DoubleCheckLockdoubleCheckLock = DoubleCheckLock.getInstance();

                        System.out.println(doubleCheckLock.counter());

                        //EagerInitialization

                        EagerInitializationeagerInitialization = EagerInitialization

                                        .getInstance();

                        System.out.println(eagerInitialization.counter());
                        //StaticBlockInitialization

                        StaticBlockInitializationstaticBlockInitialization =

StaticBlockInitialization

                                        .getInstance();

                        System.out.println(staticBlockInitialization.counter());

                        //DemandHolderIdiom

                        DemandHolderIdiomdemandHolderIdiom = DemandHolderIdiom

                                        .getInstance();

                        System.out.println(demandHolderIdiom.counter());

                        //UsingEnum

                        System.out.println(UsingEnum.Instance.counter());

                        System.out.println("\n\n");

                }

        }

}
Output:
Now, from the output it’s clear that, all the singleton classes have been initialized for one time.

LasyInitializationThreadUnsafe.LasyInitializationThreadUnsafe()

LasyInitializationThreadUnsafe.counter()

LasyInitializationThreadSafe.LasyInitializationThreadSafe()

LasyInitializationThreadSafe.counter()

DoubleCheckLock.DoubleCheckLock()

DoubleCheckLock.counter()

EagerInitialization.EagerInitialization()

EagerInitialization.counter()

StaticBlockInitialization.StaticBlockInitialization()

StaticBlockInitialization.counter()

DemandHolderIdiom.DemandHolderIdiom()

DemandHolderIdiom.counter()

UsingEnum.counter()

1
LasyInitializationThreadUnsafe.counter()

LasyInitializationThreadSafe.counter()

DoubleCheckLock.counter()

EagerInitialization.counter()

StaticBlockInitialization.counter()

DemandHolderIdiom.counter()

UsingEnum.counter()

Conclusion

Well, after discussing all the implementation styles, we may think the Enum Singleton Style and Domain
Holder Idiom are the most smarter ways to implement Singleton pattern in java. But that doesn't mean
other styles are irrelevant. Styles like Simple Lazy Initialization Style and Early Initialization are very
good for learning phase.  Because you can get the concept and structure of a singleton class very clearly
form these patterns. And remember java.lang.Runtime uses Early Initialization too.

Therefore, when it comes to Singleton Implementation style, choose wisely and code smartly.

You might also like