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.

Wednesday, 8 July 2015

Binary search in java

In this post,we will see how to perform binary search in java using divide and conquer method.When you want to find a value in sorted array, we use binary search and we will also see how to compute complexity of binary search.
Lets say we have an sorted array.

Algorithm:

  1. Initialize first=0 and last=sortedArray.length-1
  2. compute mid and compare  sortedArray[mid]  with element to be searched
  3. If element to be searched is less than sortedArray[mid] then element lies in left part of the mid, so last=mid
  4. if element to be searched is greater than sortedArray[mid] then element lies in right part of the mid, so first=mid+1.
  5. if element to be searched is equal to sortedArray[mid] , then return index
  6. Repeat above process until first is less than last.

  
 public  static int binarySearch(int[] sortedArray, int elementToBeSearched) {
  int first = 0;
        int last = sortedArray.length - 1;
       
      while (first < last) {
       
          int mid = (first + last) / 2;  // Compute mid point.
         
          if (elementToBeSearched < sortedArray[mid]) {
           last = mid;     // repeat search in first half.
          } else if (elementToBeSearched > sortedArray[mid]) {
              first = mid + 1;  // Repeat sortedArray in last half.
          } else {
              return mid;     // Found it. return position
          }
      }
     
      return -1;    // Failed to find element
  }

Example:
Now lets assume our sorted array is:
  
int[] sortedArray={12,56,74,96,112,114,123,567};
and we want to search for 74 in above array. Below diagram will explain how binary search will work here.

When you observe closely, in each of the iteration you are cutting scope of array to the half. In every iteration, we are overriding value of first or last depending on sortedArray[mid].
So for
0th iteration : n
1th iteration: n/2
2nd iteration n/4
3rd iteration n/8.
Generalizing above equation:
For ith iteration : n/2i

So iteration will end , when we have 1 element left i.e. for any i, which will be our last iteration:
1=n/2i;
2i=n;
after taking log
i= log(n);
so it concludes that number of iteration requires to do binary search is log(n) so complexity of binary search is log(n)
It makes sense as in our example, we have n as 8 . It took 3 iterations(8->4->2->1) and 3 is log(8).
Code:

 
package org.arpit.java2blog.thread;

public class BinarySerarchMain {

 
 public  static int binarySearch(int[] sortedArray, int elementToBeSearched) {
  int first = 0;
        int last = sortedArray.length - 1;
       
      while (first < last) {
       
          int mid = (first + last) / 2;  // Compute mid point.
         
          if (elementToBeSearched < sortedArray[mid]) {
           last = mid;     // repeat search in first half.
          } else if (elementToBeSearched > sortedArray[mid]) {
              first = mid + 1;  // Repeat sortedArray in last half.
          } else {
              return mid;     // Found it. return position
          }
      }
     
      return -1;    // Failed to find element
  }
 
 public static void main(String[] args)
 {
    
  int[] sortedArray={12,56,74,96,112,114,123,567};
  int indexOfElementToBeSearched=binarySearch(sortedArray,74);
  System.out.println("Index of 74 in array is: " +indexOfElementToBeSearched);
  
  int indexOfElementToBeSearchedNotFound=binarySearch(sortedArray,7);
  System.out.println("Index of 7 in array is: " +indexOfElementToBeSearchedNotFound);
 }
 
}
when you run above program, you will get below output:
  
Index of 74 in array is: 2
Index of 7 in array is: -1

Sunday, 28 June 2015

Java bloggers meet to celebrate 20th birthday of java, hosted by oracle

Oracle has invited java bloggers at Hyderabad campus on 13th June 2015 and we celebrated Java 's 20th birthday. Few days back, I got an invitation mail for this event and I was more than happy to join them.

It was really pleasure to meet other java bloggers and interact with them. It started with warm welcome by Ms. Vandana Shenoy( Directory Corporate Communications, Oracle) and she introduced the presenters.First speaker was Sanket Atal ( Group Vice President, India R&D, Oracle) and he gave presentation titled “Java – 20 years of Innovation”. It started with history of java to promising future of java. If you want to go through 20 year of the java, you can read more at oracle timeline
There were some quiz questions in between and it was pretty cool.


After that, there was a talk from java champion, Hashad Oak. He raised few very good points such as
  • Warm welcome nature of java.
  • Is syntax really important?
  • Java bloggers have a great responsibility for carrying a warm culture to the future developers
  • Promising future of java.

It was followed speech by Mr. Debraj Dutta, a winner of Oracle IOT challenge. He presented his "Bot so" robot which was really great. It uses raspberry pi and It actually takes command from twitter, then capture images and upload to google drive and share same at twitter privately.



After that, we cut yummy java 20 cake and celebrated java's 20th birthday.




In the end, I would like to thank Oracle for inviting to this event and I look forward more such events from Oracle. Below is the group picture of the event











Thursday, 25 June 2015

How to iterate over Map or HashMap in java

In this post, we will see how  can we iterate a map in java. There are four ways of iterating over a map, HashMap or TreeMap.
  1. Using keyset() and for each loop(Java 5)
  2. Using keyset() and java Iterator
  3. Using EntrySet() and for each loop(Java 5)
  4. Using EntrySet() and java Iterator
if you remove elements while iterating , then 1st and 3rd option  will throw java.util.ConcurrentModificationException.
If you understand internal working of HashMap, then it may be easier for you to iterate an HashMap

Lets take an example:
1. IterateListMain.java 
package org.arpit.java2blog;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class IterateMapMain {

 public static void main(String args[])
 {
  // HashMap with Country as key and capital as value
  HashMap<String,String> countryCapitalMap=new HashMap<String,String>();
  countryCapitalMap.put("India","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");

  // Iterating Using keySet() and for each loop
  System.out.println("Iterating Using keySet() and for each loop");
  for (String countryKey:countryCapitalMap.keySet()) {
   System.out.println("Country:"+ countryKey +" and  Capital:"+countryCapitalMap.get(countryKey));

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

  // Iterating Using keySet() and java iterator
  System.out.println("Iterating Using keySet() and java Iterator");
  Iterator<String> countryKeySetIterator=countryCapitalMap.keySet().iterator();
  while(countryKeySetIterator.hasNext()){
   String countryKey=countryKeySetIterator.next();
   System.out.println("Country:"+ countryKey +" and Capital:"+countryCapitalMap.get(countryKey));

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

  // Iterating Using entrySet() and for each loop
  System.out.println("Iterating Using entrySet() and for each loop");
  for (Entry<String,String> entry:countryCapitalMap.entrySet()) {
   System.out.println("Country:"+ entry.getKey() +" and  Capital:"+entry.getValue());

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

  // Iterating Using entrySet() and java iterator
  System.out.println("Iterating Using entrySet() and and java Iterator");
  Iterator<Entry<String,String>> entryIterator=countryCapitalMap.entrySet().iterator();
  while(entryIterator.hasNext())
  {
   Entry<String,String> entry=entryIterator.next();
   System.out.println("Country:"+ entry.getKey() +" and  Capital:"+entry.getValue());

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

 }

}

Run it and you will get following output:
Iterating Using keySet() and for each loop
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------
Iterating Using keySet() and java Iterator
Country:France and Capital:Paris
Country:Russia and Capital:Moscow
Country:Japan and Capital:Tokyo
Country:India and Capital:Delhi
-----------------------------
Iterating Using entrySet() and for each loop
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------
Iterating Using entrySet() and and java Iterator
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------

Wednesday, 24 June 2015

How to iterate a list in java

In this post, we will see how  can we iterate a list in java. There are four ways of iterating over a list.
  • For loop
  • For each loop(Java 5)
  • While loop
  • Iterator
Below example will help you to understand, how to iterate list in java. I am taking custom object list to understand better

1. Country.java 
package org.arpit.java2blog;
public class Country {

 String name;
 long population;
 
 public Country(String name, long population) {
  super();
  this.name = name;
  this.population = population;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 } 
  
}
2. IterateListMain.java 
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.Iterator;

public class IterateListMain {
 /**
     * @author Arpit Mandliya
     */
    public static void main(String[] args) {
          
        Country india=new Country("India",1000);
        Country japan=new Country("Japan",10000);
          
        Country france=new Country("France",2000);
        Country russia=new Country("Russia",20000);
        
        // We are going to iterate on this list and will print 
        //name of the country 
        ArrayList<Country> countryLists=new ArrayList<Country>();
        countryLists.add(india);
        countryLists.add(japan);
        countryLists.add(france);
        countryLists.add(russia);
        
        // For loop
        System.out.println("Iterating using for loop : ");
        for (int i = 0; i < countryLists.size(); i++) {
   Country countryObj=countryLists.get(i);
   System.out.println(countryObj.getName());
  }
        System.out.println("-----------------------------");
       
       // For each loop
        System.out.println("Iterating using for each loop : ");
        for (Country countryObj:countryLists) {
   System.out.println(countryObj.getName());
  }
        System.out.println("-----------------------------");
       
       // While loop
        System.out.println("Iterating using while loop : ");
        int i=0;
        while(i<countryLists.size())
        {
         Country countryObj=countryLists.get(i);
   System.out.println(countryObj.getName());
   i++;
        }
        
        System.out.println("-----------------------------");
      
        // Iterator
        System.out.println("Iterating using iterator : ");
        Iterator<Country> iteratorCountryLists= countryLists.iterator();
        while(iteratorCountryLists.hasNext())
        {
         System.out.println(iteratorCountryLists.next().getName());
        }
        
    }
}
Run it and you will get following output:
Iterating using for loop : 
India
Japan
France
Russia
-----------------------------
Iterating using for each loop : 
India
Japan
France
Russia
-----------------------------
Iterating using while loop : 
India
Japan
France
Russia
-----------------------------
Iterating using iterator : 
India
Japan
France
Russia


Wednesday, 17 June 2015

Difference between ArrayList and LinkedList in java


One of the common interview question is "What is difference between ArrayList and LinkedList".Before we actually see differences,let me give you brief introduction of both.

ArrayList

  • ArrayList is implementation of list interface.
  • ArrayList is not synchonized(so not thread safe)
  • ArrayList is implemented using array as internal data structure.It can be dynamically resized .

LinkedList

  • LinkedList is implementation of list and deque interface.
  • LinkedList is not synchronized
  • LinkedList is implemented using doubly linked list as internal data structure.

ArrayList vs LinkedList:

Parameter
ArrayList
LinkedList
Internal data structure
It uses dynamic array to store elements internally
It uses doubly Linked List to store elements internally
Manipulation
If  We need to insert or delete element in ArrayList, it may take O(n), as it internally uses array and we may have to shift elements in case of insertion or deletion
If  We need to insert or delete element in LinkedList, it will take O(1), as it internally uses doubly LinkedList 
Search
Search is faster in ArrayList as uses array internally which is index based. So here time complexity is O(1)
Search is slower in LinkedList as uses doubly Linked List internally So here time complexity is O(n)
Interfaces
ArrayList implements List interface only, So it can be used as List only
LinkedList implements List,Deque interfaces, so it can be used as List,Stack or Queue

When to use ArrayList or LinkedList?

It actually depends on our need.

  • If we have more insertion or deletion then we should use LinkedList.
  • If we have less insertion or deletion and more search operations then we should use ArrayList.


Tuesday, 16 June 2015

Java Thread Join Example

Thread class's join method can be used to stop current execution of thread until thread it joins, completes its task. So basically , it waits for the thread on which join method is getting called, to die.

There are three variant of join method:

public final void join() throws InterruptedException :
Thread on which join method is getting called to die.

public final void join(long millis) throws InterruptedException:
This method when called on the thread, it waits for either of following:
  • Thread on which join method is getting called, to die. 
  • Specified milliseconds
public final void join(long millis,int nanos) throws InterruptedException:
This method when called on the thread, it waits for either of following:
  • Thread on which join method is getting called, to die. 
  • Specified milliseconds + nano seconds

Example:

Lets take simple example:
package org.arpit.java2blog.thread;

public class MyRunnable implements Runnable{

 public void run()
 {
  try {
   System.out.println(Thread.currentThread().getName()+" Start");
   // thread sleeps for 4 secs
   Thread.sleep(4000);
   System.out.println(Thread.currentThread().getName()+" end");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 } 
}
Create ThreadExampleMain.java
package org.arpit.java2blog.thread;

public class ThreadExampleMain {
 
 public static void main(String args[])
 {
               
  System.out.println("Main thread execution starts");
  MyRunnable mr=new MyRunnable();
  
  Thread t1=new Thread(mr,"Thread 1");
  Thread t2=new Thread(mr,"Thread 2");
  Thread t3=new Thread(mr,"Thread 3");
  
  t1.start();
  // lets waits for  t1 to die
  try {
   t1.join();
  } catch (InterruptedException e) {
   
   e.printStackTrace();
  }
 
 
  t2.start();
  try {
 // lets waits for 1 sec or t2 to die which ever occurs first 
  t2.join(1000);
   
  } catch (InterruptedException e1) {
   
   e1.printStackTrace();
  }
  t3.start() ;
  
  // complete all threads before completing main thread
  try {
   t2.join();
   t3.join();
   
  } catch (InterruptedException e1) {
   
   e1.printStackTrace();
  }
  System.out.println("Main thread execution ends");   
 }
}

When you run above program, you will get following output.
Main thread execution starts
Thread 1 Start
Thread 1 end
Thread 2 Start
Thread 3 Start
Thread 2 end
Thread 3 end
Main thread execution ends

Lets analysis output now.
  1. Main thread execution starts
  2. Thread 1 starts(Thread 1 start) and as we have put t1.join() , it will wait for t1 to die(Thread 1 end). 
  3. Thread 2 starts(Thread 2 start) and waits for either 1 seconds or die but as we have put sleep for 4 seconds in run method, it will not die in 1 second. so main thread resumes and Thread 3 starts(Thread 3 start)
  4. As we have put t2.join() and t3.join(). These 2 threads will get completed before exiting main thread.So Thread 2 will end(Thread 2 end ) and then thread 3 will end(Thread 3 end).
  5. Main thread execution ends.