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. You can also go through top 50 java interview questions for interview questions.

Collections:

    Collections interview questions and answers How HashMap internally works in java How to iterate over HashMap in java How to Sort ArrayList based on attributes using Comparator in java How to sort ArrayList based on attributes using Comparable in java How to remove duplicates from list in java How to iterate over ArrayList in java

LinkedList :

    How to reverse a linked list in java How to reverse a linked list in pairs How to find middle element of linked list in java How to detect a loop in linked list in java Find start node of loop in linkedlist How to find nth element from end of linked list How to check if linked list is palindrome in java Add two numbers represented by linked list in java

Binary tree :

    Binary tree in java Binary tree preorder traversal Binary tree postorder traversal Binary tree inorder traversal Binary tree level order traversal Binary tree spiral order traversal Binary tree reverse level order traversal Binary tree boundary traversal Print leaf nodes of binary tree Count leaf nodes in binary tree get maximum element in binary tree Print all paths from root to leaf in binary tree Print vertical sum of binary tree in java Get level of node in binary tree in java Lowest common ancestor(LCA) in binary tree in java

Array :

    Find missing number in an array search an element in a sorted and rotated array in java Find second largest number in array Find number occurring odd number of times in array Minimum numbers of platforms required for railway station in java Find pair whose sum is closest to zero in array in java Find pair whose sum is closest to X in array in java Find all pairs of elements whose sum is equal to given number Search element in row wise and column wise sorted matrix Stock buy and sell to maximize profit.

Sorting :

    How to implement merge sort in java How to implement bubble sort in java How to implement insertion sort in java

String :

    How to reverse String in java How to check if two Strings are angrams Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String Why String is immutable in java Find duplicate characters in String

Number :

    How to swap two numbers without using temporary variables Java program to check prime number Find prime factors of number in java Java Program to check armstrong number Fibonacci series program in java Java Program to check Palindrome Number Java Program to to find gcd and lcm of two numbers

Algorithm :

    How to calculate complexity of algorithm Binary Search in java

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.
Java timer example

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

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.

CountDownLatch in java


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.


Please go through  top 50 core java interview questions for more interview questions.

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

Please go through java interview programs for more such programs.

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

Please go through java interview programs for more such programs.

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

Please go through Common java interview Programs for more such programs.

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.

Please go through Frequently asked java interview Programs for more such programs.

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:

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

Please go through java interview programs for more such programs and core java interview questions for more interview questions.

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

Please go through Frequently asked java interview Programs for more such programs.

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

Please go through java interview programs for more such programs.

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.
Please go through Interview programs in java  for more such programs.
 

Java tutorial for beginners Copyright © 2012