Singleton Design Pattern in java

Problem:

  • Instead of creating multiple objects of same class having same data and wasting memory, degrading performance it is recommended to create only one object and use it multiple times.

Solution:

  •  Use Singleton Java Class.
  • Java class that allows us to create one object per JVM is is called as singleton java class.
  • The logger class of  Log 4J API is given as singleton java class.

Rules:

  • It must have only private constructors.
  • It must have private static reference variable of same class.
  • It must have public static factory method having the logic of singleton.
  • Static method should create and return only one object.
  • All these rules close all the doors of creating objects for java class and opens only one door to create object.
  • factory method where singleton logic is placed
  • The method of a class capable of creating and returning same class or other class object is known as factory method.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  
  22. return object;
  23.  
  24. }
  25.  
  26. }
     

  1. package instanceofjava;
  2.  
  3. public class SingletonObjectDemo {

  4. public static void main(String args[]) {
  5.  
  6.      SingletonClass s1= SingletonClass .getInstance();
  7.      SingletonClass s2= SingletonClass .getInstance();
  8.      System.out.println(s1.hashCode());
  9.      System.out.println(s2.hashCode());
  10.  
  11. }
  12. }

Output:

  1. getInstance(): First time getInstance was called and object created !
  2. Singleton(): Private constructor invoked
  3. 655022016
  4. 655022016


Make the Factory method Synchronized to prevent from Thread Problems:


  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.   
  22. return object;
  23.  
  24. }
  25.  
  26. }

Override the clone method to prevent cloning:

 

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  else 
  22. return object;
  23.  
  24.  
  25. public Object clone() throws CloneNotSupportedException {
  26.  
  27. throw new CloneNotSupportedException();
  28.  
  29. }
  30.  
  31. }

Eager Initialization:

  • In eager initialization object of the class will be created when class loading itself its easy way to create singleton but its having one disadvantage that even though nobody needs it still it creates object.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object= new SingletonClass ();
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. return object;
  15.  
  16. }
  17.  
  18. }
     


Lazy Initialization:

  • When ever client needs object it will check for whether object is created or not if not it will create otherwise it will return created object
  • First basic example shows lazy initialization.


Static Block Initialization:

  • This is similar to eager initialization except that in this we create object in static block and we can place exception logic.

  1. package com.instanceofjava;
  2.  
  3. public class StaticBlockSingleton {
  4.  
  5. private static StaticBlockSingleton object;
  6.  
  7. private StaticBlockSingleton(){}
  8.  
  9.     //static block initialization for exception handling
  10. static{
  11.  
  12.  try{
  13.  
  14.             object = new StaticBlockSingleton();
  15.  
  16.         }catch(Exception e){
  17.  
  18.             throw new RuntimeException("Exception occured in creating singleton object");
  19. }
  20. }
  21.  
  22. public static StaticBlockSingleton getInstance(){
  23.         return object;
  24. }
  25.  
  26. }


Comparable vs Comparator

  • One of the common interview question What are the differences between comparable and comparator and how to sort collections using these interfaces ?
  • What are the differences between comparable and comparator and how to sort employee object by empId or empName using these interfaces.
  • In this topic we will clear questions like difference between comparable and comparator in java, comparator vs comparable in java with example and comparable and comparator in java
  • Comparator and Comparable are two interfaces in Java API.
  • Before discussing about differences lets see brief description about these two interfaces

Comparable Interface:

  • Comparable Interface is actually from java.lang package.
  • It will have a method compareTo(Object obj)to sort objects
  • public int compareTo(Object obj){ }
  • Comparable interface used for natural sorting these is the reason all wrapper classes and string class implementing this comparator and overriding compareTo(Object obj) method.
  • So in String and all wrapper classes compareTo(Object  obj) method is implemented in such way that it will sort all objects.

String class:

  • If we observe String class it is implementing comparable interface.
  • If compareTo(String str) methods returns 0 : both strings are equal
  • If compareTo(String str) method returns 1: string is lexicographically greater than the string argument
  • If compareTo(String str) method returns -1: string is lexicographically less than the string argument

  1. package java.lang;
  2.  
  3. public final class String
  4. extends Object
  5. implements Serializable, Comparable<String>, CharSequence {
  6.   
  7. public int compareTo(String anotherString){
  8.  //logic
  9. }
  10. }

Comparing String Objects:

  •  Lets see an example java program that will explains how two string objects are compared using compareTo(String str) method in String class.


  1. package com.instanceofjava;
  2. public class StringCompareDemo {
  3. public static void main(String [] args){
  4.    
  5.  String str1="comparable";
  6.  String str2="comparator";
  7.  
  8. int value=str1.compareTo(str2);
  9.  
  10. if(value==0){
  11.  
  12. System.out.println("Strings are equal");
  13.  
  14. }
  15. else{
  16.  
  17. System.out.println("Strings are not equal");
  18.  
  19. }
  20.  
  21. }
  22. }

Output:

  1. Strings are not equal

Wrapper classes:

  • Wrapper classes is used to convert primitive data values into java objects. for 8 primitive data types java has 8 corresponding wrapper classes. All these classes implementing comparable interface.
  • Lets see an example on Integer wrapper class 

Integer:


  1. package java.lang;
  2. public final class Integer
  3. extends Number
  4. implements Comparable<Integer> {
  5.   
  6. public int compareTo(Integer i){
  7.  //
  8. }
  9. }

  •  Lets see an example program of comparing two integer objects

  1. package instanceofjava;
  2.  
  3. public class IntegerComparableDemo {
  4.  
  5. public static void main(String [] args){
  6.  
  7.    // compares two Integer objects numerically
  8.  
  9.    Integer obj1 = new Integer("37");
  10.    Integer obj2 = new Integer("37");
  11.  
  12.    int retval =  obj1.compareTo(obj2);
  13.  
  14. if(retval > 0) {
  15.  
  16.    System.out.println("obj1 is greater than obj2");
  17. }
  18.  
  19. else if(retval < 0) {
  20.  
  21.  System.out.println("obj1 is less than obj2");
  22.  
  23.  }
  24.  else {
  25.  
  26.  System.out.println("obj1 is equal to obj2");
  27.  
  28. }
  29.  
  30. }

Output:
  1. obj1 is equal to obj2;

Sorting Collections using Comparable :

  •  By using Collections.sort(list); method we can sort objects in natural object sorting order 
  • An example program on Collections.sort(list); 
  • Sorting Employee objects by id.



  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee implements  Comparable {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  @Override
  35.  public int compareTo(Object in) {
  36.         return  new Integer(this.id).compareTo(((Employee)in).id);
  37.   }
  38.  public static void main(String[] args) {
  39.  
  40.         Employee e1= new Employee("xyz", 37);
  41.         Employee e2= new Employee("abc", 46);
  42.         Employee e3= new Employee("sai", 38);
  43.  
  44.         ArrayList al= new ArrayList();
  45.  
  46.         al.add(e1);
  47.         al.add(e2);
  48.         al.add(e3);
  49.         Collections.sort(al);
  50.         Iterator itr= al.iterator();
  51.  
  52.      while (itr.hasNext()) {
  53.             Employee em = (Employee) itr.next();
  54.             System.out.println(em.getId()+" "+em.getName());            
  55.        }
  56. }
  57. }
     
Output:

  1. 37 xyz
  2. 38 sai
  3. 46 abc

Comparator:

  • Comparator Interface is actually from java.util package.
  • It will have a method compare(Object obj1, Object obj2)to sort objects
  • public int  compare(Object obj1, Object obj2){ }
  • Comparator interface used for customized sorting.
  • Will place sorting logic in other class so that its easy to change.
  • An example program which will sort employee objects by name

 

 1.Employee.java

  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee  {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  
  35.  public static void main(String[] args) {
  36.  
  37.         Employee e1= new Employee("xyz", 37);
  38.         Employee e2= new Employee("abc", 46);
  39.         Employee e3= new Employee("sai", 38);
  40.  
  41.         ArrayList al= new ArrayList();
  42.  
  43.         al.add(e1);
  44.         al.add(e2);
  45.         al.add(e3);
  46.        Collections.sort(al, new EmpSortByName());
  47.         Iterator itr= al.iterator();
  48.  
  49.      while (itr.hasNext()) {
  50.             Employee em = (Employee) itr.next();
  51.             System.out.println(em.getId()+" "+em.getName());            
  52.        }
  53. }
  54. }

EmpSortByName.java:

 

  1. package instanceofjava;
  2. import java.util.Comparator;
  3. public class EmoSortByName implements Comparator<Employee> {
  4.  
  5.     @Override
  6.     public int compare(Employee arg0, Employee arg1) {
  7.         return arg0.getName().compareTo(arg1.getName());
  8.     }
  9.  
  10. }
     
Output:

  1. 46 abc
  2. 38 sai
  3. 37 xyz

Differences Between Comparable and Comparator:


Parameter Comparable Comparator
Package java.lang.Comparable java.util.Comparator
Sorting logic Must be in Same class Separate class
Method definition public int compareTo(Object obj) public int compare(Object obj1, Object obj2)
Method call Collections.sort(list) Collections.sort(list, new OtherSortClass())
Purpose Natural Sorting Custom Sorting


You Might Like:

1. Java Concept and Example Programs 
2. Java Concept and Interview Questions 
3. Core java Tutorial
4. Java experience interview Questions
5. Java Programs asked in Interviews

10 Interesting Core Java Interview Coding Questions and Answers

1. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class B{
  4.  
  5.   B b= new B();
  6.  
  7.  public int show(){
  8.       return (true ? null : 0);
  9.  }
  10.  
  11.  public static void main(String[] args)  {
  12.  
  13.         B b= new B();
  14.         b.show();
  15.     }
  16.  
  17. }




Exaplanation:

  • Whenever we create the object of any class constructor will be called first and memory allocated for all non static variables
  • Here  B b= new B(); variable is object and assigned to new object of same class
  • B b= new B(); statement leads to recursive execution of constructor will create infinite objects so at run time an exception will be raised
  • Exception in thread "main" java.lang.StackOverflowError
  • The common cause for a stack overflow exception  is a bad recursive call. Typically this is caused when your recursive functions doesn't have the correct termination condition

2. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  public static void show(){
  6.  
  7.         System.out.println("Static method called");
  8.  }
  9.  
  10.  public static void main(String[] args)  {
  11.  
  12.         A obj=null;
  13.         obj.show();
  14.  
  15.     }
  16.  
  17. }



Exaplanation:

  • We can call static methods using reference variable which is pointing to null because static methods are class level so we can either call using class name and reference variable which is pointing to null.


3. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  static int a = 1111;
  6.  static
  7.  {
  8.         a = a-- - --a;
  9.  }
  10.     
  11. {
  12.         a = a++ + ++a;
  13.  }
  14.  
  15.  public static void main(String[] args)  {
  16.  
  17.        System.out.println(a);
  18.  
  19.     }
  20.  
  21. }




Explanation:

Top 10 Increment and decrement  operators interview Questions

4. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  int GetValue()
  6.  {
  7.         return (true ? null : 0);
  8.  }
  9.  
  10.  public static void main(String[] args)  {
  11.  
  12.    A obj= new A();

  13.       obj.GetValue();
  14.  
  15.     }
  16.  
  17. }




5. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.   
  5.  public static void main(String[] args)  {
  6.  
  7.    Integer i1 = 128;
  8.  
  9.    Integer i2 = 128;
  10.  
  11.      System.out.println(i1 == i2);
  12.  
  13.    Integer i3 = 127;
  14.    Integer i4 = 127;
  15.  
  16.       System.out.println(i3 == i4);
  17.  
  18.     }
  19.  
  20. }




6. What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. void method(int i)
  6. {
  7.  
  8.  }
  9.  
  10.     }
  11.  
  12.  class B extends A
  13.  {
  14.  
  15. @Override
  16. void method(Integer i)
  17.  {
  18.  
  19.  }
  20.           


  21. }



7. Which line will throw compile time error? 8 or 9?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. public static void main(String [] args)
  6. {
  7.  
  8.   Integer i = new Integer(null);
  9.   String s = new String(null);
  10.  
  11.  }
  12.  
  13. }



8.What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. public static void main(String [] args)
  6. {
  7.  
  8.   String s = "ONE"+3+2+"TWO"+"THREE"+5+4+"FOUR"+"FIVE"+5;
  9.   System.out.println(s);
  10.  
  11.  }
  12.  
  13. }



9.What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.  
  5. static int method1(int i)
  6. {
  7. return method2(i *= 11);
  8. }
  9.  
  10.  static int method2(int i)
  11. {
  12.   return method3(i /= 11);
  13. }
  14.  
  15.  static int method3(int i)
  16. {
  17.  return method4(i -= 11);
  18. }
  19.  
  20.  static int method4(int i)
  21. {
  22.   return i += 11;
  23. }
        
  24. public static void main(String [] args)
  25. {
  26.  
  27.   System.out.println(method1(11));
  28.  
  29.  }
  30.  
  31. }





10.What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. public static void main(String [] args)
  6. {
  7.  
  8.   System.out.println(null);

  9.  }
  10.  
  11. }



Explanation:

What happens When System.out.println(null)?


  1. Print prime numbers? 
  2. Java Program Find Second highest number in an integer array 
  3. Java Interview Program to find smallest and second smallest number in an array 
  4. Java Coding Interview programming Questions : Java Test on HashMap 
  5. Constructor chaining in java with example programs 
  6. Swap two numbers without using third variable in java 
  7. Find sum of digits in java 
  8. How to create immutable class in java 
  9. AtomicInteger in java 
  10. Check Even or Odd without using modulus and division  
  11. String Reverse Without using String API 
  12. Find Biggest substring in between specified character
  13. Check string is palindrome or not?
  14. Reverse a number in java? 
For more interview programs : Java Programs asked in interviews

Group Discussion on Java Topic

Hi Friends We are planning to conduct a group discussion on a topic every week So interested candidates can join us based on everybody convenience time we will schedule it.

We will conclude the topic at the end.

Our Skype ID : Instanceofjava.

Update: Based on your interest and time we will schedule the session. its free




Java Interview programs on Strings


1.Reverse a String Without using String API?

  1. package com.instaceofjava;
  2.  
  3. public class ReverseString {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String str="Hello world";
  8. String revstring="";
  9.  
  10. for(int i=str.length()-1;i>=0;--i){
  11. revstring +=str.charAt(i);
  12. }
  13.  
  14. System.out.println(revstring);
  15. }
  16. }


Program:

output: dlrow olleH.

2)Sorting the String without using String API?


  1. package com.Instanceofjava;
  2.  
  3. public class SortString {
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.   String original = "edcba";
  8.  int j=0;
  9.    char temp=0;
  10.  
  11.      char[] chars = original.toCharArray();
  12.      for (int i = 0; i <chars.length; i++) {
  13.          for ( j = 0; j < chars.length; j++) {
  14.          if(chars[j]>chars[i]){
  15.              temp=chars[i];
  16.              chars[i]=chars[j];
  17.               chars[j]=temp;
  18.           }
  19.      }
  20.   }
  21.  
  22.     for(int k=0;k<chars.length;k++){
  23.     System.out.println(chars[k]);
  24.    }
  25.  
  26.  }
  27. }

program:

output:abcde.

3.Sort the String with using String API?

program:
  1. package com.instanceofjava;
  2.  
  3.  public class SortString {
  4.  
  5.  public static void main(String[] args) {
  6.    String original = "edcba";
  7.  
  8.    char[] chars = original.toCharArray();
  9.    Arrays.sort(chars);
  10.  
  11.     String sorted = new String(chars);
  12.      System.out.println(sorted);
  13.  
  14. }
  15. }




OutPut:abcde

4.Check String is palindrome or not?

program:

Solution #1:

  1. package com.instaceofjava; 
  2.  
  3. public class PalindromeDemo{ 
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String str="MADAM";
  8. String revstring="";
  9.  
  10. for(int i=str.length()-1;i>=0;--i){
  11. revstring +=str.charAt(i);
  12. }
  13.  
  14. System.out.println(revstring);
  15.  
  16. if(revstring.equalsIgnoreCase(str)){
  17. System.out.println("The string is Palindrome");
  18. }
  19. else{
  20. System.out.println("Not Palindrome");
  21. }
  22.  
  23. }
  24.  
  25. }



  Output:

The string is Palindrome

Solution #2:

  1. package com.instaceofjava;
  2.  
  3.   import java.util.Scanner;
  4.  
  5.  public class Palindrome {
  6.  
  7. public static void main(String[] args)
  8. {
  9.  
  10. Scanner in = new Scanner(System.in);
  11.  
  12.  System.out.println("Enter a string");
  13.  String str=in.nextLine();
  14.  
  15. StringBuffer strone=new StringBuffer(str);
  16.  StringBuffer strtwo=new StringBuffer(strone);
  17.  
  18.   strone.reverse();
  19.  
  20. System.out.println("Orginal String ="+strtwo);
  21. System.out.println("After Reverse ="+strone);
  22.  
  23. if(String.valueOf(strone).compareTo(String.valueOf(strtwo))==0)
  24.    System.out.println("Result:Palindrome");
  25.    else
  26.     System.out.println("Result:Not Palindrome");
  27.  
  28.    }
  29.  
  30. }




 Output:

Enter a string
MOOM
Orginal String =MOOM
After Reverse =MOOM

Result:Palindrome

5.Program to Check given number is palindrome or not?

Program:

  1.  package com.instaceofjava; 
  2.  
  3. import java.util.Scanner; 
  4.  
  5. public class Palindrome {
  6.  
  7. public static void main(String[] args)
  8. {
  9.  
  10. System.out.println("Please Enter a number : ");
  11.       int givennumber = new Scanner(System.in).nextInt();
  12.       int number=givennumber;
  13.        int reverse=0;
  14.         while (number != 0) {
  15.            int remainder = number % 10;
  16.             reverse = reverse * 10 + remainder;
  17.             number = number / 10;
  18.         }           
  19. if(givennumber == reverse)
  20.    System.out.println("Result:Palindrome");
  21.     else
  22.     System.out.println("Result:Not Palindrome");
  23.     }
  24.  
  25. }

 Output:

Please Enter a number :
535
Result:Palindrome.

 Also Read:


Top 16 Java Inheritance Interview questions for freshers and experienced


1.what is inheritance?
  • inheritance is one of the oops concepts in java.inheritance is concept of  getting properties of one class object to another class object.
  • Inheritance represents the IS-A relationship,also known as parent-child relationship.
2.what are the types of inheritance?

1.Multiple inheritance( java doesn't support multiple inheritance).
2.Multilevel inheritance.

3.How Inheritance can be implemented in java?
  • Inheritance can be implemented in JAVA using below two keywords:
1.extends
2.implements
  • extends is used for developing inheritance between two classes and two interfaces.
  • implements keyword is used to developed inheritance between interface and class.
4.Why we need to use Inheritance?

1.For Code Re usability.
2.For Method Overriding.

5.what is syntax of inheritance?

public class subclass extends superclass{

//all methods and variables declare here
}

6.what is multilevel inheritance?
  • Getting the properties from one class object to another class object level wise with different priorities.


6.what is Multiple inheritance?why Java Doesn't Support multiple Inheritance.
  • The concept of Getting the properties from multiple class objects to sub class object with same priorities is known as multiple inheritance.
  • In multiple inheritance there is every chance of multiple properties of multiple objects with  the same name available to the sub class object with same priorities leads for the ambiguity. also known as diamond problem. one class extending two super classes.
  • Because of multiple inheritance there is chance of the root object getting created more than once.
  • Always the root object i.e object of object class hast to be created only once.
  1. Because of above mentioned reasons multiple inheritance would not be supported by java.
  2. Thus in java a class can not extend more than one class simultaneously. At most a class can extend only one class.

8.How do you implement multiple inheritance in java?
  • Using interfaces java can support multiple inheritance concept in java. in java can not extend more than one classes, but a class can implement more than one interfaces.
Program:

interface A{

}
interface B{
}
class C implements A,B{
}

9.Can a class extend itself?

  • No,A class can't extend itself.

10.What happens if super class and sub class having same field name?


  • Super class field will be hidden in the sub class. You can access hidden super class field in sub class using super keyword.

Select Menu