Saturday, 9 December 2017

Singleton Design Pattern, a complete guide

In this blog, we are going to discuss all about Singleton Design Pattern which is one of the popular topic during Java Interview.

You can see a lot of discussion on this topic on various  blogs or sites in google but what I personally feel none of them have covered the entire design. So here I am going to share the complete design step by step.

What is Singleton pattern?

Singleton pattern ensures that class has only one instance and it provides a global point to access it.
Real time example of Singleton pattern is JDBC  getConnection() method.
Below one is the sample implementation of Singleton class:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private ,else somebody can easily     //creates its object.
private SingleTon()
{

}
public static SingleTon getInstance()
{
if(singletonObj==null)
singletonObj=new SingleTon();

return singletonObj;

}

}


/****End of code****/


So here we have created the Singleton class which restricts creation object using new operator as we made the constructor as private. So we have ensured that at any point time there would be only one instance of Singleton Class. We can write the code in main() method as below:

public static void main(String args[]){
  SingleTon singleton=SingleTon.getInstance();
}

Congratulation!!! We have created the SingleTon instance which can be accessed globally.

Wait!!!!!, this code can be cracked using Reflection in java that means even though we made Constructor as private but still during run time any body can create its instance using Reflection, here is the code snippet.

public class SingleTontest {

public static void main(String[] args) throws                               InstantiationException, IllegalAccessException,                     IllegalArgumentException, InvocationTargetException {

 /**
  * getDeclaredConstructors() method returns the number of            *   constructor present in the class,
  * default constructor always comes in 0th index 
  */
Constructor[] cons =                                                 SingleTon.class.getDeclaredConstructors();
cons [0].setAccessible(true); 

// get the instance of the class, initially it was                   // null,


SingleTon s2=(SingleTon)cons[0].newInstance();


System.out.println("hashcode after creating new                             Intance--> "+s2.getInstance().hashCode());


// get all the declared fields, in our class we                     // have only one declared field as singletonObj


Field [] f1=s2.getClass().getDeclaredFields();


f1[0].setAccessible(true);


//setting the singletonObj as NULL during runtime                   //using Reflection


f1[0].set(f1[0].getName(), null);


System.out.println("after setting null to                             singletonObj--> "+s2.getInstance().hashCode()); 


   }


}


Output:

hashcode after creating new Intance--> 366712642

after setting null to singletonObj--> 1311053135


So here we can conclude that using reflection we can create a new instance even though contructor is private and we can change its state to null as well.


So the Question here is how we can come out of this problem. Here is the solution, we have to throw UnsupportedOperationException() from the constructor which can ensure if anybody try to create an instance, it will throw this exception.

Code Snippet:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private, else somebody can //easily creates its object.

private SingleTon()
{
     throw new UnsupportedOperationException();
}

public static  SingleTon getInstance()
{
if(singletonObj==null)
singletonObj=new SingleTon();

return singletonObj;

}


}


But We are not yet done!!, what will happen if multiple threads like Thread 1, Thread 2, Thread 3 will try access getInstance() method, will it creates three different singletonObj for three threads, well quite possible as per our above class design.

To resolve this issue, we should use synchronized keyword to make the getInstance method as Thread safe which ensures, at a time only one thread will be executed.

Lets imagine the scenario like Thread 1 access the getInstance() method so Thread 2 and Thread 3 will have to wait unless Thread 1 come out of getInstance() method. Next time when Thread2 or Thread 3 will access the getInstance() method, it will see that singleton instance has already been created so they wont create any other singleTon object. 

Well but it will impact the performance because every thread has to wait at the method level, to resolve this issue, we can synchronized only the condition where it check the instance value, which can improve the performance.

Here is the complete Singleton class:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private ,else                //somebody can easily creates its object.
private SingleTon()
{
throw new UnsupportedOperationException();
}
public static  SingleTon getInstance()
{

if(singletonObj==null)
synchronized (SingleTon.class) {
if(singletonObj==null)
singletonObj=new                                                    SingleTon();
}

return singletonObj;

}

}


/***************End of SingleTon design pattern**************/


You may also Like:

Design your custom or own HashMap implementation in JAVA







Saturday, 9 September 2017

Determine if a String has all unique character or not in JAVA

We can determine a String has all unique characters or not by several ways.
Suppose you are given a String like "abcdef10&g" and our program should return TRUE as it contains all unique characters, but for a String like "abccdefg", the output would be FALSE.

I am going to use a boolean array to solve this approach. Initially each element of the array would be FALSE. We will find out the ASCII value of each character and check the current value for that index in boolean array, if the value is FALSE that means the character is unique and make the value TRUE.

If the value is TRUE that means character is already present and the String contains non-unique characters.

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class UniqueString {
public static void main(String[] args) {
String uniqueTest="abcdef10gg";
if(isUniqueChanracter(uniqueTest))
System.out.println("Yes, Unique String.");
else
System.out.println("No, its not unique ");
}

private static boolean isUniqueChanracter(String uniqueTest) {

boolean unique_set[]=new boolean[256];
for(int i=0;i<uniqueTest.length();i++)
{
int val=uniqueTest.charAt(i);
if(unique_set[val])
return false;
else
unique_set[val]=true;
}
return true;
}

Friday, 8 September 2017

Converting String to Integer without using any Standard Library in JAVA

This question can be asked in both service and product based company as well.
Suppose you are given a String like "12345" and after converting it should be "12345".
Normally using standard library we can convert this using Integer.parseInt("") or Integer.valueOf("").

Without using standard library, we will find out ASCII code of each character and subtract it with '0' which will give current int value and finally multiply by 10 to get actual result.

Initially we will check it starts with negative or not, if negative then substract the result from 0 at last else do nothing.

Input: "12345"
Output: 12345

Input: "-12345"
Output: -12345

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class StringToInteger {

public static void main(String[] args) {

String number="-1234567";
System.out.println("Number is: "+ getNumber(number));

}
public static int getNumber(String number) {
   int result = 0;
   boolean isNegative=false;
   if(number.charAt(0)=='-')
   {
    isNegative=true;    
   }else
   {
    result=number.charAt(0)-'0';
   }
   for (int i = 1; i < number.length(); i++) {
    result = result * 10 + number.charAt(i) - '0';
   }
   if(isNegative)
    result=0-result;
   return result;

}



}

Thursday, 24 August 2017

Left rotation of an array by K steps in JAVA

This is another popular java coding interview question. You can find this question almost every online coding sites like HackerRank, leetcode etc.

We have an array mainArr[]={1,2,3,4,5,6}  and K is given as 3.

So after left rotation, actual array would be mainArr[]={4,5,6,1,2,3}.

Logic: I am using two arrays here. Temp[] array will hold the elements from 0th index to kth index , after that I will merge temp[] and mainArr[] into finalArr[].

Sample code:

/**
 * 
 * @author Sourin
 *
 */
public class LeftRotationOfAnArray {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("Enter the arrays length: \n");
int n=in.nextInt();
System.out.println("Enter the no of rotation needed.. \n");
int k=in.nextInt();
int mainArr[]=new int[n];
for(int i=0; i<n;i++)
{
mainArr[i]=in.nextInt();
}
int finalArr[]=makeLeftRotation(mainArr,n,k);
for(int m:finalArr)
{
System.out.println("After rotations: "+ m);
}
}
private static int[] makeLeftRotation(int[] mainArr, int n, int k) {
int finalArr[]=new int[n];
int temp[]=new int[k];
int j=0;
for(int l=0;l<k;l++)
{
temp[l]=mainArr[l];
}
for(int i=0;i<n;i++){
if(k<n){
finalArr[i]=mainArr[k];
k=k+1;

}else
{
finalArr[i]=temp[j];
j=j+1;
}
}
return finalArr;
}

}

Sample Output:

Enter the arrays length: 

6
Enter the no of rotation needed.. 

3
1
2
3
4
5
6
After rotations: 4
After rotations: 5
After rotations: 6
After rotations: 1
After rotations: 2
After rotations: 3


Wednesday, 16 August 2017

Write a program in JAVA to print EVEN and ODD numbers within a range using multithreading.

To solve this problem we will be using one volatile variable as the variable will be shared between multiple threads.

We will have two threads even and odd. The logic is when even thread is executing odd thread will be suspended.

Suppose the Given input is: 10 
so output would be:
Odd Thread: 1
Even Thread: 2
Odd Thread: 3
Even Thread: 4
Odd Thread: 5
Even Thread: 6
Odd Thread: 7
Even Thread: 8
Odd Thread: 9
Even Thread: 10


Implemented Code:

 public class ThreadEvenOdd extends Thread{
    //Volatile keyword as this variable is going to be shared between multiple threads
    public volatile static int i=1;
    public Object lock;
    public ThreadEvenOdd(Object ob)
    {
        this.lock=ob;
    }
    public static void main(String[] args) {
        //Createing two threads even and Odd.
        Object object=new Object();
        ThreadEvenOdd even=new ThreadEvenOdd(object);
        ThreadEvenOdd odd=new ThreadEvenOdd(object);
        even.setName("Even Thread");
        odd.setName("Odd Thread");
        even.start();
        odd.start();      
    }
    @Override
    public void run()
    {
        while(i<=10)
        {
            if(i%2==0 && Thread.currentThread().getName().equalsIgnoreCase("Even Thread"))
            {
                synchronized(lock)
                {
                    System.out.println(Thread.currentThread().getName()+": "+i);
                    i++;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(i%2==1 && Thread.currentThread().getName().equalsIgnoreCase("Odd Thread"))
            {
                synchronized(lock)
                {
                    System.out.println(Thread.currentThread().getName() + ": "+i);
                    i++;
                    lock.notify();
                }
            }
        }
    }
}
 



Monday, 14 August 2017

Divide two integers without using multiplication, division and mod operator

You are given one Dividend and Divisor. You need to find out the Quotient without using multiplication, division and mod operator.

For example :
Dividend=20 and Divisor=5 then Quotient=4
if Dividend=21 and Divisor=5, then Quotient=4

Sample code:

public class DivideTwoInt {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("Enter Integer to Dividend:  \n");
        int dividend=in.nextInt();
        System.out.println("Enter Divisor: \n");
        int divisor=in.nextInt();
        int count=checkDividend(dividend,divisor);
        System.out.println("Result is: "+count);

    }

    private static int checkDividend(int dividend, int divisor) {
        if(dividend==divisor)
            return 1;      
        if(dividend==0)
            return 0;
        if(divisor==0)
            return -1;
        int count=0;
        while(dividend>=divisor)
        {
            dividend=dividend-divisor;
            count=count+1;
        }
        return count;
    }
}



Sample Output 1:

Enter Integer to Dividend: 
20
Enter Divisor:
5
Result is: 4 


Sample output 2:

Enter Integer to Dividend: 
26
Enter Divisor:
5
Result is: 5

Write a program in JAVA where the sum of two elements of an array indices a specific target.

Another tricky question for java job seekers. You are given an array and a target element. You have to find out the sum of two elements which is equal to the specific target.

We will solve this approach by using Map. Time complexity would be O(n).

Sample Input:

Given array ={2,7,11,15};
Target element= 9
Output would be : 2 & 7.


Code:

public class SumOfTwoTarget {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        int nums[]={2,7,11,15};
        Scanner in=new Scanner(System.in);
        System.out.println("Please enter the target: \n");
        int target=in.nextInt();
        checkTargetExist(nums,target);

    }
// Logic is substract each element of that array from target and assign it to a variable called element.
//If that element is present in the map, then return that key else add the array element in map and continue. 


    private static void checkTargetExist(int[] nums, int target) {
        Map<Integer, Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++)
        {
            int element=target-nums[i];
            if(map.containsKey(element))
            {
                System.out.println("Target is present: values are: "+ map.get(element)+ " = "+i);
                return;
            }
            map.put(nums[i],i);
        }
        System.out.println("Sorry: Target is not present");
    }
}



Sample Output:

Please enter the target:
9
Target is present: values are: 0 = 1
 

Sunday, 13 August 2017

Write a program to find out the longest palindrome of a given String in JAVA

This is very tricky java interview questions. This question has been asked  in almost every product based company.

This problem can be asked in different ways like "find out no of palindromes of a given String"

Logic is pretty simple here. We will check every substring from start and end index. If the substring is palindrome then store it somewhere and check other substrings as well.

 So if the given input is "abcdcbaaaaaabccccba", then longest palindrome would be "cbaaaaaabc"

Sample Code:

/**
 * 
 * @author Sourin
 * 
 * This class is used to find out the longest palindrome of a given string. Logic is pretty simple, everytime 
 * we will pull out start and end index and check that is palindrome or not, if its palindrome store it somewhere and check the other substrings.
 *
 */
public class LongestPalindrome {
public static void main(String[] args) {
String palindrome="abcdcbaaaaaabccccba";
String longestPalindrome2=checkLongestPalindrome(palindrome);
System.out.println("Longest Palindrome is: "+ longestPalindrome2);
}
public static String checkLongestPalindrome(String palindrome)
{
String longestPalindrome="";
for(int i=0;i<palindrome.length();i++)
{
for(int j=palindrome.length()-1;j!=i;j--)
{
if(isPalindrome(palindrome.substring(i,j+1)))//check whether given string is palindrome or not.
{
if(palindrome.substring(i,j+1).length()>longestPalindrome.length())
{
longestPalindrome=palindrome.substring(i,j+1);
}
}
}
}
return longestPalindrome;
}
public static boolean isPalindrome(String ptest)
{
int k=ptest.length()-1;
for(int i=0;i<ptest.length()/2;i++)
{
if(ptest.charAt(i)!=ptest.charAt(k)){
return false;
}
k--;
}
return true;
}

}


Sample Output:


Longest Palindrome is: cbaaaaaabc





Write a program in java to do addition between two Linked List

This is one of the most common and tricky question in JAVA interview. I have faced this question during my interview with Nokia R&D.

We have two Linked Lists L1 and L2 having same or different size. We need to print the output.

Sample example1,
LinkedList l1: 4-->5-->3

LinkedList l2: 4-->5-->2

Output should be:
LinkedList l3: 8-->0-->6

Sample example2:

LinkedList l1: 4-->5-->3-->6

LinkedList l2: 4-->5-->2

Output:

LinkedList l3: 8-->0-->6-->6

Sample Code:

public class LinkListAddition {
public static void main(String[] args) {
LinkedList<Integer> linkList1=new LinkedList<>();
LinkedList<Integer> linkedList2=new LinkedList<>();
linkList1.add(2);/* adding values into the link lists*/ 
linkList1.add(4);
linkList1.add(3);
linkedList2.add(5);
linkedList2.add(6);
linkedList2.add(4);
linkedList2.add(8);
int carry=0;
Iterator<Integer> it1=linkList1.iterator();
Iterator<Integer> it2=linkedList2.iterator();
LinkedList< Integer> finalList=new LinkedList<>();
// Iterate through LinkedList 
while(it1.hasNext() || it2.hasNext())
{
int i=0;
int x=(it1.hasNext()?it1.next():0);
int y=(it2.hasNext()?it2.next():0);
int sum=x+y+carry;
if(sum>=10)
{
carry=sum/10;
finalList.add(sum%10);
}
else
{
finalList.add(sum%10);
carry=0;
}
i=i+1;
}
System.out.println("Lined List1: "+linkList1+" Linked List 2: "+ linkedList2 );
System.out.println("Output below:");
Iterator<Integer> it3=finalList.iterator();
while(it3.hasNext())
{
System.out.println("=>"+it3.next());
}
}
}


Sample Output:

Lined List1: [2, 4, 3] Linked List 2: [5, 6, 4, 8]
Output below:
=>7
=>0
=>8
=>8


Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...