Wednesday, December 14, 2011

Exceptions in Java -II

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.

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

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.

Tuesday, November 29, 2011

Creating a Thread



Java defines two ways in which this can be accomplished:
  • You can implement the Runnable interface.
  • You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );

Example:

Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Threads in Java


Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.
I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.


The Arrays Class



The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
SNMethods with Description
1public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
3public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
4public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)

Java String valueOf example.


  1. /*
  2. Java String valueOf example.
  3. This Java String valueOf example describes how various java primitives and Object
  4. are converted to Java String object using String valueOf method.
  5. */
  6.  
  7. public class JavaStringValueOfExample{
  8.  
  9. public static void main(String args[]){
  10.  
  11. /*
  12.   Java String class defines following methods to convert various Java primitives to
  13.   Java String object.
  14.   1) static String valueOf(int i)
  15.   Converts argument int to String and returns new String object representing
  16.   argument int.
  17.   2) static String valueOf(float f)
  18.   Converts argument float to String and returns new String object representing
  19.   argument float.
  20.   3) static String valueOf(long l)
  21.   Converts argument long to String and returns new String object representing
  22.   argument long.
  23.   4) static String valueOf(double i)
  24.   Converts argument double to String and returns new String object representing
  25.   argument double.
  26.   5) static String valueOf(char c)
  27.   Converts argument char to String and returns new String object representing
  28.   argument char.
  29.   6) static String valueOf(boolean b)
  30.   Converts argument boolean to String and returns new String object representing
  31.   argument boolean.
  32.   7) static String valueOf(Object o)
  33.   Converts argument Object to String and returns new String object representing
  34.   argument Object.
  35.   */
  36.  
  37. int i=10;
  38. float f = 10.0f;
  39. long l = 10;
  40. double d=10.0d;
  41. char c='a';
  42. boolean b = true;
  43. Object o = new String("Hello World");
  44.  
  45. /* convert int to String */
  46. System.out.println( String.valueOf(i) );
  47. /* convert float to String */
  48. System.out.println( String.valueOf(f) );
  49. /* convert long to String */
  50. System.out.println( String.valueOf(l) );
  51. /* convert double to String */
  52. System.out.println( String.valueOf(d) );
  53. /* convert char to String */
  54. System.out.println( String.valueOf(c) );
  55. /* convert boolean to String */
  56. System.out.println( String.valueOf(b) );
  57. /* convert Object to String */
  58. System.out.println( String.valueOf(o) );
  59.  
  60. }
  61.  
  62. }
  63.  
  64. /*
  65. OUTPUT of the above given Java String valueOf Example would be :
  66. 10
  67. 10.0
  68. 10
  69. 10.0
  70. a
  71. true
  72. true
  73. Hello World
  74. */

How to find the most appropriate Keywords?

  🔍 Step 1: Understand Your Business and Audience Define your products, services, or content . Identify your target audien...