Friday 23 December 2016

Interview Questions based on Method Overloading and Method Overriding

What is method overriding?

Modifying a super class method in the sub class is called method overriding. Using method overriding, we can change super class method according to the requirements of sub class.

What are the rules to be followed while overriding a method?

  • Must have the same argument list.
  • Must have the same return type, except that as of Java 5, the return type can be a subclass—this is known as a covariant return. 
  • Must not have a more restrictive access modifier.
  • May have a less restrictive access modifier.
  • Must not throw new or broader checked exceptions.
  • May throw fewer or narrower checked exceptions, or any unchecked exception.

Can we override static methods.? Explain the answer.

No, Static methods can not be overridden.
Explanation: Static method are not associated with any object.Even if we invoke any static method of the class on any object, at compile time, complier replaces the reference variable with the class name, therefore they can not be overridden.



What happens if we change the arguments of overriding method?

If we change the arguments of overriding method, then that method will be treated as overloaded not overridden.

Can we override protected method of super class as public method in the sub class?
Yes. We can change the visibility of overriding methods, but we can only increase it and can’t reduce it.

Can we change the return type of overriding method from Number type to Integer type?

Yes. The return type of the overriding method can be a sub-type of return type of super class(also knows as co-variance).

Can we override a super class method without throws clause as a method with throws clause in the sub class?

Yes, but only with unchecked type of exceptions.

Can we change an exception of a method with throws clause from NullPointerException to ArrayIndexOutOfBoundException while overriding it?

Yes. Overridden method may throw NullPointerException or it’s sub class exception or any unchecked type of exceptions.

What is the use of super keyword?

Using super keyword, we can refer super class version of overridden method in the sub class.

Can we override private methods?

No, we can not override private methods because private method is not visible in the sub class.

Can we remove throws clause of a method while overriding it?

Yes. You can remove throws clause of a method while overriding it.

What is method overloading?
When a class has more than one method with same name but different parameters, then we call those methods are overloaded. Overloaded methods will have same name but different number of arguments or different types of arguments.

What is method signature? What are the things it consist of?
Method signature is used by the compiler to differentiate the methods. Method signature consist of three things.
  •  Method name
  •  Number of arguments
  •  Types of arguments
Can we declare one overloaded method as static and another one as non-static?
Yes. Overloaded methods can be either static or non static.

How do compiler differentiate overloaded methods from duplicate methods?
Compiler uses method signature to check whether the method is overloaded or duplicated. Duplicate methods will have same method signatures i.e same name, same number of arguments and same types of arguments. Overloaded methods will also have same name but differ in number of arguments or else types of arguments.

Is it possible to have two methods in a class with same method signature but different return types?
No, compiler will give duplicate method error. Compiler checks only method signature for duplication not the return types. If two methods have same method signature, straight away it gives compile time error.

Can overloaded methods be synchronized?
Yes. Overloaded methods can be synchronized.
Can we overload main() method?
Yes, we can overload main() method. A class can have any number of main() methods but execution starts from public static void main(String[] args) only.

Can we declare overloaded methods as final?
Yes, we can declare overloaded methods as final.


Saturday 3 December 2016

Intermediate Level(1-3 yrs ) Interview Question based on Java Collections

The collection framework of Java is asked in almost every Java interview. In the last post I shared some of the collection questions which are asked the fresher level or below 1 year of experience. If you haven't gone through that here is the link for that.Java Collection Interview Question(0-1 Years). Below are some of questions that are asked at some experience level.

 

What is the difference between ArrayList and Vector ?


Vector is synchronized while ArrayList is not . Vector is slow while ArrayList is fast . Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%.

 

What is the difference between HashMap and Hashtable ?


a. HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
b. HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe .

 

What is the difference between peek(),poll() and remove() method of the Queue interface ?


Both poll() and remove() method is used to remove head object of the Queue. The main difference lies when the Queue is empty().
If Queue is empty then poll() method will return null . While in similar case , remove() method will throw NoSuchElementException .
peek() method retrieves but does not remove the head of the Queue. If queue is empty then peek() method also returns null.

 

What is the difference between Iterator and ListIterator.


Using Iterator we can traverse the list of objects in forward direction . But ListIterator can traverse the collection in both directions that is forward as well as backward.

 

What is the difference between Array and ArrayList in Java ?


a. Array is static in size while ArrayList is dynamic in size.
b. Array can contain primitive data types while ArrayList can not contain primitive data types.When you add any primitive data type to ArrayList, it will automatically convert it to its corresponding Wrapper class(auto Boxing).

 

What is the difference between HashSet and TreeSet ?


a.  HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
b. HashSet can store null object while TreeSet can not store null object.

 

What is the difference between HashMap and ConcurrentHashMap ?


Main differences between HashMap and ConcurrentHashMap are :
a. HashMap is not synchronized while ConcurrentHashMap is synchronized.
b. HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .

 

What is the difference between LinkedList and ArrayList in Java ?


Main differences between LinkedList and ArrayList are :
a. LinkedList is the doubly linked list implementation of list interface , while , ArrayList is the resizable array implementation of list interface.
b. LinkedList can be traversed in the reverse direction using descendingIterator() method  provided by the Java Api developers , while , we need to implement our own method to traverse ArrayList in the reverse direction.

 

Why Map interface does not extend the Collection interface in Java Collections Framework ?


Map interface is not compatible with the Collection interface.
Explanation : Since Map requires key as well as value , for example , if we want to add key-value pair then we will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap object  . In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet , keySet as well as other appropriate methods which have just different views from the Collection interface.

 

When to use ArrayList and when to use LinkedList in application?


ArrayList has constant time get operation O(1).Hence, ArrayList is preferred when the list is collection required more querying than modifying.
Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.

Suggested Posts:

Interview Questions on List Interface 

 

Friday 25 November 2016

Data Structures - UnderStanding Merge Sort

Data structures is asked in every programming interview. Irrespective of the programming language, data structures and algorithm puzzles are asked in every programming interview.Sorting is one of the most common topic asked in data structures.
 Merge Sort  works on the concept of Divide and Conquer approach.But it doesn't divides the list into two halves. In merge sort the unsorted list is divided into N sublists, each having one element, because a list of one element is considered sorted.

Wednesday 19 October 2016

Beginners Level(0-1 yrs ) Interview Question based on Java Collections

What is the root interface in collection hierarchy ?
Root interface in collection hierarchy is Collection interface .

What is the difference between Collection and Collections ?
Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.

Which collection classes are synchronized or thread-safe ?
Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).

Name the core Collection  interfaces ?
The list of core collection interfaces are : just mention the important ones
Important : Collection , Set , Queue , List , Map
Maps do not extend this interface, yet they are part of java collection framework
Other interface also in the list :  SortedSet, SortedMap , Deque, ListIterator etc.

What is the difference between List and Set ?
Set contain only unique elements while List can contain duplicate elements.
Set is unordered while List is ordered . List maintains the order in which the objects are added .

What is the difference between Map and Set ?
Map object has unique keys each containing some value, while Set contain only unique values.

What are the classes implementing List and Set interface ?
Class implementing List interface :  ArrayList , Vector , LinkedList ,
Class implementing Set interface :  HashSet , TreeSet

What is an iterator ?
Iterator is an interface . It is found in java.util package. It provides methods to iterate over any Collection.

What is the difference between Iterator and Enumeration ?

The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn't.
Hence , using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it .

Which design pattern followed by Iterator ?
It follows iterator design pattern. Iterator design pattern provides us to navigate through the collection of objects by using a common interface without letting us know about the underlying implementation.
Enumeration is an example of Iterator design pattern.

Which methods you need to override to use any object as key in HashMap ?
To use any object as key in HashMap , it needs to implement equals() and hashCode() method .

What is the difference between Queue and Stack ?
Queue is a data structure which is based on FIFO ( first in first out ) property . An example of Queue in real world is buying movie tickets in the multiplex or cinema theaters.
Stack is a data structure which is based on LIFO (last in first out) property . An example of Stack in real world is  insertion or removal of CD  from the CD case.

How to reverse the List in Collections ?
There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.
Collections.reverse(listobject);

How to convert the array of strings into the list ?
Arrays class of java.util package contains the method asList() which accepts the array as parameter.
So,

String[]  wordArray =  {"Hello" , "World" , "from Java"};
List wordList =  Arrays.asList(wordArray);

Thursday 13 October 2016

repeatEnd

Home
Goto Problem

Given a string and an int N, return a string made of N repetitions of the last N characters of the string. You may assume that N is between 0 and the length of the string, inclusive.
repeatEnd("Hello", 3) → "llollollo"
repeatEnd("Hello", 2) → "lolo"
repeatEnd("Hello", 1) → "o"

public String repeatEnd(String str, int n)

{
    String res=str.substring(str.length()-n);
    for(int i=1;i<n;i++)
            res=res+str.substring(str.length()-n);
    return res;
}

Tuesday 11 October 2016

List Interface - An Interview based approach.

List is all about indexes and index based access of elements. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like get(int index) , indexOf(Object o) , add(int index, Object obj) , and so on. The three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end. The three List implementations are described in the following sections.

ArrayList : ArrayList can be considered as dynamically resizing array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted. It implements RandomAccess interface—a marker interface that says, "this list supports fast (generally constant time) random access.

Vector : Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two original collections, the rest were added with Java 2 versions 1.2 and 1.4. A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety. You'll normally want to use ArrayList instead of Vector because the synchronized methods add a performance hit you might not need. And if you do need thread safety, there are utility methods in class Collections that can help. Vector is the only class other than ArrayList to implement RandomAccess.

LinkedList A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a  stack or queue. Remenber that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek() , poll() , and offer() .

ArrayList Vs LinkedList
  1.  Both are concrete implementations of List interface. 
  2.  ArrayList provided random access where as LinkedList provide sequential access.
  3.  Both LinkedList and ArrayList maintains the insertion order.
  4. Add operation of ArrayList is slower than that of LinkedList because it may involve resizing of array which requires creating new array and copying elements to new array.
  5. Get Opration of ArrayList is much faster than LinkedList. Time complexity of get operation of ArrayList is O(1) ie. constant time wheres as that of LinkedList is O(n)
  6. Both provide fail-fast iterator and throw concurrent modification exception.
Imporant : ArrayList is preferred when the list manipulation is done less frequently and the get operation is performed more frequently whereas LinkedList is preferred when the frequency of list manipulation is more than the frequency of get operation on the list.

Sunday 9 October 2016

Understanding Polymorphism in Java

Polymorphism is one of the hot topics for a java interview. Questions, based on polymorphism, are asked at every level in java interview. In java, polymorphism is achieved, when a method with same name but different body are executed under different conditions.Polymorphic method invocations apply only to instance methods. You can always refer to an object with a more general reference variable type (a superclass or interface), but at runtime, the ONLY things that are dynamically selected based on the actual object (rather than the reference type) are instance methods. In java, objects can only be accessed through reference variables. Let us see few important things regarding the reference type variables in java :

  • A reference variable can be of only one type, and once declared, that type can never be changed (although the object it references can change).
  • A reference is a variable, so it can be reassigned to other objects, (unless the reference is declared final ).
  • A reference variable's type determines the methods that can be invoked on the object the variable is referencing.
  • A reference variable can refer to any object of the same type as the declared reference, or—this is the big one—it can refer to any subtype of the declared type!
  • A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.
In java, there are two types of Polymorphism; 1. Runtime Polymorphism(implemented through method overriding). 2. Compile-time polymorphism(implemented through method overloading).

Method Overriding

When a method with same name and same signature is present in both Super class and Sub class, then the method in the super class is called over ridden method and the method in the sub class is called overriding method.Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method. The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type. The following example demonstrates a Horse subclass of Animal overriding the Animal version of the eat() method:

public class Animal {
	public void eat() {
		System.out.println("Eat method of Animal Class");
	}
}
class Horse extends Animal {
	public void eat() {
		System.out.println("Eat method of Horse class");
	}
}
public class TestAnimals 
{
	public static void main (String [] args) {
		Animal a = new Animal();
		Animal b = new Horse(); //Animal ref, but a Horse object
		a.eat(); // Runs the Animal version of eat()
		b.eat(); // Runs the Horse version of eat()
	}
}

In the above example,since,the object creation occurs at run time,therefore which version of eat() to be called is decided at run time.This why it is referred to as runtime polymorphism

Method Overloading

Two methods with same,name in same class but with different signatures will be referred to as as overloaded methods.Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type).


class SumNumber {
	public int getSum(int x, int y) {
		return x + y;
	}
	// Overload the getSum method to add doubles instead of ints
	public double getSum(double x, double y) {
		return x + y;
	}
}

public class TestSum{
	public static void main(String [] args)
	{
		SumNumber sn = new SumNumber();
		System.out.println("Sum of Integer : "+sn.getSum(10, 20));//Integer version of getSum is called
		System.out.println("Sum of Double : "+sn.getSum(10.5, 19.5));//Double version of getSum is called

	}
}

In the above example,which method of get sum is to be called is decided at compile time,based on method signature therefore it is called compile-time polymorphism

Some key take aways and rules regarding method overloading and method overriding

  • Methods can be overridden or overloaded; constructors can be overloaded but not overridden.
  • Abstract methods must be overridden by the first concrete (non-abstract) subclass.
  • With respect to the method it overrides, the overriding method
  • Must have the same argument list.
  • Must have the same return type, except that as of Java 5, the return type can be a subclass—this is known as a covariant return.
  • Must not have a more restrictive access modifier.
  • May have a less restrictive access modifier.
  • Must not throw new or broader checked exceptions.
  • May throw fewer or narrower checked exceptions, or any unchecked exception.
  • final methods cannot be overridden.
  • Only inherited methods may be overridden, and remember that private methods are not inherited.
  • A subclass uses super.overriddenMethodName() to call the superclass version of an overridden method.
  • Overloading means reusing a method name, but with different arguments.
  • Overloaded methods must have different argument lists.
  • Overloaded methods may have different return types, if argument lists are also different.
  • Overloaded methods may have different access modifiers.
  • Overloaded methods may throw different exceptions.
  • Methods from a superclass can be overloaded in a subclass.
  • Polymorphism applies to overriding, not to overloading.
  • Object type (not the reference variable's type), determines which overridden method is used at runtime.
  • Reference type determines which overloaded method will be used at compile time.

Saturday 8 October 2016

Yield Vs Join and Sleep Vs Wait

In this post, I am going to discuss about some of the important methods of Thread class and their usage.These methods are also actively asked in interviews.There is very little chance that you would have had the experience of actually using them at the starting level.It is expected from all the interviewee to have basic idea about these methods. Before diving straight into the topic, first let us gather some background information which will help us to understand them better.

Understanding thread priorities and thread scheduling

JVM is a preemptive, priority-based scheduler for threads.Each java thread has a well defined priority.A developer can change the priority of the thread as per the requirements.If the user doesn't set the priority of the thread, a default priority is set for each thread which is same for all in a particular java application.This priority value has its significance in multi threaded environment. It helps the JVM to decide which thread to execute when more than one threads are waiting for a common resource.This is why it is called priority based scheduler. The operating system generally chooses the thread with the highest priority. If any high priority thread is ready for the execution then the scheduler interrupts (preempts) the low priority thread. However, there is a catch, the OS may choose to wait the high priority thread and continue wit the lower priority thread(Ya ya... I know, OS some time can be moody -_- ).

  • Remember that all the threads carry normal priority when a priority is not specified.
  • Priorities can be specified from 1 to 10. 10 being the highest, 1 being the lowest priority and 5 being the normal priority.
  • Remember that the thread with highest priority will be given preference in execution. But there is no guarantee that it will be in running state the moment it starts.
  • It can be assumed that the currently executing thread might have the higher priority when compared to the threads in the pool who are waiting for their chance. However as we have learned this is not 100% guaranteed.
  • It is the thread scheduler which decides what thread should be executed.
  • setPriority(Thread.MIN_PRIORITY) method can be used to set the priority of the thread.
  • Remember that the priorities should be set before the threads start method is invoked.
  • Thread class provides some predefined constants for setting the priority, MIN_PRIORITY,MAX_PRIORITY and NORM_PRIORITY.

sleep() is a method which is used to hold the process for the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.


yield() is defined as following in Thread.java.

/**
  * A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore
  * this hint. Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilize a CPU.
  * Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
  */

public static native void yield();

A yielding thread tells the virtual machine that it’s willing to let other threads be scheduled in its place. This indicates that it’s not doing something too critical. Note that it’s only a hint, though, and not guaranteed to have any effect at all.

join() method

The join() method of a Thread instance can be used to “join” the start of a thread’s execution to the end of another thread’s execution so that a thread will not start running until another thread has ended. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing.


Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout. When the timeout is reached, the main thread and taskThread are equally probable candidates to execute. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

Like sleep, join responds to an interrupt by exiting with an InterruptedException.

Thursday 6 October 2016

The Two Synchronized method Problem

The Two Synchronized method Problem.

Problem Statement: A class has two synchronized (non-static)methods M1 and M2. Two different threads T1 and T2 simultaneously trying to access the methods M1 and M2 respectively.
Is is possible?


import java.util.concurrent.TimeUnit;

public class TwoSyncMethods {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  
  final TwoSyncMethods tsm = new TwoSyncMethods();
  new Thread(new Runnable() {
   
   @Override
   public void run() {
    try {
     tsm.m1();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }, "One").start();
  
   new Thread(new Runnable() {
   
   @Override
   public void run() {
    try {
     tsm.m2();//Calling other synchronized method on same object
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    
   }
  }, "Two").start();
  
 }

 public synchronized void m1() throws InterruptedException{
  System.out.println("Acquired by "+Thread.currentThread().getName());
  TimeUnit.SECONDS.sleep(2);  
  System.out.println("Released by "+Thread.currentThread().getName());
  
  
 }
  
 public synchronized void m2() throws InterruptedException
        {
   System.out.println("In Sync "+Thread.currentThread().getName());
   TimeUnit.SECONDS.sleep(5);
   System.out.println("In Sync After time out "+Thread.currentThread().getName());
  
 }
 
}

Answer. No,this is not possible.Two different methods can not access the two different synchronized method of the same class simultaneously.

Explanation : Every object has a monitor associated with it.For a thread to enter the synchronized block (also known as critical section), the thread must be the owner of the lock on the monitor. In other words, a thread must acquire a lock on the monitor if it wants to enter critical section.Now, since both the methods are non-static, therefore if they are called on the same object, the 1st thread, requesting the lock on monitor,will acquire the lock on the monitor while the 2nd thread will have to wait for lock to be released.

How to make it possible? As stated above, since same object is used to call both the methods, therefore once the lock is acquired by any one of the threads will cause the other thread to wait. So the solution to this to make two different objects of the class and then call the two methods simultaneously from the different threads using the different objects. This way, both the threads will acquire lock on the monitor of two different objects.


import java.util.concurrent.TimeUnit;

public class TwoSyncMethods {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  
  final TwoSyncMethods tsm1 = new TwoSyncMethods();
                final TwoSyncMethods tsm2 = new TwoSyncMethods();
  new Thread(new Runnable() {
   
   @Override
   public void run() {
    try {
     tsm1.m1();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }, "One").start();
  
   new Thread(new Runnable() {
   
   @Override
   public void run() {
    try {
     tsm2.m2();//Calling synchronized methods on different objects
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    
   }
  }, "Two").start();
  
 }

 public synchronized void m1() throws InterruptedException{
  System.out.println("Acquired by "+Thread.currentThread().getName());
  TimeUnit.SECONDS.sleep(2);  
  System.out.println("Released by "+Thread.currentThread().getName());
  
  
 }
  
 public synchronized void m2() throws InterruptedException
        {
   System.out.println("In Sync "+Thread.currentThread().getName());
   TimeUnit.SECONDS.sleep(5);
   System.out.println("In Sync After time out "+Thread.currentThread().getName());
  
 }
 
}

What is the state of the thread waiting for other thread to exit critical section?
Blocked

public class StateCheck {

    public synchronized void m1() {
        try { Thread.sleep(2000); }
        catch (InterruptedException ie) {}
    }

    public synchronized void m2() {
        try { Thread.sleep(2000); }
        catch (InterruptedException ie) {}
    }

    public static void main(String[] args) throws InterruptedException {
        final StateCheck t = new StateCheck();
        Thread t1 = new Thread() { public void run() { t.m1(); } };
        Thread t2 = new Thread() { public void run() { t.m2(); } };

        t1.start();
        Thread.sleep(500);

        t2.start();
        Thread.sleep(500);

        System.out.println(t2.getState());
    }
}
A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

Sunday 25 September 2016

repeatFront

Home
Goto Problem
Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive (i.e. n >= 0 and n <= str.length()).
repeatFront("Chocolate", 4) → "ChocChoChC"
repeatFront("Chocolate", 3) → "ChoChC"
repeatFront("Ice Cream", 2) → "IcI"

public String repeatFront(String str, int n) 
{
     String res=str.substring(0,n);
     for(int i=1;i<n;i++)
     {
            res=res+str.substring(0,n-i);
     }
     return res;
}

Saturday 10 September 2016

loneSum

Goto Problem

Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0

public int loneSum(int a, int b, int c) {
if(a==b) { if(a==c) return 0; else return c; }
if(a==c) { return b; } if(b==c) return a; else return a+b+c; }

Monday 5 September 2016

repeatSeparator

Home
Goto Problem

Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.
repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"

 public String repeatSeparator(String word, String sep, int count) 
 {
    String res=word;
    if(count==0) 
       return "";
   for(int i=1;i<count;i++)
   {
      res=res+sep;
      res=res+word;
   }
   return res;
}

Sunday 28 August 2016

prefixAgain

Home
Goto Problem
Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume that the string is not empty and that N is in the range 1..str.length().
prefixAgain("abXYabc", 1) → true
prefixAgain("abXYabc", 2) → true
prefixAgain("abXYabc", 3) → false

public boolean prefixAgain(String str, int n)
{
   String prefix=str.substring(0,n);
   return(str.substring(n).contains(prefix));

}

Friday 26 August 2016

getSandwich

Home
Goto Problem

A sandwich is two pieces of bread with something in between. Return the string that is between the first and last appearance of "bread" in the given string, or return the empty string "" if there are not two pieces of bread.
getSandwich("breadjambread") → "jam"
getSandwich("xxbreadjambreadyy") → "jam"
getSandwich("xxbreadyy") → ""

public String getSandwich(String str)

{
  if(str.indexOf("bread")==str.lastIndexOf("bread")) 
      return "";
  return(str.substring(str.indexOf("bread")+5,str.lastIndexOf("bread")));
}

Tuesday 23 August 2016

sameStarChar

Home
Goto Problem

Returns true if for every '*' (star) in the string, if there are chars both immediately before and after the star, they are the same.
sameStarChar("xy*yzz") → true
sameStarChar("xy*zzz") → false
sameStarChar("*xa*az") → true

public boolean sameStarChar(String str) {
  int i=1;
  while(i<str.length()-1){
  if(str.charAt(i)=='*'){
  if(str.charAt(i-1)!=str.charAt(i+1))
  return false;
  }
  i++;
  
  }
  return true;
  }

Tuesday 9 August 2016

xyzMiddle

Goto Problem

Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one. This problem is harder than it looks.

xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBB") → true
xyzMiddle("AxyzBBB") → false

public boolean xyzMiddle(String str) 
{
  int i=0;
  while(str.indexOf("xyz",i)!=-1)
 {
    i=str.indexOf("xyz",i);
    if(Math.abs(str.substring(0,i).length()-str.substring(i+3).length())<=1)
       return true;
   i++;
 }
 return false;
}

Wednesday 3 August 2016

zipZap

Home
Goto Problem

Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".

zipZap("zipXzap") → "zpXzp"
zipZap("zopzop") → "zpzp"
zipZap("zzzopzop") → "zzzpzp"

public String zipZap(String str)
{
  String temp=str,res="";
  int j=temp.length();
  int i=0;
  while(i<j-2)
  {
      if(temp.charAt(i)=='z' && temp.charAt(i+2)=='p')
     {
         res=res+temp.substring(0,i+1);
         temp=temp.substring(i+2);
         j=temp.length();
         i=0;
      }
     i++;
  }
res=res+temp; return res;
}

Monday 1 August 2016

starOut

Goto Problem

Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad".

starOut("ab*cd") → "ad"
starOut("ab**cd") → "ad"
starOut("sm*eilly") → "silly"

public String starOut(String str)
{ 
   String result = "";
   for(int i = 0; i < str.length(); i++)  
   {     
     if(str.charAt(i)=='*')     
     {
     }      
     else if(i != 0 && str.charAt(i-1)=='*')       
     { 
     }
     else  if(i != str.length() - 1 && str.charAt(i+1)=='*')
     {
     }    
     else 
     {      
          result += str.charAt(i);      
     }   
  }
     return result;   
}

Friday 29 July 2016

plusout

Goto Problem

Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

public String plusOut(String str, String word)
 {
    String res="";
    int i=0;
    while(i<str.length())
    {
       if(str.substring(i).startsWith(word))
       {
           res=res+word;
           i=i+word.length();
       }
       else 
       {
          res=res+"+";i++;
       }
    }
    return res;
 }

Wednesday 27 July 2016

The HelloWorldThread

Multithreading is one of the most powerful features of Java. Also it is the hottest topic in the Java Interviews at some experience level or even for freshers.This is a must know topic for every Java Developer.In every thread related Java interview, the basic understanding of threads will be tested by asking the wait(),notify() and notifyAll() methods. In the following post, you will get a basic idea about them, followed by some basic interview questions related to them.
The Object class in Java has three final methods that allow threads to communicate about the locked status of a resource. These are :

wait() :It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify() or notifyAll(). It also has a parameterized version wait(long timeout) which can be used to to pass the amount of time the particular thread should wait before it kicks off again even if the notify() is not called.This method must be called from the synchronized block.If the current thread is interrupted while waiting, it will throw the InterruptedException

notify() : It will wake up a single thread on the monitor associated with the synchronized object. If multiple threads are waiting to acquire the lock, only one of them will be notified.However, the awakened thread will still not be able to execute until and unless the lock is released by this thread.

notifyAll() : Almost similar to notify() in many prospects.It will wake up all the threads that are waiting on the monitor associated with the synchronized object.However, if the awakened threads will try to get the lock on the object, only one thread will be given the lock and the rest of them will again go in the waiting state.The awakened threads will complete their execution in the usual manner.

One common characteristic among the three is that they will throw IllegalMonitorStateException if the current thread is not the owner of this object's monitor.

FAQs

Q. What happens to the lock when the wait method is called?
A. It releases the lock on the monitor.
Q. What is the difference between notify() and notifyAll()?
A. notify() wakes up only one of the threads waiting due to the monitor lock whereas notifyAll() wakes up all the threads.
Q. Can we some how control which thread to wake using notify()?
A. No,this can not be controlled.
Q. Why are these methods in Object class and not in Thread class?
A.Because these methods are used for locking which can be performed on objects and not threads. Apart from threads, these methods are the only way to communicate between the two objects.

Implementation of these methods

Write a Program that will start two threads. One thread will be used to print "Hello" and the other thread should print "World". This should be printed 5 times.

This problem can be treated as a classic Producer-Consumer problem. The HelloPrinter can be considered as Producer and the WorldPrinter can be considered as consumer.Both will take turns to do their job in a synchronized environment.

import java.util.concurrent.TimeUnit;

public class HelloWorldThread
{
 private int helloCount=0;
 private int worldCount=0;
 public final int totalCount=5;// 
 
 public static void main(String[] args) {

  HelloWorldThread hwt = new HelloWorldThread();
  //Sharing same object between threads
  Thread ht = new Thread(new HelloPrinter(hwt));
  Thread wt = new Thread(new WorldPrinter(hwt));

  ht.start();
  wt.start();
  
 }

 public int getHelloCount() {
  return helloCount;
 }

 public void setHelloCount(int helloCount) {
  this.helloCount = helloCount;
 }

 public int getWorldCount() {
  return worldCount;
 }

 public void setWorldCount(int worldCount) {
  this.worldCount = worldCount;
 }

}


class HelloPrinter implements Runnable
{

 HelloWorldThread hwt=null;

 public HelloPrinter(HelloWorldThread hwt) 
 {
  this.hwt=hwt;
 }
 @Override
 public void run() {
  try
  {
   synchronized (hwt) //Critical Section begins
   {
    int helloCount=0;
    while(hwt.getHelloCount() < hwt.totalCount)
    {
     if(hwt.getHelloCount()>hwt.getWorldCount())
     {
      hwt.wait();
     }
     helloCount++;
     System.out.print("Hello ");
     TimeUnit.MILLISECONDS.sleep(200);
     hwt.setHelloCount(helloCount);//Updating the count
     hwt.notify();
    }
   }
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
 }
}

class WorldPrinter implements Runnable
{

 HelloWorldThread hwt=null;

 public WorldPrinter(HelloWorldThread hwt) 
 {
  this.hwt=hwt;
 }
 @Override
 public void run() {
  try
  {
   synchronized (hwt) //Critical Section begins
   {
    int worldCount=0;
    while(hwt.getWorldCount() < hwt.totalCount)
    {
     if(hwt.getHelloCount()==hwt.getWorldCount())
     {
      hwt.wait();
     }
     worldCount++;
     System.out.println("World!!");
     TimeUnit.SECONDS.sleep(1);
     hwt.setWorldCount(worldCount);//Updating the count
     hwt.notify();
    }
   }
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
 }
}


Monday 25 July 2016

withoutString

Goto Problem

Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".

withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"

public String withoutString(String base, String remove)
 {
      String res="";
      int i=0;
      while(i<=(base.length()-remove.length()))
       {
           if(base.substring(i,i+remove.length()).equalsIgnoreCase(remove))
           {
               i=i+remove.length();
               continue;
           }
            res=res+base.charAt(i);
            i++;
        }
        res=res+base.substring(i);
        return res;
  }

Sunday 24 July 2016

Forever Singleton

What is Singleton? or What are singleton classes? or What is Singleton Design Pattern. These are one of the most common interview questions asked in Java as some experience level.There are various methods by which one can implement singleton class depending upon the requirement. The implementation is fairly simple yet a lot of complexity is involved while working with singleton classes, specially in multi-threaded environment.Following are some of the common ways of making a class singleton.

Eager Initialization


public class EagerInitialization
{
        private static volatile EagerInitialization singleInstance = new EagerInitialization();

        // private constructor
        private EagerInitialization()
       {
        }

        public static EagerInitialization getInstance()
    {
                return singleInstance;
        }
}

This is the most simple way of creating a singleton class.The singleInstance of class is a static variable and will be initialized only once, as soon as the class is loaded in to the memory.Notice the private constructor of the class, which will prevent any other class from making the object. The only way to get the object of the EagerInitialization class is to call the public getInstance() method of the class.
 Despite the simplicity of this method, it is not preferred. The major pitfall of this method is that Instance is created irrespective of it is requirement at runtime. Now, there might be a possibility that this heavy instance might go unused throughout the application. If you can sleep on that, then this is the best approach.

Lazy Initialization


public final class LazyInitializationSingleton
{
        private static volatile LazyInitializationSingleton lazyInstance = null;

      // private constructor
     private LazyInitializationSingleton()
     {
     }
     public static LazyInitializationSingleton getInstance()
    {
       if (lazyInstance == null)
          {
             synchronized (LazyInitializationSingleton.class)
             {
                 lazyInstance = new LazyInitializationSingleton();
              }
            }
            return lazyInstance;
      }
 }

There are 3 take aways from this.

1. It solved the problem of Eager Initialization, it the object will be created only when it is required for the first time
2.The lazyInstance of the class is made volatile so as to avoid any caching related issues.
3. The object creation is done inside the synchronized block.
In this, on first invocation the object will be created and the same object will be returned in subsequent invocations.Although at first, this method seems to solve all the problems but it has its own drawback in multi-threaded environment.
Suppose there are two Threads, T1 and T2, and both check for the null condition at the same time. Since the lazyInstance will be null for both, they both will assume that object needs to be created and will enter the synchronized block sequentially and will create the object.

DoubleCheckSingleton


public class DoubleCheckSingleton
{
  private static volatile DoubleCheckSingleton instance = null;

  // private constructor
  private DoubleCheckSingleton()
  {
  }

  public static DoubleCheckSingleton getInstance()
  {
    if (instance == null)
      {
      synchronized (DoubleCheckSingleton.class)
    {
        // Double check
        if (instance == null)
        {
          instance = new DoubleCheckSingleton();
        }
      }
    }
    return instance;
  }
}

This is the correct implementation of singleton class.Re checking the instance for null inside the synchronized block makes this class thread safe singleton.

Bill pugh solution

This is my personal favorite method of making a class singleton.It uses the concept of static block initialization with the advantage of Lazy Initialization.

public class BillPughSingleton
{
// private constructor
 private BillPughSingleton()
  {
  }
  private static class LazyHolder
  {
    private static final BillPughSingleton INSTANCE = new BillPughSingleton();
  }

  public static BillPughSingleton getInstance()
  {
    return LazyHolder.INSTANCE;
  }
}

As you can see, the static inner class will be loaded on the first invocation of getInstance method. And on subsequent invocations, the same object will be returned from the static inner class.

Using Enum


We use enum to create a single object of the class. Enum, as written in java docs, provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort.

public enum EnumSingleton
{
  INSTANCE;
 
}

Now, based on your requirement you can choose which implementation of Singleton suits the purpose.



countCode

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

countCode("aaacodebbb") → 1
countCode("codexxcode") → 2
countCode("cozexxcope") → 2

public int countCode(String str)
{
   int count =0;
    for(int i=0;i<str.length()-3;i++)
   {
      if(str.charAt(i)=='c' && str.charAt(i+1)=='o' && str.charAt(i+3)=='e')
      count++;
   }
  return count;
 }

Friday 22 July 2016

endOther

Goto Problem
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.

endOther("Hiabc", "abc") → true
endOther("AbC", "HiaBc") → true
endOther("abc", "abXabc") → true

public boolean endOther(String a, String b)
{
   String al=a.toLowerCase(),bl=b.toLowerCase();
   return(al.endsWith(bl) || bl.endsWith(al));
}

Tuesday 19 July 2016

xyBalance

Home

Goto Problem

We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced.

xyBalance("aaxbby") → true
xyBalance("aaxbb") → false
xyBalance("yaaxbb") → false
public boolean xyBalance(String str)
{
 int i=0;
 boolean res=true;
 while(i<str.length())
 {
 if(str.charAt(i)=='x')
 {
  for(int j=i;j<str.length();j++)
  {
      if(str.charAt(j)=='y')
     {
        res=true;
        break;
      }
    else
         res=false;
  }
   }
 i++;
  }
 return res;
 }

Sunday 5 June 2016

wordEnds

Goto Problem

Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

wordEnds("abcXY123XYijk", "XY") → "c13i"
wordEnds("XY123XY", "XY") → "13"
wordEnds("XY1XY", "XY") → "11"
public String wordEnds(String str, String word)
 {
    String res="";
    if(word.equals(str))
       return res;
    if(str.startsWith(word)) 
    res=res+str.charAt(word.length());
    int i=1;
    while(i<(str.length()-word.length()))
   {
      if(str.substring(i).startsWith(word))
      {
         res=res+str.charAt(i-1)+str.charAt(i+word.length()); i=i+word.length();
       }
      else
       {
          i++;
       }
    }
    if(str.endsWith(word))
    {
        res=res+str.charAt(str.length()-word.length()-1);
        }
     return res;
 }

countYZ

Goto Problem

Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)


countYZ("fez day") → 2

countYZ("day fez") → 2

countYZ("day fyyyz") → 2

public int countYZ(String str)
{
str=str.toLowerCase();
int count=0;
for(int i=0;i<str.length()-1;i++)
{
if(str.charAt(i)=='y' || str.charAt(i)=='z')
{
if(!Character.isLetter(str.charAt(i+1)))
count++;
}
}
if(str.charAt(str.length()-1)=='y' || str.charAt(str.length()-1)=='z') count++;
return count;
}

Friday 3 June 2016

NullPointerException - Every Java Developer’s Nightmare

NullPointerException is a nightmare for any java programmer. The moment you move form primitive variables to reference variables, NullPointerException will begin to haunt you. This exception is most common and most annoying.  If you are a java developer, there is no way that you can avoid it. When I started development through java, there is nothing that I fear more than NullPointerException in my code.
When I first got the NullPointerException in my program, it kept me wondering that when java doesn’t support pointer how a NullPointerException can occur. I think it should have been named as NullReference Exception.  But as I explored the depths of java, I came to know about pointers in java too. Although a programmer neither can control nor can access the pointers, since they are implicitly managed by the JVM.  I have faced this exception many times during my project and was able to remove it and therefore I decided to honor it by writing about it.

Why is NullPointerException considered as programmer’s nightmare?

The main reason for this is that error description for NullPointerException doesn’t tells about the name of the null reference which caused the exception. The programmers, mostly beginners spend a lot of time in finding the reason for this error. Also it happens to occur frequently that it gets you tilted! On checking the stack trace, the line where this exception actually occurs is shown at the last. The first error is shown in the line in main() where the method (causing NullPointerException) is called. Since in java, the propagation of exception is stack based, it is very difficult to trace the line of origin of exception especially when a chain of methods is formed.

   Scenarios when we get NullPointerException.

Java API documentation says that NullPointerException can be thrown, when there is an attempt to use null where an object is required. That is you are trying to access a reference where there is no value. In java the references are used in calling the instance methods of the class. When the reference is used before it is being initialized to a default value, or is initialized as null.  When you pass null to a method when it expects a real value. It means to say that null object is used illegally.
How to prevent or solve the NullPointerException?
The solution is very simple. Put a null check for the reference variable using the if statement before the is used.
if(object!=null)
{
    Perform task with object.
}
However using this check pollutes the code when the number of reference variable is high in the code. But to avoid the pitfall, one has to use this ugly code.  A simple example is to have proper ‘required field’ check at GUI level, when your business logic expects an operation on a given object. Then you can depend on your design and omit the if-null-check which beefs up your code.

Ways of handling NullPointerException.?

  • Always use if-null-check when you don’t have control over the object’s value. (Ugly but no choice!)
  • Put the string constant first from left when comparing values with a String variable.
  • Erroneously don’t declare a variable inside a constructor, it will hide the instance variable.
  • Religiously initialize (fill) arrays immediately after declaration. Arrays mostly causes NullPointerException.