Monday 30 January 2012

Exception


Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.

Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment

An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.

A Program Showing How the JVM throws an Exception at runtime

public class DivideException {

    public static void main(String[] args) {
          division(100,4);                  // Line 1
          division(100,0);        // Line 2
        System.out.println("Exit main().");
    }

    public static void division(int totalSum, int totalNumber) {
          System.out.println("Computing Division.");
          int average  = totalSum/totalNumber;
        System.out.println("Average : "+ average);
    }
}

An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method

Output

Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)
Exception in thread “main”

Exceptions in Java

Throwable Class

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.

Syntax

String getMessage()

void printStackTrace()

String toString()

Class Exception

The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Exception Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax

try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}

try Block
The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception.. If an exception is generated within the try block, the remaining statements in the try block are not executed.

catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed (Though the catch block throws an exception).

finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.

The following program illustrates the scenario.

try {
    <code>
} catch (<exception type1> <parameter1>) { // 0 or more
    <statements>

}
} finally {                               // finally block
    <statements>
}

Download DivideException2.java

Output

Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1

Below is a program showing the Normal Execution of the Program.

Please note that no NullPointerException is generated as was expected by most people

public class DivideException2 {

    public static void main(String[] args) {
          int result  = division(100,0);        // Line 2
        System.out.println("result : "+result);
    }

    public static int division(int totalSum, int totalNumber) {
          int quotient = -1;
          System.out.println("Computing Division.");
          try{
                   quotient  = totalSum/totalNumber;

          }
          catch(Exception e){
                   System.out.println("Exception : "+ e.getMessage());
          }
          finally{
                   if(quotient != -1){
                             System.out.println("Finally Block Executes");
                             System.out.println("Result : "+ quotient);
                   }else{
                             System.out.println("Finally Block Executes. Exception Occurred");
                             return quotient;
                   }

          }
          return quotient;
    }
}
Output

null (And not NullPointerException)

String Buffer


StringBuffer Class

StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).

Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations

Creation of StringBuffers

StringBuffer Constructors

public class StringBufferDemo {

          public static void main(String[] args) {
                   //       Examples of Creation of Strings
                   StringBuffer strBuf1 = new StringBuffer("Bob");
                   StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
                   StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
                   System.out.println("strBuf1 : " + strBuf1);
                   System.out.println("strBuf2 capacity : " + strBuf2.capacity());
                   System.out.println("strBuf3 capacity : " + strBuf3.capacity());
          }
}

Output

strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16

StringBuffer Functions

The following program explains the usage of the some of the basic StringBuffer methods like ;

1. capacity()
Returns the current capacity of the String buffer.

2. length()
Returns the length (character count) of this string buffer.

3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.

4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch




5. toString()
Converts to a string representing the data in this string buffer

6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.

7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.

9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.

11. setLength(int newLength)
Sets the length of this String buffer.

public class StringBufferFunctionsDemo {

          public static void main(String[] args) {
                   //       Examples of Creation of Strings
                   StringBuffer strBuf1 = new StringBuffer("Bobby");
                   StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
                   StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
                   System.out.println("strBuf1 : " + strBuf1);
                   System.out.println("strBuf1 capacity : " + strBuf1.capacity());
                   System.out.println("strBuf2 capacity : " + strBuf2.capacity());
                   System.out.println("strBuf3 capacity : " + strBuf3.capacity());
                   System.out.println("strBuf1 length : " + strBuf1.length());
                   System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2));
                   //       A StringIndexOutOfBoundsException is thrown if the index is not valid.
                   strBuf1.setCharAt(1, 't');
                   System.out.println("strBuf1 after setCharAt 1 to t is : "
                                      + strBuf1);
                   System.out
                                      .println("strBuf1 toString() is : " + strBuf1.toString());
                   strBuf3.append("beginner-java-tutorial");
                   System.out.println("strBuf3 when appended with a String : "
                                      + strBuf3.toString());
                   strBuf3.insert(1, 'c');
                   System.out.println("strBuf3 when c is inserted at 1 : "
                                      + strBuf3.toString());
                   strBuf3.delete(1, 'c');
                   System.out.println("strBuf3 when c is deleted at 1 : "
                                      + strBuf3.toString());
                   strBuf3.reverse();
                   System.out.println("Reversed strBuf3 : " + strBuf3);
                   strBuf2.setLength(5);
                   strBuf2.append("jdbc-tutorial");
                   System.out.println("strBuf2 : " + strBuf2);
                   //       We can clear a StringBuffer using the following line
                   strBuf2.setLength(0);
                   System.out.println("strBuf2 when cleared using setLength(0): "
                                      + strBuf2);
          }
}

Output

strBuf1 : Bobby
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 5
strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 :

String Comparison


Java String Comparison

Java String compare to determine Equality

java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used.

* == Operator
* equals method
* compareTo method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to. The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision1 {

          public static void main(String[] args) {
                   String name1 = "Bob";
                   String name2 = new String("Bob");
                   String name3 = "Bob";
                   // 1st case
                   if (name1 == name2) {
                             System.out.println("The strings are equal.");
                   } else {
                             System.out.println("The strings are unequal.");
                   }
                   // 2nd case
                   if (name1 == name3) {
                             System.out.println("The strings are equal.");
                   } else {
                             System.out.println("The strings are unequal.");
                   }
          }
}

Comparing using the equals Method

The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values). The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision2 {

          public static void main(String[] args) {
                   String name1 = "Bob";
                   String name2 = new String("Bob1");
                   String name3 = "Bob";
                   // 1st case
                   if (name1.equals(name2)) {
                             System.out.println("The strings are equal.");
                   } else {
                             System.out.println("The strings are unequal.");
                   }
                   // 2nd case
                   if (name1.equals(name3)) {
                             System.out.println("The strings are equal.");
                   } else {
                             System.out.println("The strings are unequal.");
                   }
          }
}

Create beautiful Banners for your website – Click Here!

Comparing using the compareTo Method

The compareTo method is used when we need to determine the order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print “name2 follows name1” In the first case and “name1 follows name3” in the second case.

public class StringComparision3 {

          public static void main(String[] args) {
                   String name1 = "bob";
                   String name2 = new String("cob");
                   String name3 = "Bob";
                   // 1st case
                   if (name1.compareTo(name2) == 0) {
                             System.out.println("The strings are equal.");
                   } else if (name1.compareTo(name2) < 0) {
                             System.out.println("name2 follows name1");
                   } else {
                             System.out.println("name1 follows name2");
                   }
                   // 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case
                   if (name1.compareTo(name3) == 0) {
                             System.out.println("The strings are equal.");
                   } else if (name1.compareTo(name3) < 0) {
                             System.out.println("name3 follows name1");
                   } else {
                             System.out.println("name1 follows name3");
                   }
          }
}

Java String Class


Strings in java

Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.

Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

Java.lang.String class creation

A simple String can be created using a string literal enclosed inside double quotes as shown;

String str1 = “My name is bob”;

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.

If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.

String str1 = “My name is bob”;
String str2 = “My name is bob”;
String str3 = “My name ”+ “is bob”; //Compile time expression
String name = “bob”;
String str4 = “My name is” + name;
String str5 = new String(“My name is bob”);

In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects.

Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (“”), using the string concatenation operator (+).

public class StringsDemo {

    public static void main(String[] args) {

          byte[] bytes = {2, 4, 6, 8};

          char[] characters = {'a', 'b', 'C', 'D'};

          StringBuffer strBuffer = new StringBuffer("abcde");

//       Examples of Creation of Strings

          String byteStr = new String(bytes);     

          String charStr = new String(characters);

          String buffStr = new String(strBuffer);

          System.out.println("byteStr : "+byteStr);

          System.out.println("charStr : "+charStr);

          System.out.println("buffStr : "+buffStr);

    }

}

Output

byteStr : : [1]


charStr : abCD
buffStr : abcde

Java toString Method


Implementing toString method in java is done by overriding the Object’s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object’s Default toString java method.

class PointCoordinates {

          private int x, y;
          public PointCoordinates(int x, int y) {
                   this.x = x;
                   this.y = y;
          }
          public int getX() {
                   return x;
          }
          public int getY() {
                   return y;
          }
}

public class ToStringDemo {

          public static void main(String args[]) {
                   PointCoordinates point = new PointCoordinates(10, 10);
                   // using the Default Object.toString() Method
                   System.out.println("Object toString() method : " + point);
                   // implicitly call toString() on object as part of string concatenation
                   String s = point + " testing";
                   System.out.println(s);
          }
}

When you run the ToStringDemo program, the output is:
Object toString() method : PointCoordinates@119c082
PointCoordinates@119c082 testing

In the above example when we try printing PointCoordinates object, it internally calls the Object’s toString() method as we have not overridden the java toString() method. Since out example has no toString method, the default one in Object is used. The format of the default toString method of the Object is as shown below.

Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string.
The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer.

Below is an example shown of the same program by Overriding the default Object toString() method. The toString() method must be descriptive and should generally cover all the contents of the object.

class PointCoordinates {

          private int x, y;
          public PointCoordinates(int x, int y) {
                   this.x = x;
                   this.y = y;
          }
          public int getX() {
                   return x;
          }
          public int getY() {
                   return y;
          }
          // Custom toString() Method.
          public String toString() {
                   return "X=" + x + " " + "Y=" + y;
          }
}

public class ToStringDemo2 {

          public static void main(String args[]) {
                   PointCoordinates point = new PointCoordinates(10, 10);
                   System.out.println(point);
                   String s = point + " testing";
                   System.out.println(s);
          }
}

When you run the ToStringDemo2 program, the output is:

X=10 Y=10
X=10 Y=10 testing

Method Overriding


Java Method Overriding

Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass, following which the new method implementation in the subclass that is executed.

The new method definition must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen it. The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class

A program to explain the different concepts of Java Method Overridding

class CustomException extends Exception {

}

class SuperClassWithDifferentMethods {

          protected int field1 = 10;
          protected static int field2 = 20;
          public void method1() {
                   System.out.println("SuperClassWithDifferentMethods.method1()");
          }
          public final void method2() {
                   System.out.println("SuperClassWithDifferentMethods.method2()");
          }
          private void method3() {
                    System.out.println("SuperClassWithDifferentMethods.method3()");
          }
          private final void method4() {
                   System.out.println("SuperClassWithDifferentMethods.method4()");
          }
          public static void method5() {
                   System.out.println("SuperClassWithDifferentMethods.method5()");
          }
          public void method6() throws Exception {
                   System.out.println("SuperClassWithDifferentMethods.method6()");
          }
          private void method7() {
                   System.out.println("SuperClassWithDifferentMethods.method7()");
          }
          private void method8(int x) {
                   System.out.println("SuperClassWithDifferentMethods.method8()");
          }
          public static void method9() {
                   System.out.println("SuperClassWithDifferentMethods.method9()");
          }
}

class OverridingClass extends SuperClassWithDifferentMethods {

          public int field1 = 30;
          public static int field2 = 40;
          public void method1() {
                   System.out.println("OverridingClass.method1()");
          }
          //We can't override a public final method
          /*         public final void method2(){                  

           System.out.println("OverridingClass.method2()");

           }*/
          private void method3() {
                   System.out.println("OverridingClass.method3()");
          }
          private final void method4() {
                   System.out.println("OverridingClass.method4()");
          }
          public static void method5() {
                   System.out.println("OverridingClass.method5()");
          }
          public void method6() throws CustomException {
                   System.out.println("OverridingClass.method6()");
          }
          public void method7() {
                   System.out.println("OverridingClass.method7()");
          }
          public void method8(final int x) {
                   System.out.println("OverridingClass.method8()");
          }
          //A static method cannot be overridden to be non-static instance method
          /*public void method9() {

           System.out.println("OverridingClass.method9()");

           }*/
}

public class MethodOverridingDemo {

          public static void main(String[] args) {
                   OverridingClass oc1 = new OverridingClass();
                   SuperClassWithDifferentMethods sc3 = new OverridingClass();
                   oc1.method1();
                   oc1.method2();
                   //           Since its private, the below 2 methods are not visible
                   /*           oc1.method3();

                    oc1.method4();*/
                   oc1.method5();
                   try {
                             oc1.method6();
                   } catch (CustomException e) {
                             e.printStackTrace();
                   }
                   oc1.method7();
                   oc1.method8(100);
                   System.out.println("oc1.field1 : " + oc1.field1);
                   System.out.println("oc1.field2 : " + oc1.field2);
                   System.out.println("sc3.field1 : " + sc3.field1);
                   System.out.println("sc3.field2 : " + sc3.field2);
                   sc3.method5();
                   OverridingClass overClass = new OverridingClass();
          SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass;
                   supClass.method5();
                   supClass.method1();
          }
}

Output

OverridingClass.method1()
SuperClassWithDifferentMethods.method2()
OverridingClass.method5()
OverridingClass.method6()
OverridingClass.method7()
OverridingClass.method8()
oc1.field1 : 30
oc1.field2 : 40
sc3.field1 : 10
sc3.field2 : 20
SuperClassWithDifferentMethods.method5()
SuperClassWithDifferentMethods.method5()
OverridingClass.method1()

The new method definitions in the subclass OverridingClass have the same signature and the same return type as the methods in the superclass SuperClassWithDifferentMethods. The new overridden method6 definition specifies a subset of the exceptions (CustomException). The new overridden method7 definition also widens the accessibility to public from private. The overriding method8 also declares the parameter to be final, which is not a part of the method signature and Method Overriding holds good. A static method cannot be overridden to be non-static instance method as shown in the overridden method declaration of method9. A static method is class-specific and not part of any object, while overriding methods are invoked on behalf of objects of the subclass. There are no such restrictions on the fields, as for fields only the field names matter. A final method cannot be overridden, an attempt to which will result in a compile-time error. A private method is not accessible outside the class in which it is defined; therefore, a subclass cannot override it.

A subclass must use the ‘super’ keyword in order to invoke an overridden method in the superclass. A subclass cannot override fields of the superclass, but it can hide them. Code in the subclass can use the keyword super to access members, including hidden fields.

The following distinction between invoking instance methods on an object and accessing fields of an object must be noted. When an instance method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference, that determines which method implementation will be executed. When a field of an object is accessed using a reference, it is the type of the reference, not the class of the current object denoted by the reference, that determines which field will actually be accessed. This is demonstrated in the above program