Saturday 25 August 2012

When should I use an interface instead of an abstract class?


Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.

Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts

Say a real estate builder is constructing an apartment with many flats.All the rooms in the flats have the same design,except the bedroom. The bedroom design is left for the ppl who would own the flats i.e; the bedRooms can be of different designs for different flats. 

I can achieve this through an abstract class like below:



public abstract class Flat
{
 //some properties


 public void livingRoom(){
    //some code
 }
 
 public void kitchen(){
    //some code
 }

 public abstract void bedRoom();

}

An implementation class would be as follows:
public class Flat101 extends Flat
{
        public void bedRoom() {
            System.out.println("This flat has a customized bedroom");
       }  

}

Suppose real estate builder is allowing you to customize all the rooms according to
your taste then you can go with interface.


interface Flat {
 // some properties

 public void livingRoom();

 public void kitchen();

 public void bedRoom();

}

public class Flat101 implements Flat {

 @Override
 public void livingRoom() {
  System.out.println("This flat has a customized living room");

 }

 @Override
 public void kitchen() {
  System.out.println("This flat has a customized kitchen");

 }

 @Override
 public void bedRoom() {
  System.out.println("This flat has a customized bedroom");

 }

}


One more thing is that interface supports multiple inheritance in Java i.e. you can implement more than one interface at a time or you can extend one class and implement one or more interfaces at the same time.

Interfaces can also be used as marker interface, interface with no methods in it.For example java.lang.Cloneable and java.io.Serializable.

Friday 24 August 2012

Compare two StringBuffer objects in Java

We can't use the equals method of the StringBuffer class for comparing two StringBuffer objects.The StringBuffer class equals method returns true only if both the comparing objects pointing to the same memory location.i.e. here comparing the memory address of the StringBuffer objects, not their contents.

Hence we have to convert the StringBuffer objects to String and use the String class equals method for comparing StringBuffer objects.String class equals method returns true if both the String objects occupies the same content.

See the example given below:


public class CompareStringBuffer {

	public static void main(String[] args) {

		StringBuffer sb1 = new StringBuffer("Java");
		StringBuffer sb2 = new StringBuffer("Java");

		System.out.println("sb1.equals(sb2)=" + sb1.equals(sb2));
		System.out.println("Is sb1 equals sb2?="
				+ sb1.toString().equals(sb2.toString()));

	}
}


The output is:


sb1.equals(sb2)=false
Is sb1 equals sb2?=true

New Java 7 Features: Using String in the Switch Statement

In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:


public class StringSwitchDemo {

 public static int getMonthNumber(String month) {

  int monthNumber = 0;

  if (month == null) {
   return monthNumber;
  }

  switch (month.toLowerCase()) {
  case "january":
   monthNumber = 1;
   break;
  case "february":
   monthNumber = 2;
   break;
  case "march":
   monthNumber = 3;
   break;
  case "april":
   monthNumber = 4;
   break;
  case "may":
   monthNumber = 5;
   break;
  case "june":
   monthNumber = 6;
   break;
  case "july":
   monthNumber = 7;
   break;
  case "august":
   monthNumber = 8;
   break;
  case "september":
   monthNumber = 9;
   break;
  case "october":
   monthNumber = 10;
   break;
  case "november":
   monthNumber = 11;
   break;
  case "december":
   monthNumber = 12;
   break;
  default:
   monthNumber = 0;
   break;
  }

  return monthNumber;
 }

 public static void main(String[] args) {

  String month = "August";

  int returnedMonthNumber = StringSwitchDemo.getMonthNumber(month);
  System.out.println("The month number is:");
  if (returnedMonthNumber == 0) {
   System.out.println("Invalid month");
  } else {
   System.out.println(returnedMonthNumber);
  }
 }
}


The output is:


The month number is:
8

Sunday 12 August 2012

Comparing String with StringBuilder in Java


This example shows how to compare String object with a StringBuilder object using equals and contentEquals  methods of the String class.



public class ComapreStringWithStringBuilder {
 public static void main(String args[]) {

  String str = "Java";
  StringBuilder strBuild = new StringBuilder(str);

  /**
   * String.equals method can be used only for comparing
   * two Strings,so first convert StringBuilder to String
   * using toString method and then compare.
   **/
  if (str.equals(strBuild.toString())) {
   System.out.println("String and StringBuilder contains" +
     " same data");
  }

  /**
   * boolean contentEquals(CharSequence cs) Compares this
   * string to the specified CharSequence. The result is
   * true if and only if this String represents the same
   * sequence of char values as the specified
   * sequence.
   **/

  if (str.contentEquals(strBuild)) {
   System.out.println("String and StringBuilder contains" +
     " same data");
  }
 }
}


The output is:


String and StringBuilder contains same data
String and StringBuilder contains same data

Comparing String with StringBuffer in Java


This example shows how to compare String object with a StringBuffer object using equals and contentEquals  methods of the String class.


public class ComapreStringWithStringBuffer {
 public static void main(String args[]) {

  String str = "Java";
  StringBuffer strBuff = new StringBuffer(str);

  /**
   * String.equals method can be used only for comparing two
   * Strings,so first convert StringBuffer to String using
   * toString method and then compare.
   **/
  if (str.equals(strBuff.toString())) {
   System.out.println("String and StringBuffer contains" +
     " same data");
  }

  /**
   * boolean contentEquals(StringBuffer sb) - Compares this
   * string to the specified StringBuffer. The result is true
   * if and only if this String represents the same sequence
   * of characters as the specified StringBuffer.
   **/
  if (str.contentEquals(strBuff)) {
   System.out.println("String and StringBuffer contains" +
     " same data");
  }
 }
}


The output is:


String and StringBuffer contains same data
String and StringBuffer contains same data

Difference between == , equals and equalsIgnoreCase


A lot of Java new programmers get confused when comparing String with another. With so many different ways to do comparison on String, every of them seems to be the same. But the fact is, they are NOT! Having to know the differences on these will help to create a better , more efficient application, thus getting required results.

Here, we will compare ways and differences between == , equals and equalsIgnoreCase.


== Operator 



This operator compares two object references to see whether they refer to the same instance. Consider x and y, two String object references, then x==y comparing the memory addresses of the objects referenced by x and y (i.e. not the data of the objects).

String s1 = new String(“Java”);

String s2 = new String(“Java”);

System.out.println(s1==s2); ——> returns false

String s3 = s1;

System.out.println(s3==s1); ——-> returns true


boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.


String f1 = “mouse”;

String f2 = “mouse”;

String f3 = “MOUSE”;

System.out.println(f1.equals(f2)); ——> returns true

System.out.println(f1.equals(f3)); ——> returns false


boolean equalsIgnoreCase(String anotherString)




Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.

String s1 = new String(“Java”);

String s2 = new String(“JAVA”);

System.out.println(s1.equalsIgnoneCase(s2)); ——> returns true

Java String to byte Array Example


This Java String to byte Array example shows how to convert Java String object to byte array.



public class JavaStringToByteArray {
 public static void main(String args[]) {

  // Java String object
  String str = "Hello World";

  /**
   * To convert Java String to byte array, use
   * byte[] getBytes() method of String class.
   **/

  byte[] bytes = str.getBytes();
 }
}

Java Substring Example


This Java substring example describes how substring method of java String class can be used to get substring of the given java string object.

Java String class defines two methods to get substring from the given Java String object.


String substring(int beginIndex)


Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.This method throws IndexOutOfBoundsException  if beginIndex is negative or larger than the length of this String object.


String substring(int beginIndex,int endIndex)
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.The method throws 
IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
 
See the example given below:








public class JavaSubstringExample {

 public static void main(String args[]) {

  String name = "Hello World";

  /**
   * This will print the substring starting 
   * from index 6
   **/
  System.out.println(name.substring(6));

  /**
   * This will print the substring starting from index
   * 0 upto 4 not 5.IMPORTANT : Here startIndex is inclusive
   * while endIndex is exclusive.
   **/
  System.out.println(name.substring(0, 5));

 }

}


The output is:


World
Hello

Saturday 11 August 2012

Java String to Upper Case example


This Java String to Upper Case example shows how to change the string to upper case using toUpperCase method of String class.



public class StringToUpperCaseExample {

 public static void main(String[] args) {

  String str = "string touppercase example";

  /*
   * To change the case of string to upper case use,
   * public String toUpperCase() method of String class.
   */

  String strUpper = str.toUpperCase();

  System.out.println("Original String: " + str);
  System.out.println("String changed to upper case: "+strUpper);
 }
}


The output is:


Original String: string touppercase example
String changed to upper case: STRING TOUPPERCASE EXAMPLE

Java String to Lower Case example


This Java String to Lower Case example shows how to change the string to lower case using toLowerCase method of String class.


public class StringToLowerCaseExample {

 public static void main(String[] args) {

  String str = "STRING TOLOWERCASE EXAMPLE";

  /**
   * To change the case of string to lower case use,
   * public String toLowerCase() method of String class.
   **/

  String strLower = str.toLowerCase();

  System.out.println("Original String: " + str);
  System.out.println("String changed to lower case: " + strLower);
 }
}


The output is:


Original String: STRING TOLOWERCASE EXAMPLE
String changed to lower case: string tolowercase example

Java String isEmpty Example


This Java String isEmpty example shows how to check whether the given string is empty or not using isEmpty method of Java String class.


public class JavaStringIsEmptyExample {
 public static void main(String args[]) {

  String str1 = "";
  String str2 = null;
  String str3 = "Hello World";

  /**
   * To check whether the String is empty or not, use boolean
   * isEmpty() method of Java String class.
   * 
   * This method returns true if and only if string.length() is 0.
   **/

  System.out.println("Is String 1 empty? :" + str1.isEmpty());

  // this will throw NullPointerException since str2 is null
  // System.out.println("Is String 2 empty? :" + str2.isEmpty());

  System.out.println("Is String 3 empty? :" + str3.isEmpty());

  /**
   * Please note that isEmpty method was added in JDK 1.6 and
   * it is not available in previous versions.
   * 
   * However, you can use (string.length() == 0) instead of
   * (string.isEmpty()) in previous JDK versions.
   **/
 }
}


The output is:


Is String 1 empty? :true
Is String 3 empty? :false

Java String Reverse Example


This example shows how to reverse a given string



public class StringReverseExample {

 public static void main(String args[]) {

  // declare one string object.

  String str = "Hello World";
  System.out.println("Original String : " + str);

  /**
   * The easiest way to reverse a given string is to use
   * reverse() method of java StringBuilder class.reverse()
   * method returns the StringBuilder object so we need to
   * cast it back to String using toString() method of
   * StringBuilder
   **/

  str = new StringBuilder(str).reverse().toString();

  System.out.println("Reversed String : " + str);
 }

}


The output is:


Original String : Hello World
Reversed String : dlroW olleH

Java String Trim Example


This Java String trim example shows how to remove leading and trailing space from string using
trim method of Java String class.


public class RemoveLeadingTrailingSpace {

 public static void main(String[] args) {

  String str = "   String Trim Example   ";

  /**
   * To remove leading and trailing space from string use,
   * public String trim() method of Java String class.
   **/

  String strTrimmed = str.trim();

  System.out.println("Original String is: " + str);
  System.out.println("Removed Leading and trailing space");
  System.out.println("New String is: " + strTrimmed);
 }
}


The output is:


Original String is:    String Trim Example
Removed Leading and trailing space
New String is: String Trim Example

Java String Split Example


This Java String split example describes how Java String is split into multiple Java String objects.



public class JavaStringSplitExample {

 public static void main(String args[]) {
  
  /**
   * Java String class defines following methods to split
   * Java String object. String[] split( String regularExpression )
   * Splits the string according to given regular expression.
   * String[] split( String reularExpression, int limit ) Splits
   * the string according to given regular expression. The number
   * of resultant substrings by splitting the string is controlled
   * by limit argument.
   **/

  // String to split. 
  String str = "one-two-three";
  String[] temp;

  // delimiter
  String delimiter = "-";
  /**
   * given string will be split by the argument delimiter
   * provided.
   **/
  temp = str.split(delimiter);
  // print substrings
  for (int i = 0; i < temp.length; i++)
   System.out.println(temp[i]);

  /**
   * IMPORTANT : Some special characters need to be escaped while
   * providing them as delimiters like "." and "|".
   **/

  System.out.println("");
  str = "one.two.three";
  delimiter = "\\.";
  temp = str.split(delimiter);
  for (int i = 0; i < temp.length; i++)
   System.out.println(temp[i]);

  /**
   * Using second argument in the String.split() method, we
   * can control the maximum number of substrings generated
   * by splitting a string.
   **/

  System.out.println("");
  temp = str.split(delimiter, 2);
  for (int i = 0; i < temp.length; i++)
   System.out.println(temp[i]);

 }

}


The output is:


one
two
three

one
two
three

one
two.three

Java String Replace Example


This Java String Replace example describes how replace method of Java String class can be used to replace character or substring by new one.



String replace(char oldChar,char newChar)



Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceFirst(String regex,String replacement)



Replaces the first substring of this string that matches the given regular expression with the given replacement.


String replaceAll(String regex, String replacement)



Replaces each substring of this string that matches the given regular expression with the given replacement.

See the example given below:


public class JavaStringReplaceExample {

 public static void main(String args[]) {

  String str = "Replace Region";

  /**
   * Replaces all occurrences of given character with
   * new one and returns new String object.
   **/
  System.out.println(str.replace('R', 'A'));

  /**
   * Replaces only first occurrences of given String
   * with new one and returns new String object.
   **/
  System.out.println(str.replaceFirst("Re", "Ra"));

  /**
   * Replaces all occurrences of given String with new
   * one and returns new String object.
   **/
  System.out.println(str.replaceAll("Re", "Ra"));

 }

}


The output is:


Aeplace Aegion
Raplace Region
Raplace Ragion

Java String Length Example


This example shows how to get a length of a given String object using length() method of the String class.



public class StringLengthExample {

 public static void main(String[] args) {

  // declare the String object

  String str = "Hello World";

  // length() method of String returns the
  // length of a String.

  int length = str.length();

  System.out.println("Length of a String is : " + length);
 }
}


The output is:

Length of a String is : 11

Determining If a String Contains a Substring in Java


To check if a string contains a substring, I usually use:

if(s.indexOf(sub) >= 0)

For JDK 5 or later, a contains method can also be used, which seems to be a little more readable:

if(s.contains(sub))

The signature of contains method is:

public boolean contains(java.lang.CharSequence s);

Note that CharSequence is a super-interface of String, StringBuffer, StringBuilder, java.nio.CharBuffer, javax.swing.text.Segment. So you can pass any of the 5 types to contains method.

The current implementation of contains method just convert the param to String and calls indexOf.

See the example given below:


public class SearchSubStringExample {

 public static void main(String args[]) {

  String str = "Hello World";

  int index = str.indexOf("World");

  if (index >= 0) {
   System.out.println("Substring 'World' found at index:" + index);
  }

  if (str.contains("World")) {

   System.out.println("Substring 'World' found.");
  }

 }
}


The output is:


Substring 'World' found at index:6
Substring 'World' found.

Java String Concatenation and Performance


The following methods will be used to concatenate strings.



  • Concatenation Operator (+)
  • String concat method - concat(String str)
  • StringBuffer append method - append(String str)
  • StringBuilder append method - append(String str)

Let us check which one is most efficient for string concatenation.

Concatenation Operator (+)

The quick and dirty way to concatenate strings in Java is to use the concatenation operator (+). This will yield a reasonable performance if you need to combine two or three strings (fixed-size). But if you want to concatenate n strings in a loop, the performance degrades in multiples of n. Given that String is immutable, for large number of string concatenation operations, using (+) will give us a worst performance.

The + operator, until JDK 1.4 StringBuffer is used internally and from JDK 1.5 StringBuilder is used to concatenate. After concatenation the resultant StringBuffer or StringBuilder is changed to String. i.e.Internally str3=str1 + str 2 statement would be executed as,


 str3=new StringBuffer().append(str1).append(str2).toString()

when a + is used for concatenation see how many steps are involved in the execution of the statement str=str+"*" 
  1. A StringBuffer object is created
  2. string1 is copied to the newly created StringBuffer object
  3. The “*” is appended to the StringBuffer (concatenation)
  4. The result is converted to back to a String object.
  5. The string1 reference is made to point at that new String.
  6. The old String that string1 previously referenced is then made null.
When concatenating static strings it is totally safe to use the "+" operator.A static strings concatenating means that all of the substrings building the final string are known at compile time. If this is the case we should use the "+" operator since the compiler will perform the concatenating at compile time without any performance penalty.


StringBuilder and StringBuffer


When we use dynamic strings the compiler cannot precalculate the concatenating result for us, instead, it uses StringBuilder. This is not that bad if we only do the operation once or twice but if we loop again and again over such code it will have dramatic affect on performance, think of the following example:

String result = "";
 for (int t=0; t<10000; ++t ) {

 result = result + "*";

 }

The compiler will generate something similar to that 

String result = "";
 for (int t=0; t<10000; ++t ) {

 result = new StringBuffer(result).append("*").toString();

 }

Obviously this is not the most efficient way to get our task done. The code generated by the compiler instantiates too many StringBuilder objects, invokes too many methods, and instantiates too many String objects. Using StringBuffer/StringBuilder we can do it more efficiently.


StringBuilder sb = new StringBuilder();


 for (int t=0; t<10000; ++t ) {
 sb.append("*");
 }
 String result = sb.toString();

So what is the difference between StringBuilder and StringBuffer? The difference is that
StringBuffer is a synchronized class, all of its methods are synchronized and as such it should be used in a multithreaded environment (when more than one thread access the same StringBuffer instance). Usually strings concatenating is done by a single thread - in that scenario the StringBuilder should be used.

There is a Third Way - String.concat()


The java.lang.String concat() method is another way to concat strings. This method should be pretty efficient when concatenating a small number of strings (I usually use it when concatenating two strings. For more than two I use the StringBuilder). The concat() method builds a char buffer in the exact size of the destination string, fills the buffer from the two original strings' underlying buffers (using System.arraycopy() which is considered to be a very efficient method) and returns a new string based on the newly allocated buffer. Here is the method code (taken from JDK 1.6)

public String concat(String str) {
 int otherLen = str.length();
  if (otherLen == 0) {
     return this;
 } 
 char buf[] = new char[count + otherLen];
 getChars(0, count, buf, 0); 
 str.getChars(0, otherLen, buf, count);
 return new String(0, count + otherLen, buf); 

}


Example Java Source Code For String Concatenation


Now let’s implement each of the four methods mentioned in the article. Nothing fancy here, plain implementations of (+), String.concat(), StringBuffer.append() & StringBuilder.append().


class Clock {

 private final long startTime;

 public Clock() {
  startTime = System.currentTimeMillis();
 }

 public long getElapsedTime() {
  return System.currentTimeMillis() - startTime;
 }
}

public class StringConcatenationExample {

 static final int N = 50000;

 public static void main(String args[]) {

  // Concatenation using + operator

  Clock clock = new Clock();

  // String to be used for concatenation
  String string1 = "";
  for (int i = 1; i <= N; i++) {

   // String concatenation using +
   string1 = string1 + "*";
  }
  // Recording the time taken to concatenate
  System.out.println("Using + Elapsed time: " + clock.getElapsedTime());

  // Concatenation using String.concat() method.

  clock = new Clock();
  String string2 = "";

  for (int i = 1; i <= N; i++) {

   // String concatenation using String.concat()
   string2 = string2.concat("*");
  }
  // Recording the time taken to concatenate
  System.out.println("Using String.concat Elapsed time: "
    + clock.getElapsedTime());

  // Concatenation using StringBuffer

  clock = new Clock();
  StringBuffer stringBuffer = new StringBuffer();
  for (int i = 1; i <= N; i++) {

   // String concatenation using StringBuffer
   stringBuffer.append("*");
  }
  String string3 = stringBuffer.toString();
  System.out.println("Using StringBuffer Elapsed time: "
    + clock.getElapsedTime());

  // Concatenation using StringBuilder

  clock = new Clock();
  StringBuilder stringBuilder = new StringBuilder();
  for (int i = 1; i <= N; i++) {

   // String concatenation using StringBuilder
   stringBuilder.append("*");
  }
  String string4 = stringBuffer.toString();
  System.out.println("Using StringBuilder Elapsed time: "
    + clock.getElapsedTime());

 }
}


The output is:


Using + Elapsed time: 1578
Using String.concat Elapsed time: 764
Using StringBuffer Elapsed time: 5
Using StringBuilder Elapsed time: 3

From the above generated performance metrics you can see that concatenation using StringBuilder is most efficient compared to other three methods.

Conclusion

For the simple operations we should use String.concat compared to (+), if we don’t want to create a new instance of StringBuffer/Builder. But for huge operations, we shouldn’t be using the concat operator, as seen in the performance results it will bring down the application to its knees and spike up the CPU utilization. To have the best performance, the clear choice is StringBuilder as long as you do not need thread-safety or synchronization

Friday 10 August 2012

Java String Compare using compareTo and compareToIgnoreCase


This Java String compare example describes how Java String is compared with another Java String object using compareTo and compareToIgnoreCase methods of  the String class.

int compareTo(String anotherString)

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

int compareToIgnoreCase(String anotherString)

Compares two strings lexicographically, ignoring case differences.

See the example given below



public class JavaStringCompareExample {

 public static void main(String[] args) {

  // declare String objects

  String str = "Java";
  String anotherStr = "Programming";

  /**
   * Compares two strings lexicographically using
   * compareTo(String anotherString) method.
   **/
  int compare = str.compareTo(anotherStr);

  if (compare > 0) {

   System.out.println(str + " is greater than " + anotherStr);

  } else if (compare < 0) {
   System.out.println(str + " is less than " + anotherStr);

  } else {
   System.out.println(str + " is equal to " + anotherStr);
  }

  String str2 = "JAVA";

  // Compares two strings lexicographically,
  // ignoring case differences.

  if (str.compareToIgnoreCase(str2) == 0)

   System.out.println("Java is equal to JAVA ");
 }
}


The output is:


Java is less than Programming
Java is equal to JAVA

Java String methods - indexOf() and lastIndexOf()


This example shows how we can search a word or a character within a Java String object using indexOf and lastIndexOf methods of the String class.

public class SearchStringExample {

 public static void main(String[] args) {

  // declare a String object
  String strOrig = "Hello world Hello World";

  /**
   * To search a particular word in a given string use,
   * int indexOf(String str) method. It returns the index
   * within this string of the first occurrence of the
   * specified substring if found. Otherwise it returns
   * -1.
   **/

  int intIndex = strOrig.indexOf("Hello");

  if (intIndex == -1) {
   System.out.println("Hello not found");
  } else {
   System.out.println("Found Hello at index " + intIndex);
  }

  /**
   * we can also search a word after particular position
   * using indexOf(String word, int position) method.
   **/

  int positionIndex = strOrig.indexOf("Hello", 11);
  System.out.println("Index of Hello after 11 is " + positionIndex);

  /**
   * Use lastIndexOf method to search a last occurrence
   * of a word within string.
   **/
  int lastIndex = strOrig.lastIndexOf("Hello");
  System.out.println("Last occurrence of Hello is at index " + lastIndex);

  /**
   * To search a particular character in a given string use,
   * int indexOf(int ch) method. It returns the index within
   * this string of the first occurrence of the specified
   * character if found.Otherwise it returns -1.
   **/
  int indexOf_e = strOrig.indexOf('e');

  if (indexOf_e == -1) {
   System.out.println("Character 'e' not found");
  } else {
   System.out.println("Found character 'e' at index " + indexOf_e);
  }

  /**
   * we can also search a character after particular position
   * using indexOf(int ch, int position) method.
   **/

  int positionIndex_e = strOrig.indexOf('e', 11);

  System.out.println("Index of character 'e' after 11 is "
    + positionIndex_e);

  /**
   * Use lastIndexOf method to search a last occurrence of
   * a character within string.
   **/
  int lastIndex_e = strOrig.lastIndexOf('e');

  System.out.println("Last occurrence of 'e' is at index " + lastIndex_e);

 }
}


The output is:


Found Hello at index 0
Index of Hello after 11 is 12
Last occurrence of Hello is at index 12
Found character 'e' at index 1
Index of character 'e' after 11 is 13
Last occurrence of 'e' is at index 13

Searching a String for a Character or a Substring in Java


This example shows how we can search a word or a character within a Java String object using indexOf and lastIndexOf methods of the String class.

public class SearchStringExample {

 public static void main(String[] args) {

  // declare a String object
  String strOrig = "Hello world Hello World";

  /**
   * To search a particular word in a given string use,
   * int indexOf(String str) method. It returns the index
   * within this string of the first occurrence of the
   * specified substring if found. Otherwise it returns
   * -1.
   **/

  int intIndex = strOrig.indexOf("Hello");

  if (intIndex == -1) {
   System.out.println("Hello not found");
  } else {
   System.out.println("Found Hello at index " + intIndex);
  }

  /**
   * we can also search a word after particular position
   * using indexOf(String word, int position) method.
   **/

  int positionIndex = strOrig.indexOf("Hello", 11);
  System.out.println("Index of Hello after 11 is " + positionIndex);

  /**
   * Use lastIndexOf method to search a last occurrence
   * of a word within string.
   **/
  int lastIndex = strOrig.lastIndexOf("Hello");
  System.out.println("Last occurrence of Hello is at index " + lastIndex);

  /**
   * To search a particular character in a given string use,
   * int indexOf(int ch) method. It returns the index within
   * this string of the first occurrence of the specified
   * character if found.Otherwise it returns -1.
   **/
  int indexOf_e = strOrig.indexOf('e');

  if (indexOf_e == -1) {
   System.out.println("Character 'e' not found");
  } else {
   System.out.println("Found character 'e' at index " + indexOf_e);
  }

  /**
   * we can also search a character after particular position
   * using indexOf(int ch, int position) method.
   **/

  int positionIndex_e = strOrig.indexOf('e', 11);

  System.out.println("Index of character 'e' after 11 is "
    + positionIndex_e);

  /**
   * Use lastIndexOf method to search a last occurrence of
   * a character within string.
   **/
  int lastIndex_e = strOrig.lastIndexOf('e');

  System.out.println("Last occurrence of 'e' is at index " + lastIndex_e);

 }
}


The output is:


Found Hello at index 0
Index of Hello after 11 is 12
Last occurrence of Hello is at index 12
Found character 'e' at index 1
Index of character 'e' after 11 is 13
Last occurrence of 'e' is at index 13

Java Char Array To String Example


This example shows how to convert char array to String in Java using String(Char[] ch) constructor of String class.



public class CharArrayToStringExample {

 public static void main(String args[]) {

  // char array
  char[] charArray = new char[] { 'J', 'a', 'v', 'a' };

  /**
   * To convert char array to String in Java,
   * use String(Char[] ch) constructor of Java
   * String class.
   **/

  String str = new String(charArray);

  System.out.println("Char array converted to String: " + str);
 }
}


The output is:


Char array converted to String: Java

Convert String to Character Array Example


This example shows how to convert a given String object to an array of character using
toCharArray method of the String class.

public class StringToCharacterArrayExample {

 public static void main(String args[]) {

  // declare the String object
  String str = "Hello World";

  // declare the char array
  char[] stringArray;

  // convert string into array using toCharArray()
  // method of string class

  stringArray = str.toCharArray();
  System.out.println("The String array contains...");
  // display the array
  for (int index = 0; index < stringArray.length; index++)
   System.out.print(stringArray[index]);

 }

}


The output is:


The String array contains...
Hello World

Thursday 9 August 2012

Copy all the key-value pairs from one Map into another in Java


This Java Example shows how to copy all the key-value pairs from one Map into another using putAll(Map map) method of Java TreeMap class.

public void putAll(Map map)


Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.

See the example given below:

import java.util.TreeMap;

public class CopyTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap treeMap = new TreeMap();

  // add key value pairs to TreeMap
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  // create TreeMap object to copy

  TreeMap copyTreeMap = new TreeMap();

  /**
   * putAll - Copies all of the mappings from
   * the specified map to this map.
   **/

  copyTreeMap.putAll(treeMap);

  System.out.println("copyTreeMap Map Contains:"+copyTreeMap);

 }
}


The output is:


copyTreeMap Map Contains : {1=One, 2=Two, 3=Three, 4=Four, 5=Five}

Get Tail Map from Java TreeMap example


This Java Example shows how to get the portion of TreeMap whose keys are greater than or equal to the specified key using tailMap method.


public SortedMap tailMap(Object fromKey)

Returns a view of the portion of this map whose keys are greater than or equal to fromKey. The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey.

See the example given below:

import java.util.SortedMap;
import java.util.TreeMap;

public class GetTailMapFromTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap treeMap = new TreeMap();

  // add key value pairs to TreeMap
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  /**
   * To get a Tail Map from Java TreeMap use,
   * SortedMap tailMap(Object fromKey) method
   * of Java TreeMap class.
   **/

  SortedMap sortedMap = treeMap.tailMap("2");

  System.out.println("Tail Map Contains : " + sortedMap);

 }
}


The output is:


Tail Map Contains : {2=Two, 3=Three, 4=Four, 5=Five}

Get Head Map from Java TreeMap example


This Java Example shows how to get the portion of TreeMap whose keys are less than
the specified key using headMap method of Java TreeMap class.


public SortedMap headMap(Object toKey)

Returns a view of the portion of this map whose keys are strictly less than toKey. The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key greater than or equal to toKey.

See the example given below:


import java.util.SortedMap;
import java.util.TreeMap;

public class GetHeadMapFromTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap treeMap = new TreeMap();

  // add key value pairs to TreeMap
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  /*
   * To get a Head Map from Java TreeMap use,
   * SortedMap headMap(Object toKey) method
   * of Java TreeMap class.
   */

  SortedMap sortedMap = treeMap.headMap("3");

  System.out.println("Head Map Contains : " + sortedMap);

 }
}


The output is:


Head Map Contains : {1=One, 2=Two}

Get Sub Map from Java TreeMap example


This Java Example shows how to get the sub Map from Java Treemap by giving specific
range of keys using
subMap method of Java TreeMap class.

SortedMap subMap(Object fromKey,Object toKey)


Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. (If fromKey and toKey are equal, the returned sorted map is empty.) The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey or greater than or equal to toKey.

See the example given below:

import java.util.TreeMap;
import java.util.SortedMap;

public class GetSubMapFromTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap treeMap = new TreeMap();

  // add key value pairs to TreeMap
  
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  /**
   * To get the sub Map from Java TreeMap use,
   * SortedMap subMap(Object fromKey,Object toKey)
   * method of TreeMap class.
   **/

  SortedMap sortedMap = treeMap.subMap("2", "5");

  System.out.println("SortedMap Contains : " + sortedMap);

 }
}


The output is:


SortedMap Contains : {2=Two, 3=Three, 4=Four}

Get lowest and highest key stored in Java TreeMap example


This Java Example shows how to get the lowest and highest key stored in the Java TreeMap object using firstKey and lastKey methods of java TreeMap class.



import java.util.TreeMap;

public class GetLowestHighestKeyTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap treeMap = new TreeMap();

  // add key value pairs to TreeMap
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  /**
   * To get the lowest key currently stored in Java TreeMap
   * use, Object firstKey() method of TreeMap class.
   * 
   * This method returns the first or lowest key currently
   * stored in the TreeMap object.
   **/

  System.out.println("Lowest key Stored in Java TreeMap is : "
    + treeMap.firstKey());

  /**
   * To get the highest key currently stored in Java TreeMap
   * use, Object lastKey() method of TreeMap class.
   * 
   * This method returns the last or highest key currently
   * stored in the TreeMap object.
   **/

  System.out.println("Highest key Stored in Java TreeMap is : "
    + treeMap.lastKey());

 }
}


The output is:


Lowest key Stored in Java TreeMap is : 1
Highest key Stored in Java TreeMap is : 5

Wednesday 8 August 2012

Get Synchronized Map from Java TreeMap example


This java example shows how to get a synchronized Map from Java TreeMap using synchronizedMap method of Collections class.

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class GetSynchronizedMapFromTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object

  TreeMap treeMap = new TreeMap();

  /**
   * Java TreeMap is NOT synchronized. To get synchronized
   * Map from TreeMap use static void synchronizedMap(Map map)
   * method of Collections class.
   **/

  Map map = Collections.synchronizedMap(treeMap);

  /**
   * Use this map object to prevent any unsynchronized access
   * to original TreeMap object.
   **/

 }
}

Remove value from Java TreeMap example


This Java Example shows how to remove a key value pair from TreeMap object using remove method.

import java.util.TreeMap;

public class RemoveValueFromTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap tMap = new TreeMap();

  // add key value pairs to TreeMap
  tMap.put("1", "One");
  tMap.put("2", "Two");
  tMap.put("3", "Three");

  /**
   * To remove a key value pair from TreeMap use Object
   * remove(Object key) method of TreeMap class.It returns
   * either the value mapped with the key or null if no
   * value was mapped.
   **/

  Object obj = tMap.remove("2");
  System.out.println(obj + " Removed from TreeMap");

 }
}


The output is:


Two Removed from TreeMap

Remove all values from Java TreeMap example


This Java Example shows how to remove all values from TreeMap object or empty TreeMap or clear TreeMap using clear method.

import java.util.TreeMap;

public class EmptyTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap tMap = new TreeMap();

  // add key value pairs to TreeMap
  tMap.put("1", "One");
  tMap.put("2", "Two");
  tMap.put("3", "Three");

  /**
   * To remove all values or clear TreeMap use
   * void clear method() of TreeMap class. Clear
   * method removes all key value pairs contained in
   * TreeMap.
   **/

  tMap.clear();

  System.out.println("Total key value pairs in TreeMap are : "
    + tMap.size());
 }
}


The output is:


Total key value pairs in TreeMap are : 0

Get Size of Java TreeMap Example


This Java Example shows how to get the size or nubmer of key value pairs stored in TreeMap using size method.

import java.util.TreeMap;

public class GetSizeOfTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap tMap = new TreeMap();

  /**
   * To get the size of TreeMap use int size() method
   * of TreeMap class.It returns the number of key 
   * value pairs stored in TreeMap object.
   **/
  System.out.println("Size of TreeMap : " + tMap.size());

  // add key value pairs to TreeMap using put method
  tMap.put("1", "One");
  tMap.put("2", "Two");
  tMap.put("3", "Three");

  System.out.println("Size of TreeMap after addition : " + tMap.size());

  // remove one element from TreeMap using remove method
  Object obj = tMap.remove("2");

  System.out.println("Size of TreeMap after removal : " + tMap.size());
 }
}


The output is:


Size of TreeMap : 0
Size of TreeMap after addition : 3
Size of TreeMap after removal : 2

Check if a particular value exists in Java TreeMap example


This Java Example shows how to check if TreeMap object contains a particular value using containsValue method of TreeMap class.

import java.util.TreeMap;

public class CheckParticularValueExistTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // add key value pairs to TreeMap

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * To check whether a particular value exists in
   * TreeMap use boolean containsValue(Object key) 
   * method of TreeMap class. It returns true if
   * the value is mapped to one or more keys in the
   * TreeMap otherwise false.
   **/

  boolean blnExists = phoneBook.containsValue("245745");

  System.out.println("Phone number '245745' exists in TreeMap ? : "
    + blnExists);

 }
}


The output is:


Phone number '245745' exists in TreeMap ? : true

Check if a particular key exists in Java TreeMap example


This Java Example shows how to check if TreeMap object contains a particular key using containsKey method of TreeMap class.


import java.util.TreeMap;

public class CheckParticularKeyExistTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // Adding key value pairs to TreeMap

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * To check whether a particular key exists in
   * TreeMap use boolean containsKey(Object key) method
   * of TreeMap class. It returns true if the TreeMap
   * contains mapping for specified key otherwise false.
   **/

  boolean blnExists = phoneBook.containsKey("Joy");
  System.out.println("Name 'Joy' exists in TreeMap ? : " + blnExists);

 }
}


The output is:


Name 'Joy' exists in TreeMap ? : true

How to get all keys in Java TreeMap?


This Java Example shows how to retrieve all keys contained in TreeMap using keySet method of Java TreeMap class.

import java.util.Set;
import java.util.TreeMap;

public class GetKeysFromTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // Adding key value pairs to TreeMap

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys
   * contained in this map in ascending order.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

 }
}


The output is:


Names in the phone book are :
Name: John
Name: Joy
Name: Roy

Tuesday 7 August 2012

Get Set view of Keys from Java TreeMap example


This Java Example shows how to get a Set of keys contained in TreeMap using keySet method of Java TreeMap class.


import java.util.Set;
import java.util.TreeMap;

public class GetSetViewOfKeysFromTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // Add key value pairs to TreeMap.

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys contained
   * in this map in ascending order.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

  /**
   * Please note that resultant Set object is backed by
   * the TreeMap. Any key that is removed from Set will
   * also be removed from original TreeMap object. The same
   * is not the case with the element addition.
   **/

  // remove Roy from nameSet

  nameSet.remove("Roy");

  // check if original TreeMap still contains entry for name Roy.
  boolean blnExists = phoneBook.containsKey("Roy");
  System.out.println("Does TreeMap contain Roy ? " + blnExists);
 }
}


The output is:


Names in the phone book are :
Name: John
Name: Joy
Name: Roy
Does TreeMap contain Roy ? false

Iterate through the values of Java TreeMap example


This Java Example shows how to iterate through the values contained in the TreeMap object.


import java.util.Collection;
import java.util.TreeMap;
import java.util.Iterator;

public class IterateValuesOfTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap tMap = new TreeMap();

  // add key value pairs to TreeMap
  tMap.put("1", "One");
  tMap.put("2", "Two");
  tMap.put("3", "Three");

  /**
    values() - Returns a collection view of the values contained
     in this map. The collection's iterator will return the values
     in the order that their corresponding keys appear in the tree.
     The collection is backed by this TreeMap instance, so changes
     to this map are reflected in the collection, and vice-versa
   **/
  Collection c = tMap.values();

  // obtain an Iterator for Collection
  Iterator itr = c.iterator();

  System.out.println("The map contains values...");
  // iterate through TreeMap values iterator
  while (itr.hasNext())
   System.out.println(itr.next());
 }
}


The output is:


The map contains values...
One
Two
Three

Simple Java TreeMap example


This simple Java Example shows how to use Java TreeMap. It also describes how to add something to  TreeMap and how to retrieve the value added from  TreeMap .



import java.util.Set;
import java.util.TreeMap;

public class JavaTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap
  TreeMap phoneBook = new TreeMap();

  /**
   * Add key value pair to TreeMap using Object put(Object key, Object
   * value) method of Java TreeMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  // retrieve value using Object get(Object key) method of Java TreeMap
  // class
  Object phoneNo = phoneBook.get("Joy");
  System.out.println("Phone number of Joy: " + phoneNo);

  System.out.println("The Map contains...");

  /**
   * Set keySet() - Returns a Set view of the keys contained in this map.
   * The set's iterator will return the keys in ascending order. The map
   * is backed by this TreeMap instance, so changes to this map are
   * reflected in the Set, and vice-versa.
   **/

  Set nameSet = phoneBook.keySet();
  for (Object name : nameSet) {
   System.out.println("Name: " + name + " Phone: "
     + phoneBook.get(name));
  }

  /**
   * put - If the map previously contained a mapping for this key, the old
   * value is replaced and the put method returns the old value.
   **/

  Object oldPhone = phoneBook.put("Roy", "222222");

  System.out.println("Roy's old phone number:" + oldPhone);
  System.out.println("Roy's new phone number:" + phoneBook.get("Roy"));

 }
}


The output is:


Phone number of Joy: 245786
The Map contains...
Name: John Phone: 245745
Name: Joy Phone: 245786
Name: Roy Phone: 233783
Roy's old phone number:233783
Roy's new phone number:222222

Monday 6 August 2012

Checked vs Unchecked Exceptions in Java

Type of exceptions in java are checked exceptions and unchecked exceptions. This classification is based on compile-time checking of exceptions.

At compile time, the java compiler checks that a program contains handlers for checked exceptions.Either you have to enclose the code with a try-catch block or the method must declares that a method can throw a given exception using 'throws' clause, and the caller to that method must explicitly handle the exception (or 'throw it up' to the next caller up the chain).

The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.

Unchecked exceptions behave as follows:



  • They they don't have to be explicitly caught. When an unchecked exception occurs, such as a NullPointerException, ClassCastException,OutOfMemoryError etc, Java will "handle" the exception automatically (see below).

  • Methods and constructors don't have to explicitly state that they can throw an unchecked exception. It's taken for granted that any method can throw them.

  • Indeed, certain Java bytecode instructions (such as array access, invoking a method on an object, integer division etc) can actually throw an unchecked exception.

Creating user defined exceptions in Java

Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter.


While defining an user defined exception, we need to take care of the following aspects:
  • The user defined exception class should extend from Exception class.
  • The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.
Let us see a simple example to learn how to define and make use of user defined exceptions.

Sunday 5 August 2012

Exception Handling : Throws clause in Java

The throws is used for specifying the exceptions thrown by a method.If a method doesn't catch the checked exceptions that can occur within it, the method must specify that it can throw these exceptions.

If a method is throwing a checked exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature. Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.

Let us take one method divide, here we are throwing a user-defined exception if the second parameter is zero.



static int divide(int first, int second) {
if (second == 0)
throw new MyException("can't be divided by zero");
return first / second;
}


In the above method you can handle the exception in two ways.


Difference between throw and throws in Java?

Throw is used to actually throw the exception, whereas throws is used for specifying the exceptions thrown by a method .They are not interchangeable. 
public void myMethod(int param) throws MyException



   if (param < 10) 
throw new MyException("Too low!); 
      --------
}
The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. 
If a method is throwing a checked exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature. Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.

How to Throw Exceptions in Java

It is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:


throw ThrowableInstance;


Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions.There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.


The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.


Here is a sample program that creates and throws an exception. 

What is finally block in java?

The Finally block in java is used along with the try-catch statements. The usual structure is 

try {
 .....
} catch (Exception e) {
 ....
} finally {
 .....
}

 When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown. See the example given below,


public class MyFinallyBlock {
public static void main(String[] a) {
/**
* Exception will occur here, after catch block  the contol will goto
* finally block.
**/
try {
int i = 10 / 0;
} catch (Exception ex) {
System.out.println("Inside 1st catch Block");
} finally {
System.out.println("Inside 1st finally block");
}
/**
* In this case exception won't, after executing try block  the contol
* will goto finally block.
**/
try {
int i = 10 / 10;
} catch (Exception ex) {
System.out.println("Inside 2nd catch Block");
} finally {
System.out.println("Inside 2nd finally block");
}
}
}