Saturday, 5 September 2015

How to create dynamic web project using maven in eclipse

In this post, we will see how to create dynamic web project using maven in eclipse.

I am using following tools for this post.

  • eclipse-jee-mars-R-macosx-cocoa-x86_64
  • Apache tomcat 8
  • m2eclipse plugin
  • jdk 1.7

Steps for creating dynamic web project using maven in eclipse.


1) Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

2) goto new -> project-> Maven Project and click on next

3) You will see below screen , again click on next


4) We need to select type of archetype here.As we are creating web app here, please put following text in filter : maven-archetype-webapp


5) We need to put group id and artifact id here.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as mavenWebApp

Version : Version is used for version control for artifact id. If you distribute this project, you may incrementally create different version of it.

6) You project structure should look something like below image.

7) When I have followed above steps, I was getting below error.
"The superclass "javax.servlet.http.HttpServlet" was found in java build path".



You can resolve this error using two ways.

1) you can add following dependency to pom.xml

 javax.servlet
 javax.servlet-api
 3.1.0

2) you can set target run time as Apache tomcat .
right click on project -> properties -> target runtimes

8) It 's time to do maven build.
Right click on project -> Run as -> Maven build

9)  Provide goals as given below and click on run




10) When you run maven build, you will see below screen
11) Deploy this application to tomcat server and run it.
If you don't have tomcat server configured in eclipse, follow these steps.
Right click on project -> run as -> run on server -> choose tomcat.

12)
When you run application, you will get following output:

Bingo !! we are done with creating dynamic web project using maven in eclipse.

Please comment if you are facing any issue with this.


How to install maven plugin(m2eclipse) in eclipse

Apache maven is a build automation tool used for java projects. It is widely used for building java projects now a days.

In this post, we will see how to install m2eclipse maven plugin for eclipse.

Steps for installing m2eclipse plugin in eclipse:


1) goto Help->Install new software.

 2) Click on add to add m2eclipse site.


3)  Fill Name and location as below
Name: m2eclipse
Location : http://download.eclipse.org/technology/m2e/releases


4) Select plugin which needs to be install for m2eclipse


5) select "I Agree to the terms of license agreement"

6) It will start installing m2eclipse plugin.


7) click on yes to restart eclipse for changes to reflect.




Bingo!! we are done with m2eclipse plugin installation in eclipse.
If you want to check maven plugin is installed or not. Follow below steps:
  • Go to Window --> Preferences 
  • check whether Maven is enlisted at left panel

Wednesday, 2 September 2015

Java Enum

Java Enum is special data type which represents list of constants values. It is a special type of java class.  It can contain constant, methods and constructors  etc.

Lets see example to understand better

Let's say we get three types of issues which require different SLA to get it fixed. Usually they are level 1,level 2 and level 3 severity. So it will represent in term of enums as follows.

Public enum Severity

(Level_1,
Level_2,
Level_3
)
Here
Serverity  level= Severity. Level_1;
level variable is type of Serverity which is enum type. You can assign only 3 values (Level_1,Level_2 and Level_3) to it.If you assign any other value, it will give you compile time error.Enum in java are type safe and has its own name space

Now you must be wondering why you can't use class over here,  why you require special data type called enum.
Lets understand it with the help of example:
Create enum as SeverityEnum.java
package org.arpit.java2blog.corejava;

public enum SeverityEnum
{
LEVEL_1,
LEVEL_2,
LEVEL_3;
}

Create class as SeverityClass.java
package org.arpit.java2blog.corejava;

public class SeverityClass {
public static final String LEVEL_1="LEVEL_1";
public static final String LEVEL_2="LEVEL_2";
public static final String LEVEL_3="LEVEL_3";

}
Create issue.java. It will use above enum and class.
package org.arpit.java2blog.corejava;

public class Issue {

 String issueName;
 
 public Issue(String issueName) {
  super();
  this.issueName = issueName;
 }
 public String getIssueName() {
  return issueName;
 }
 public void setIssueName(String issueName) {
  this.issueName = issueName;
 }

 
 public void resolveIssueEnum(SeverityEnum level)
 {
  System.out.println("Resolving "+issueName+ " of "+level.name());
 }
 
 public void resolveIssueClass(String level)
 {
  System.out.println("Resolving "+issueName+ " of "+level);
 }
 
}

Create EnumMain.java .
package org.arpit.java2blog.corejava;

public class EnumMain {

 public static void main(String args[])
 {
  Issue a=new Issue("Server is down");
  Issue b=new Issue("UI is not formatted properly");
 
  
  System.out.println("Resolving issues:");
  System.out.println("*****************");

  a.resolveIssueClass(SeverityClass.LEVEL_2);

  // You are able to pass "LEVEL_5" also here, but LEVEL_5 is not defined as Severity at all
  // So this is considered to be invalid value, but you still can pass it if you use class
  b.resolveIssueClass("LEVEL_5");

  // b.resolveIssueEnum("LEVEL_5");  // Compilation error
  
  // You can pass only fixed values with this which is our requirement here
  // So enum ensures type safety
  a.resolveIssueEnum(SeverityEnum.LEVEL_2);
 }
}

When you run above program, you will get following output:
Resolving issues:
*****************
Resolving Server is down of LEVEL_2
Resolving UI is not formatted properly of LEVEL_5
Resolving Server is down of LEVEL_2
The main  reason for it is type safety . You won't be able to put any other value with enums but if you use class instead of enum, it may be more error prone as you may assign invalid value to it.

Lets understand more about Enum.
package org.arpit.java2blog.corejava;

public class Issue {

 String issueName;
 
 public Issue(String issueName) {
  super();
  this.issueName = issueName;
 }
 public String getIssueName() {
  return issueName;
 }
 public void setIssueName(String issueName) {
  this.issueName = issueName;
 }


 public static void main(String[] args)
 {
        Severity level=Severity.LEVEL_2; 
        System.out.println(level.name());
 }
 
}

We can see structure of enum using a debug point.
put debug point at line 21 and right click on project->debug as->java application. Program will stop execution at line 21 then right click on level then select watch.You will be able to see structure as below.


So it has many methods and two of them are :
name() : it returns you enum constant. For above enum level, its value is LEVEL_2.
ordinal() : It returns you position in enum declaration. This method is not generally used by programmers, it is used mostly in enum based data structures such as EnumSet.

Constructor:
protected Enum(String name, int ordinal)
This is only constructor present by default in enum. This can not be called by program. This is called internally when you declare the enum.

I am summarising important points on enum based on their nature.

Constructor:

  • Enum can have constructors and can be overloaded. 
  • Enum constructor can never be invoked directly, it will be implicitly called when enum is initialized. 
  • You also can provide value to enum constants but you need to create member variable and constructor for that

Methods:

  • You can declare methods in enum. 
  • You can also declare abstract methods in enum and while declaring constants,  you need to override it. 



Declaration :

  • You can not create instance of enum with new operation as it does not support public constructor and it make sense too as you want fixed values in Enum. If new operator would have been allowed, then you might able to add more values.
  • // compilation error
    Serverity level=new Severity();

  • Enum constants are implicitly static and final.  You can not change its value after creation. 
  • You can not extend any other class to enums as enum implicitly extends Enum class and java does not allow multiple inheritance.
  • Enum can be defined inside or outside of a class but can not be defined in method. 
  • Enum declared outside class can not be declared as static,  abstract,  private,  protected or final. 
  • Enum can implement an interface.
  •  

  • Semi colon declared at the end of enum is optional. 

  • Comparison and Switch case:

    • You can compare values of enum using '=='  operator. 
    • You can use enum in switch case too. 

    Example:

    create Enum class named Severity.java
    package org.arpit.java2blog.corejava;
    
    public enum Severity {
    
     LEVEL_1(1) {
      @Override
      public String getDescription() {
       return "SLA: 2 hours";
      }
     },
     LEVEL_2(2) {
      @Override
      public String getDescription() {
       return "SLA: 8 hours";
      }
     },
     LEVEL_3(3) {
      @Override
      public String getDescription() {
       return "SLA: 1 day";
      }
     };
     
     int level;
     Severity(int level)
     {
      this.level=level;
     }
     
     public int getLevel()
     {
      return level;
     }
     
     public abstract String getDescription();
    }
    
    Create issue.java which will used above enum class.
    package org.arpit.java2blog.corejava;
    
    public class Issue {
    
     String issueName;
     Severity issueLevel;
    
     public Issue(String issueName,Severity level) {
      super();
      this.issueName = issueName;
      this.issueLevel=level;
     }
     public String getIssueName() {
      return issueName;
     }
     public void setIssueName(String issueName) {
      this.issueName = issueName;
     }
    
    
    
     public Severity getIssueLevel() {
      return issueLevel;
     }
     public void setIssueLevel(Severity level) {
      this.issueLevel = level;
     }
     public void resolveIssueUsingSwitch()
     {
      
      switch(issueLevel)
      {
      case LEVEL_1:
       System.out.println("Resolving level 1 issue");
       break;
      case LEVEL_2:
       System.out.println("Resolving level 2 issue");
       break;
      case LEVEL_3:
       System.out.println("Resolving level 3 issue");
       break;
      }
      
     }
    
     public void resolveIssueUsingIfElse()
     {
      if(issueLevel==Severity.LEVEL_1)
      {
       System.out.println("Resolving level 1 issue");
      }
      else if(issueLevel==Severity.LEVEL_2)
      {
       System.out.println("Resolving level 2 issue");
      }
      else if(issueLevel==Severity.LEVEL_3)
      {
       System.out.println("Resolving level 3 issue");
      }
     }
    
    
    }
    
    create enumMain.java to run the code:
    package org.arpit.java2blog.corejava;
    
    public class EnumMain {
    
     public static void main(String args[])
     {
      Issue a=new Issue("Server is down",Severity.LEVEL_1);
      Issue b=new Issue("UI is not formatted properly",Severity.LEVEL_3);
     
      System.out.println("*****************");
      System.out.println("Resolving issues:");
      
      // Using if else
      a.resolveIssueUsingIfElse();
    
      // Using switch case
      b.resolveIssueUsingSwitch();
      
      
      System.out.println("*****************");
      System.out.println("valueOf method example");
      // converting string to Enum using valueOf Method 
      Severity level2=Enum.valueOf(Severity.class,"LEVEL_2");
      System.out.println(level2.name()+" -"+level2.getDescription());
      
      // values for getting all enum values
      System.out.println("*****************");
      System.out.println("values method example");
      for (Severity level:Severity.values()) {
       System.out.println(level.name()+" - "+level.getDescription());
      }
      
     }
    }
    
    When you run above code, you will get following output:
    *****************
    Resolving issues:
    Resolving level 1 issue
    Resolving level 3 issue
    *****************
    valueOf method example
    LEVEL_2 -SLA: 8 hours
    *****************
    values method example
    LEVEL_1 - SLA: 2 hours
    LEVEL_2 - SLA: 8 hours
    LEVEL_3 - SLA: 1 day
    
    


    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