Sunday, 23 August 2015

Java Interview Programs


Java Interview Programs

I have been posting java programs on various topics such as Binary tree, LinkedList , String, Number, ArrayList, HashMap etc. So I am consolidating list of programs to create an index post. I will keep adding links to this post whenever I add any new program. These are frequently asked programs in interview.

LinkedList :

1. How to reverse a linked list in java 
2. How to detect a loop in linked list in java
3. How to find middle element of linked list in java 
4. How to find nth element from end of linked list 

Binary tree :

1. Binary tree in java
2. Binary tree preorder traversal
3. Binary tree postorder traversal
4. Binary tree inorder traversal
5. Binary tree level order traversal
6. Binary tree spiral order traversal
7. Print leaf nodes of binary tree
8. Count leaf nodes in binary tree
9. Print all paths from root to leaf in binary tree

String :

1. How to reverse String in java
2. Find length of String without using java inbuilt length method
3. Find all substrings of String in java
4. Find First non repeated character in a String
5. Java Program to check Palindrome String

Number :

1. How to swap two numbers without using temporary variables
2. Java program to check prime number
3. Find prime factors of number in java
4. Java Program to check armstrong number
5. Fibonacci series program in java
6. Java Program to check Palindrome Number

ArrayList :

1. How to Sort ArrayList based on attributes using Comparator in java
2. How to sort ArrayList based on attributes using Comparable in java
3. How to remove duplicates from list in java
4. How to iterate over ArrayList in java

HashMap :

1. How HashMap internally works in java
2. How to iterate over HashMap in java

Algorithm :

1. How to calculate complexity of algorithm
2. Binary Search in java

Thursday, 20 August 2015

Java Timer example

Timer is an utility class which can be used to schedule tasks on specific time or repeatedly.
Lets say, you are developing an banking application and there is need to process the data at 7 PM evening daily. You can easily schedule task using Timer class.

For creating a task, you need to extends TimerTask and Timer can be used to set time for the task.

TimerTask : It is task which will be executed at specific time.
Timer : It is utility class which is used to set time for the task.

Timer class is thread safe , so multiple threads can share one timer object. Timer class internally uses java.util.TaskQueue to manage task internally. Only one thread can execute timer task at a time.
For example:
You are executing task in every 5 secs but actual execution itself is taking 10 seconds, then subsequent task will be added to queue and as soon as current execution completes, it will notify and another thread will start executing the task.
When you debug timer object, it looks something like this.

Methods for scheduling task:

There are several methods in timer class that can be used to schedule.

For one time execution:
public void schedule(TimerTask task, long delay,long period)
For example:
// it will execute timer task after delay of 5 seconds
timer.schedule(new MyTimerTask(),5000);

For repeated execution:
public void schedule(TimerTask task,long delay)
For example:
// it will execute timer task in every 2 seconds after first delay of 1 second
timer.schedule(new MyTimerTask(),1000,2000);

For executing task at particular time:
public void schedule(TimerTask task, Date time)
For example:
  // Scheduling task at today : 23:13:00 PM
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.HOUR_OF_DAY, 23);
  calendar.set(Calendar.MINUTE, 13);
  calendar.set(Calendar.SECOND, 0);
  Date time = calendar.getTime();

  timer.schedule(new MyTimerTask(timer), time);

For executing task at particular time repeatedly:
public void schedule(TimerTask task, Date firstTime, long period)

Example:

For one time exectution:

Create a class MyTimerTask.java
package org.arpit.java2blog.timer;

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask{
 
 Timer timer;
 public MyTimerTask(Timer timer) {
  this.timer=timer;
 }

 @Override
 public void run() {
  System.out.println("Executing timer task");
  // to stop timer thread
  timer.cancel();
  
 }

}
In above class, we are using timer.cancel() to stop the timer thread. When you call timer.cancel() method, it completes execution of current thread and discards all other threads which are in queue.

Create a class TimerMain.java.
package org.arpit.java2blog.timer;

import java.util.Timer;

public class TimerMain {

 public static void main(String[] args) {
  // It will create new thread
  Timer timer=new Timer();
  //  task will be scheduled after 5 sec delay
  timer.schedule(new MyTimerTask(timer), 5000);
 

 }

}
When you run above program, you will get following output:
Executing timer task

For repeated execution:

Create a class MyTimerTask.java
package org.arpit.java2blog.timer;

import java.util.TimerTask;

public class MyTimerTask extends TimerTask{

 @Override
 public void run() {  
  System.out.println("Executing timer task on "+TimerMain.convertTimeToDateFormat(System.currentTimeMillis()));
 }

}

Create a class TimerMain.java.
package org.arpit.java2blog.timer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

public class TimerMain {

 public static void main(String[] args) {
  System.out.println("Timer tasks started on "+convertTimeToDateFormat(System.currentTimeMillis()));
  System.out.println("**************************");
  // It will create new thread
  Timer timer=new Timer();

  timer.schedule(new MyTimerTask(), 1000,2000);

  // Stopping the timer thread after some time for example :12 secs.

  try {
   Thread.sleep(12000);
  } catch (InterruptedException e) {

   e.printStackTrace();
  }

  // you can call timer.cancel() or System.exit(0)
  System.out.println("**************************");
  System.out.println("Timer tasks finished on "+convertTimeToDateFormat(System.currentTimeMillis()));

  System.exit(0);
 }

 public static String convertTimeToDateFormat(long milliseconds)
 {
  SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");    
  Date resultdate = new Date(milliseconds);
  return sdf.format(resultdate);
 }

}
When you run above program, you will get following output:
Timer tasks started on Aug 18,2015 22:48:22
**************************
Executing timer task on Aug 18,2015 22:48:23
Executing timer task on Aug 18,2015 22:48:25
Executing timer task on Aug 18,2015 22:48:27
Executing timer task on Aug 18,2015 22:48:29
Executing timer task on Aug 18,2015 22:48:31
Executing timer task on Aug 18,2015 22:48:33
**************************
Timer tasks finished on Aug 18,2015 22:48:34

For executing task at particular time:

Create a class MyTimerTask.java
package org.arpit.java2blog.timer;

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask{

 Timer timer;

 MyTimerTask(Timer timer)
 {
  this.timer=timer;
 }
 @Override
 public void run() {  
  System.out.println("Executing timer task on "+TimerMain.convertTimeToDateFormat(System.currentTimeMillis()));
  // to stop time thread
  timer.cancel();
 }

}

Create a class TimerMain.java.

package org.arpit.java2blog.timer;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

public class TimerMain {

 public static void main(String[] args) {
  System.out.println("Timer tasks started on "+convertTimeToDateFormat(System.currentTimeMillis()));
  System.out.println("**************************");
  // It will create new thread
  Timer timer=new Timer();

  // Scheduling task at today : 23:13:00 PM
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.HOUR_OF_DAY, 23);
  calendar.set(Calendar.MINUTE, 13);
  calendar.set(Calendar.SECOND, 0);
  Date time = calendar.getTime();

  timer.schedule(new MyTimerTask(timer), time);

 }

 public static String convertTimeToDateFormat(long milliseconds)
 {
  SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");    
  Date resultdate = new Date(milliseconds);
  return sdf.format(resultdate);
 }

}

When you run above program, you will get following output:
Timer tasks started on Aug 18,2015 23:12:40
**************************
Executing timer task on Aug 18,2015 23:13:00

Saturday, 8 August 2015

CountDownLatch in java

As per java docs, CountDownLatch is synchronisation aid that allow one or more threads to wait until set of operations being performed in other threads completes.
So in other words, CountDownLatch waits for other threads to complete set of operations.

CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it's interrupted by another thread and all other thread need to call latch.countDown() once they complete some operation.

So count is reduced by 1 whenever latch.countDown() method get called, so  if count is n that means count can be used as n threads have to complete some action or some action have to be completed n times.

One of disadvantage of CountDownLatch is you can not reuse it once count is zero. For that ,you need to use CyclicBarrier.

For example:

Below diagram will make you clear. It is an example how CountDownLatch can be used.
Let's say, you are developing an application, so it's main thread has to wait for other services (threads) such as UI initialization, database initialization and logging services to get completed.  So Countdownlatch will be initialized with 3 and main thread will call await()  method and each services will call latch.countDown() once they are about to complete.



Program :

Create a class named UIInitialization.java. This thread will execute latch.countDown() once it completes.
package org.arpit.java2blog.thread;

import java.util.concurrent.CountDownLatch;

public class UIInitialization implements Runnable{

 CountDownLatch latch;
 UIInitialization(CountDownLatch latch)
 {
  this.latch=latch;
 }
 @Override
 public void run() {
  System.out.println("Initializing UI");
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Done with UI Initialization");
  latch.countDown();
 }

 
}

Create a class named LoggingInitialization.java. This thread will execute latch.countDown() once it completes.
package org.arpit.java2blog.thread;

import java.util.concurrent.CountDownLatch;

public class LoggingInitialization implements Runnable{

 CountDownLatch latch;
 LoggingInitialization(CountDownLatch latch)
 {
  this.latch=latch;
 }
 @Override
 public void run() {
  System.out.println("Initializing Logging");
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Done with Logging Initialization");
  latch.countDown();
 }

 
}
Create a class named DatabaseInitialization.java. This thread will execute latch.countDown() once it completes.

package org.arpit.java2blog.thread;

import java.util.concurrent.CountDownLatch;

public class DatabaseInitialization implements Runnable{

 CountDownLatch latch;
 DatabaseInitialization(CountDownLatch latch)
 {
  this.latch=latch;
 }
 @Override
 public void run() {
  System.out.println("Initializing Database");
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Done with database Initialization");
  latch.countDown();
 }

 
}

Create a class CountDownLatchMain.java. This will be main thread which will wait for UIInitialization, DatabaseInitialization and LoggingInitialization.
package org.arpit.java2blog.thread;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchMain {

 public static void main(String[] args) {
  try {
   CountDownLatch latch = new CountDownLatch(3);

   // Initializing three dependent thread i.e. UI, database and logging

   UIInitialization uiInitialization = new UIInitialization(latch);
   Thread uiThread = new Thread(uiInitialization);

   DatabaseInitialization dataBaseInitialization = new DatabaseInitialization(latch);
   Thread databaseThread = new Thread(dataBaseInitialization);

   LoggingInitialization loggingInitialization = new LoggingInitialization(latch);
   Thread loggingThread = new Thread(loggingInitialization);

   uiThread.start();
   databaseThread.start();
   loggingThread.start();
   // Main thread will wait until above threads get completed
   latch.await();
   
   System.out.println("Initialization has been completed, main thread can proceed now");
  } catch (InterruptedException e) {

   e.printStackTrace();
  }

 }
}

When you run above program, you will get following output:
Initializing UI
Initializing Database
Initializing Logging
Done with Logging Initialization
Done with UI Initialization
Done with database Initialization
Initialization has been completed, main thread can proceed now

Why not use join instead of CountDownLatch:

As you might know you can use join for this situation too but you have to manually handles it. Most of people use ExecutorService for handling threads now and CountDownLatch works good with it. As CountDownLatch is task oriented , you can submit multiple tasks to thread pool and CountDownLatch will ensure execution of original thread once set of other  dependent threads get completed.

Fibonacci series program in java

Fibonacci series is numerical series in which next number is sum of previous two numbers.
For example :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
There are two ways to print Fibonacci series.
  • Using iteration
  • Using recursion

Using iteration:

Algorithm:

  • Initialise first two terms with 0 and 1
  • Find sum of first two terms. 
  • Iterate upto numberOfElements
  • Print the sum
  • Assign prev to next and next to sum to go for next two terms. 

Program:

 package org.arpit.java2blog.algo;

public class FibonnacciIterativeMain
{ 
 public static void main(String[] args)
 {
  System.out.println("Printing Fibonacci series:");
  // first two number of series
  int prev=0,next=1;
  //printing first two elements
  System.out.print(prev+" "+next);
  //number of elements to be printed
  int numberOfElements=10;
  int sum=0;
  for(int i=2;i<numberOfElements;i++)
  {
   sum=prev+next;
   System.out.print(" "+sum);
   prev=next;
   next=sum;
  }
 }

}
When you run above program, you will get following output:
 
Printing Fibonacci series:
0 1 1 2 3 5 8 13 21 34

Using recursion:

Algorithm:

  • Initialise first two terms with 0 and 1
  • Base case will be when numberOfElements becomes 0.
  • Find sum of first two terms. 
  • Print the sum
  • Assign prev to next and next to sum to go for next two terms. 
  • Call same function again and decrease numberOfElements.

Program:

 package org.arpit.java2blog.algo;

public class FibonnacciRecursionMain
{ 
 //First two number of series
 static int prev=0,next=1;
    static int sum=0;
 public static void main(String[] args)
 {
  
  System.out.println("Printing Fibonacci series:");
  
  //printing first two elements  
  System.out.print(prev+" "+next);
  //number of elements to be printed
  int numberOfElements=10;
  // -2 because we have already printed 2 elements
  printFibonacciSeriers(numberOfElements-2);
 }
 
 public static void printFibonacciSeriers(int numberOfElements)
 {
  if(numberOfElements==0)
   return;
  else
  {
   sum=prev+next;
   System.out.print(" "+sum);
   //prepare for next 2 terms
   prev=next;
   next=sum;
   printFibonacciSeriers(numberOfElements-1);
  }
  
 }
}
When you run above program, you will get following output:
 
Printing Fibonacci series:
0 1 1 2 3 5 8 13 21 34

Thursday, 6 August 2015

How to remove duplicates from ArrayList in java

In this post, we will see how to remove duplicate elements from ArrayList in java.
There are many ways to do it. Some of them are:
  • Using iterative approach
  • Using HashSet (but does not maintain insertion order)
  • Using LinkedHashMap

Program:

package org.arpit.java2blog.algo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;

public class RemoveDuplicatesArrayListMain {
 /*
  * @author : Arpit Mandliya
  */
 public static void main(String[] args) {
  ArrayList<String> employeeNameList = new ArrayList<String>();
  employeeNameList.add("John");
  employeeNameList.add("Ankit");
  employeeNameList.add("Rohan");
  employeeNameList.add("John");
  employeeNameList.add("Amit");
  employeeNameList.add("Ankit");

  System.out.println("Removing duplicates from list:");
  // Using iterative approach
  ArrayList<String> uniqueElements = new ArrayList<String>();
  for (String empName : employeeNameList) {

   if (!uniqueElements.contains(empName)) {
    uniqueElements.add(empName);
   }
  }
  
  System.out.println("Using iterative approach:");
  for (String uniqElem : uniqueElements) {
   System.out.println(uniqElem);
  }
  System.out.println("*******************************");
  System.out.println("Using HashSet :");
  // using HashSet but does not maintain order
  uniqueElements = new ArrayList<String>(new HashSet<String>(
    employeeNameList));
  for (String uniqElem : uniqueElements) {
   System.out.println(uniqElem);
  }
  System.out.println("*******************************");
  System.out.println("Using LinkedHashSet :");
  // using LinkedHashSet maintaining order
  uniqueElements = new ArrayList<String>(new LinkedHashSet<String>(
    employeeNameList));
  for (String uniqElem : uniqueElements) {
   System.out.println(uniqElem);
  }

 }
}
When you run above program, you will get following output:
Removing duplicates from list:
Using iterative approach:
John
Ankit
Rohan
Amit
*******************************
Using HashSet :
Rohan
Ankit
Amit
John
*******************************
Using LinkedHashSet :
John
Ankit
Rohan
Amit

Find first non repeated character in a String

One of the interview question is "How will you find first non repeating character in String."
For example:
If input string is "analogy",  then program should return 'n'
If input string is "easiest", then program should return 'a'

First approach:

We will use LinkedHashMap to find first non repeating character in String.

Algorithm:

  • Get character while looping over String
  • Put this character in LinkedHashMap with count. If character is already there, increase count by 1.
  • Get count from LinkedHashMap while iterating. If count is 1,return that character as LinkedHashMap maintains insertion order.

Program:

package org.arpit.java2blog.algo;

import java.text.*;
import java.util.*;
import java.util.Map.Entry;

public class GetFirstNonRepeatingCharacterMain {
 public static void main(String[] args) {
  System.out
    .println("First non repeated character for String analogy is : "
      + getNonRepeatedCharacter("analogy"));
  System.out
    .println("First non repeated character for String easiest is : "
      + getNonRepeatedCharacter("easiest"));
 }

 public static Character getNonRepeatedCharacter(String str) {
  Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();
  for (int i = 0; i < str.length() - 1; i++) {
   Character c = str.charAt(i);
   if (!countCharacters.containsKey(c)) {
    countCharacters.put(c, 1);
   } else {
    countCharacters.put(c, countCharacters.get(c) + 1);
   }
  }
  // As LinkedHashMap maintains insertion order, first character with
  // count 1 should return first non repeated character
  for (Entry<Character, Integer> e : countCharacters.entrySet()) {
   if (e.getValue() == 1)
    return e.getKey();

  }
  return null;

 }
}


When you run above program, you will get following output:
First non repeated character for String analogy is : n
First non repeated character for String easiest is : a

Second Approach:

Algorithm:

  • Iterate through each character of string.
  • If lastIndexOf and indexOf return same value, then it is first non repeating character in the String.

Program:

package org.arpit.java2blog.algo
public class GetFirstNonRepeatingCharacterMain
{
 public static void main(String[] args)
 {
        System.out.println("First non repeated character for String analogy is : "+getNonRepeatedCharacter("analogy"));
        System.out.println("First non repeated character for String easiest is : "+getNonRepeatedCharacter("easiest"));
 }
 public static Character getNonRepeatedCharacter(String str)
 {     char charaaray[]=str.toCharArray();
       for (int i=0; i<str.length();i++)
      {
          if (str.lastIndexOf(charaaray[i]) == str.indexOf(charaaray[i]))
               return charaaray[i];
      }
  return null;
 }
}
When you run above program, you will get following output:
First non repeated character for String analogy is : n
First non repeated character for String easiest is : a

Monday, 3 August 2015

Find all substrings of a String in java

In this post, we will see java program to find all substrings of a String.
For example: If input is "abb"  then output should be "a", "b","b", "ab", "bb", "abb"
We will use String class's subString method to find all subString

Program:

class SubstringsOfStringMain
{
 public static void main(String args[])
 {
  String str="abbc";
  System.out.println("All substring of abbc are:");
   for (int i = 0; i < str.length(); i++) {
   for (int j = i+1; j <= str.length(); j++) {
         System.out.println(str.substring(i,j));
  
   }
  }
 }
}
When you run above program, you will get following output:
All substring of abbc are:
a
ab
abb
abbc
b
bb
bbc
b
bc
c
Above solution is of o(n^2) time complexity. As number of subString for n character String is n(n+1)/2, so we won't be able to get optimal solution than this.
If you want to find all distinct substrings of String,then use HashSet to remove duplicates.

Sunday, 2 August 2015

Find length of String without using java inbuilt length method

One of the interview question is "How will you find length of String without using inbuilt length method."
There are many ways to find length of String.  Some of them are :
  • Using toCharArray
  • Using StringIndexOutOfBoundsException

Using toCharArray is simplest solution.

Using toCharArray:

Logic:

  • Convert string to char array using toCharArray method
  • Iterate over char array and incrementing length variable. 

Program:

class LenghtOfStringMain{
 
 public static void main(String args[]){
  
  String helloWorld="This is hello world";
  System.out.println("length of helloWorld string :"+getLengthOfStringWithCharArray(helloWorld));
  }

public static int getLengthOfStringWithCharArray(String str)
 {
  int length=0;
  char[] strCharArray=str.toCharArray();
  for(char c:strCharArray)
  {
   length++;
  }
  return length;
 }
When you run above program, you will get following output:
length of helloWorld string :19

Using StringIndexOutOfBoundsException:

You must be wondering how we can use StringIndexOutOfBoundsException to find length of String. Please refer below logic :

Logic:

  • Initialize i with 0 and iterate over String without specifying any condition. So it will be always true.
  • Once value of i will be more than length of String, it will throw StringIndexOutOfBoundsException exception.
  • We will catch the exception and return i after coming out of catch block.

Program:

class LenghtOfStringMain{
 
 public static void main(String args[]){
  
  String helloWorld="This is hello world";
  System.out.println("length of helloWorld string :"+getLengthOfString(helloWorld));
  
  }
  
  public static int getLengthOfString(String str)
  {
    int i=0;
  try{
   for(i=0;;i++)
   {
    str.charAt(i);
   }
   
  }
  catch(Exception e)
  {
   
  }
  return i;
 }
When you run above program, you will get following output:
length of helloWorld string :19

Java program to check Armstrong number

Armstrong number is a 3 digit number which is equal to sum of cube of its digits.
For example: 371,153
In this post,  we will see how to check for Armstrong number in java.
class CheckArmStrongNumberMain
{
 public static void main(String[] args)
 {
   CheckArmStrongNumberMain casnm=new CheckArmStrongNumberMain();
  System.out.println(" Is 153 Armstrong number: "+casnm.isArmStrongNumber(153));
  System.out.println(" Is 234 Armstrong number: "+casnm.isArmStrongNumber(234));
     System.out.println(" Is 371 Armstrong number: "+casnm.isArmStrongNumber(371));
 }
 public boolean isArmStrongNumber(int number)
 {
  int sum=0;
  int originalNumber=number;
  while(number!=0)
  {
   
  int remainder=number%10;
  sum=sum+remainder*remainder*remainder;
  number=number/10;
  }
  if(originalNumber==sum)
  {
   return true;
  }
  return false;
 }
}
When you run above program, you will get following output.
 Is 153 Armstrong number: true
 Is 234 Armstrong number: false
 Is 371 Armstrong number: true


Saturday, 1 August 2015

Java program to reverse a String

In this post,  we will see java program to reverse a String.
There are many ways to do it, some of them are:
  • Using for loop
  • Using recursion
  • Using StringBuffer

Using for loop:

class ReverseStringForMain
{
 public static void main(String[] args)
 {
  String blogName="java2blog";
  String reverse="";
  for(int i=blogName.length()-1;i>=0;i--)
  {
   reverse=reverse+blogName.charAt(i);
  }
  System.out.println("Reverse of java2blog is:"+reverse);
 }
}
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj

Using recursion:

class ReverseStringRecursive
{
 public static void main(String[] args)
 {
  ReverseStringRecursive rsr=new ReverseStringRecursive();
  String blogName="java2blog";
  String reverse=rsr.recursiveReverse(blogName);
  System.out.println("Reverse of java2blog is:"+reverse);
 }
 
 public String recursiveReverse(String orig)
 {
  if(orig.length()==1)
   return orig;
  else
   return orig.charAt(orig.length()-1)+recursiveReverse(orig.substring(0,orig.length()-1));
   
  
 }
}
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj

Using StringBuffer:

class ReverseStringRecursive
{
 public static void main(String[] args)
 {
  ReverseStringRecursive rsr=new ReverseStringRecursive();
  String blogName="java2blog";
  StringBuffer sb=new StringBuffer(blogName);
  System.out.println("Reverse of java2blog is:"+sb.reverse());
 }
}
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj

How to swap two numbers without using temporary variables

In this post, we will see how to swap two numbers without using temporary variables.
There are three ways to do it.
Java program:

package org.arpit.java2blog;
class SwapingTwoNumbers {

    public static void main(String args[]){
        int a = 5;
        int b = 10;

        // First way
        System.out.println("First way");
        System.out.println("Before swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        a = a+b;
        b = a-b;
        a = a-b;
        System.out.println("After swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

 // Second way 
 System.out.println("****************");
        System.out.println("Second way");
        System.out.println("Before swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        a = a*b;
        b = a/b;
        a = a/b;
        
        System.out.println("After swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        //Third way
 System.out.println("****************");
        System.out.println("Third way");
        System.out.println("Before swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);

        a = a^b;
        b = a^b;
        a = a^b;
        System.out.println("After swap:");
        System.out.println("a value: "+a);
        System.out.println("b value: "+b);    }
}
When you run above program, you will get following output:
First way
Before swap:
a value: 5
b value: 10

After swap:
a value: 10
b value: 5

****************

Second way
Before swap:
a value: 10
b value: 5

After swap:
a value: 5
b value: 10

****************

Third way
Before swap:
a value: 5
b value: 10

After swap:
a value: 10
b value: 5

Third way is fastest of all. 

Saturday, 18 July 2015

How to configure Apache Tomcat in eclipse

In this post, we will see how to configure apache tomcat in eclipse.

As per wikipedia, Apache Tomcat, often referred to as Tomcat, is an open-source web server and servlet container developed by the Apache Software Foundation (ASF). Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web server environment for Java code to run in.

We generally deploy our web applications on apache tomcat server. When you download eclipse, you need to configure tomcat in it. We will see step by step configuration of apache tomact in eclipse.

Step 1:

Download apache tomcat server from tomcat 7 download. You need to download it based on your system operating system. (Windows or mac).I have provided link for tomcat 7. If you want different version, you need to download it. You need to extract it after downloading.

Step 2:

Open eclipse ide.
Step 2a: go to Java EE perpective.
Step 2b: Open Servers tab
Step 2c: click on "new server wizard" as shown in the below diagram.



Step 3:

Step 3a: Select "Tomcat v7.0 Server"
Step 3b: click on Next.


Step 4 :

Step 4a: Browse to  tomcat installation directory or if you have downloded zip then browse to extract folder.
Step 4b: click finish.


Step 5:

Step 5a : Double click on servers tab/
Step 5b : If Application deployment takes more than 45 secs then make changes to timeout.
Step 5c: If you want to change default http port.
Step 5d : If you want to take full control over apache tomcat installation.


Step 6:

Right click on the server and click on start.


Then you will see following text in console:


Step 7:

Open http://localhost:8080 and you will see following output:

Bingo!! We are done with the setup of apache tomcat in eclipse

Saturday, 11 July 2015

wait, notify and notifyAll method in java with example

You might have noticed Object class has three final method called wait, notify and notifyAll. These methods are used for inter thread communication.  Java 5 has introduced executor framework which takes care of inter thread communication for you and internally uses wait, notify and notifyAll but you still require basic understanding of these methods and how inter thread communication works in java using wait , notify and notifyAll.

What are wait , notify and notifyAll methods?

wait , notify and notifyAll method are used to allow threads to communicate to each other via accessing common object or in other terms, Object can be considered a medium for inter thread communication via these methods. These methods need to be called from synchronized context,otherwise it will throw java.lang.IllegalMonitorStateException.

Some background on synchronized block :
  • Only one thread can enter at a time in synchronized block
  • A thread required lock on the object to enter in synchronized block.
  • If Thread A want to enter in synchronized block then Thread A has to wait for Thread B to release it.

Lets have some brief understanding of these methods:

wait():

When you call wait method on the object then it tell threads to give up the lock and go to sleep state unless and until some other thread enters in same monitor and calls notify or notifyAll methods on it.

notify():

When you call notify method on the object, it wakes one of thread waiting for that object. So if multiple threads are waiting for an object, it will wake of one of them. Now you must be wondering which one it will wake up. It actually depends on OS implementation.

notifyAll() :

notifyAll will wake up all threads waiting on that object unlike notify which wakes up only one of them.Which one will wake up first depends on thread priority and OS implementation.

Lets understand it with the help of example:

1. Create a class named Book.java:

It is java bean class on which thread will act and call wait and notify method.

package org.arpit.java2blog.thread;

public class Book {
 
 String title;
 boolean isCompleted;
 
 public Book(String title) {
  super();
  this.title = title;
 }
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public boolean isCompleted() {
  return isCompleted;
 }
 public void setCompleted(boolean isCompleted) {
  this.isCompleted = isCompleted;
 }
 
}

2. Create a class named BookReader.java

This thread will wait until other thread call notify method, then after it will complete its processing. It will first take a lock on book object and will be called from synchronized block .So in this example, it will wait for BookWriter to complete the book.

package org.arpit.java2blog.thread;

public class BookReader implements Runnable{
 
 Book book;
 
 public BookReader(Book book) {
  super();
  this.book = book;
 }

 @Override
 public void run() {
  synchronized (book) {
   System.out.println(Thread.currentThread().getName()+" is waiting for the book to be completed: "+book.getTitle());
   try {
    book.wait();
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName()+": Book has been completed now!! you can read it");
  }
 } 

}

3. Create a class named BookWriter.java

This class will notify thread(in case of notify) which is waiting on book object. It will not give away lock as soon as notify is called, it first complete its synchronized block. So in this example, BookWriter will complete the book and notify it to BookReaders.

package org.arpit.java2blog.thread;
public class BookWriter implements Runnable{

 Book book;
 
 public BookWriter(Book book) {
  super();
  this.book = book;
 }

 @Override
 public void run() {
  synchronized (book) {
   System.out.println("Author is Starting book : " +book.getTitle() );
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   book.setCompleted(true);
   System.out.println("Book has been completed now");
   
   book.notify();
   System.out.println("notify one reader");
  
  } 
 }
}

4. Create a class ThreadInterCommunicationMain,java.

This is our main class which will create object of above classes and run it.

package org.arpit.java2blog.thread;

public class ThreadInterCommunicationMain {
 
 public static void main(String args[])
 {
  // Book object on which wait and notify method will be called
  Book book=new Book("The Alchemist");
  BookReader johnReader=new BookReader(book);
  BookReader arpitReader=new BookReader(book);
  
  // BookReader threads which will wait for completion of book
  Thread johnThread=new Thread(johnReader,"John");
  Thread arpitThread=new Thread(arpitReader,"Arpit");
  
  arpitThread.start();
  johnThread.start();
  
  // To ensure both readers started waiting for the book
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   
   e.printStackTrace();
  }
  // BookWriter thread which will notify once book get completed
  BookWriter bookWriter=new BookWriter(book);
  Thread bookWriterThread=new Thread(bookWriter);
  bookWriterThread.start();
  
 }
 
}


In case of notify():

When you run above program, you will get following outputs:
Arpit is waiting for the book to be completed: The Alchemist
John is waiting for the book to be completed: The Alchemist
Author is Starting book : The Alchemist
Book has been completed now
notify one reader
Arpit: Book has been completed now!! you can read it

So here,two BookReader threads(arpit and john) are waiting for book to be completed,so they called book.wait(). Once BookWriter completes it book, it called book.notify() and arpit thread gets up and completes its processing.

In case of notifyAll() :

Lets change BookWriter class to call book.notifyAll().
package org.arpit.java2blog.thread;

public class BookWriter implements Runnable{

 Book book;
 
 public BookWriter(Book book) {
  super();
  this.book = book;
 }

 @Override
 public void run() {
  synchronized (book) {
   System.out.println("Author is Starting book : " +book.getTitle() );
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   book.setCompleted(true);
   System.out.println("Book has been completed now");
   
   book.notifyAll();
   System.out.println("notify readers");
  
  }
 }

}

When you run above program, you will get following output:

Arpit is waiting for the book to be completed: The Alchemist
John is waiting for the book to be completed: The Alchemist
Author is Starting book : The Alchemist
Book has been completed now
notify readers
John: Book has been completed now!! you can read it
Arpit: Book has been completed now!! you can read it

In case of notifyAll(), it notifies all threads waiting on that object.