Posts

Showing posts from 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 ...

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 Div...

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.

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 t...

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. SN Methods with Description 1 public 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). 2 public 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.) 3 public static voi...

Java String valueOf example.

/* Java String valueOf example. This Java String valueOf example describes how various java primitives and Object are converted to Java String object using String valueOf method. */   public class JavaStringValueOfExample {   public static void main ( String args [ ] ) {   /*   Java String class defines following methods to convert various Java primitives to   Java String object.   1) static String valueOf(int i)   Converts argument int to String and returns new String object representing   argument int.   2) static String valueOf(float f)   Converts argument float to String and returns new String object representing   argument float.   3) static String valueOf(long l)   Converts argument long to String and returns new String object representing   argument long.   4) static String valueOf(double i)   Converts argument double to String and returns new String object representi...

Java String split 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 ...

Java String compare example.

/* Java String compare example. This Java String compare example describes how Java String is compared with another Java String object or Java Object. */   public class JavaStringCompareExample {   public static void main ( String args [ ] ) {   /*   Java String class defines following methods to compare Java String object.   1) int compareTo( String anotherString )   compare two string based upon the unicode value of each character in the String.   Returns negative int if first string is less than another   Returns positive int if first string is grater than another   Returns 0 if both strings are same.   2) int compareTo( Object obj )   Behaves exactly like compareTo ( String anotherString) if the argument object   is of type String, otherwise throws ClassCastException.   3) int compareToIgnoreCase( String anotherString )   Compares two strings ignoring the character case of the given...