SlideShare a Scribd company logo
1 of 44
Download to read offline
[1]
Java Lecture Note
Prepared By:
Milan Vachhani
Assistant Professor, MCA Department,
B. H. Gardi College of Engineering and Technology, Rajkot
M – 9898626213
milan.vachhani@gmail.com
http://milanvachhani.blogspot.com
&
Research Scholar, Department of Computer Science,
Saurashtra University, Rajkot
Unit -3
Exception Handling
An exception is an object that is generated at run-time to describe a problem encountered
during the execution of a program.
Some causes for an exception are integer division-by-zero, array index negative or out-of-
bounds, illegal cast, interrupted I/O operation, unexpected end-of-file condition, missing
file, incorrect number format.
An exception is an abnormal condition that arises in a code sequence at run time or we can
say an exception is a run-time error.
In computer languages that do not support exception handling, errors must be checked and
handled manually through the use of error codes.
A java exception is an object that describes an exceptional condition that has occurred in a
piece of code.
When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the
exception itself, or pass it on. Either way, at some point, the exception is caught and
processed.
Java exception handling is managed via five keywords: try, catch, throw, throws and finally.
1. Try: program statements that you want to monitor for exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown.
2. Catch: your code can catch this exception using catch and handle it in some rational
manner.
3. Throw: system-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw.
4. Throws: any exception that is thrown out of a method must be specified by a throws
clause.
[2]
5. Finally: any code that absolutely must be executed before a method returns is put in
a finally block.
General form:
try
{
//block of code to monitor for errors…
}
catch(ExceptionType1 exOb)
{
// exception handling block
}
finally
{
// finally block
}
The try statement contains a block of statements enclosed by braces. This is the code you
want to monitor for exceptions. If a problem occurs during its executing, an exception is
thrown.
Immediately following the try block is a sequence of catch blocks. Each of these begins with
the catch keyword. An argument is passed to each catch block. That argument is the
exception object that contains information about the problem.
If a problem occurs during execution of the try block, the JVM immediately stops executing
the try block and looks for a catch block that can process that type of exception. Any
remaining statements in the try block are not executed. The search begins at the first catch
block. If the type of the exception object matches the type of the catch block parameter,
those statements are executed. Otherwise, the remaining catch clauses are examined in
sequence for a type match.
When a catch block completes executing, control passes to the statements in the finally
block. The java compiler ensures that finally block executed in all circumstances.
When a try block completes without problems, the finally block executes. Even if a return
statement is included in a try block, the compiler ensures that the finally block is executed
before the current method returns.
The finally block is optional. However, in some applications it can provide a useful way to
relinquish resources. For example, you may wish to close files or databases at this point.
Each try block must have at least one catch or finally block.
class ExceptionTest
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
[3]
int x,y;
try
{
X=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
finally
{
System.out.println(“This is finally block”);
}
Y=a/(b+c);
System.out.println(“y=”+y);
}
}
Output:
Division by zero
This is finally block
Y=1
Displaying a Description of an Exception
Throwable overrides the toString() method (defined by Object) so that it returns a string
containing a description of the exception. You can display this description in a println()
statement by simply passing the exception as an argument. For example, the catch block in
the preceding program can be rewritten like this:
catch (ArithmeticException e)
{
System.out.println(“Exception:” +e);
A=0;
}
Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different
type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after
the try/catch block.
The following example traps two different exception types:
[4]
class MultiCatch
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println(“a=” +a);
int b= 42/a;
int c[]={1};
C[42]=99;
}
catch(ArithmeticException e)
{
System.out.println(“divide by zero:” +e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index oob:” +e);
}
}
System.out.println(“After try/catch block”);
}
}
When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their superclasses.
This is because a catch statement that uses a superclass will catch exceptions of that type
plus any of its subclasses. Thus, a subclass would never be reached if it came after its
superclass. Further, in java, unreachable code is an error.
For example, consider the following program:
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a=0;
int b=42/a;
}
catch(Exception e)
{
System.out.println(“Generic Exception catch.”);
}
// ArithmeticException is a subclass of Exception.
[5]
catch(ArithmeticException e)
{
// error-unreachable
System.out.println(“this is never reached.”);
}
}
}
If you try to compile this program, you will receive an error message stating that the second
catch statement is unreachable because the exception has already been caught. Since
ArithmeticException is a subclass of Exception, the first catch statement will handle all
exception based errors, including ArithmeticException. This means that the second catch
statement will never execute. To fix the problem, revere the order of the catch statement.
class ExceptionMulti
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch(ArrayStoreException e)
{
System.out.println(“wrong data type”);
}
int y=a[1]/a[0];
System.out.println(“y=” +y);
}
}
[6]
Throw
We saw that an exception was generated by the JVM when certain run-time problems
occurred.
It is also possible for our program to explicitly generate an exception. This can be done with
a throw statement. Its form is as follows:
throw object;
Here, object must be of type java.lang.Throwable. Otherwise, a compiler error occurs.
Inside a catch block, you may throw the same exception object that was provided as an
argument. This can be done with the following syntax:
catch(ExceptionType param)
{
throw param;
}
Alternatively, you may create and throw a new exception object as follows:
throw new ExceptionType(args);
Here, exceptionType is the type of the exception object and args is the optional argument
list for its constructor.
When a throw statement is encountered, a search for a matching catch block begins. Any
subsequent statements in the same try or catch block are not executed.
class ThrowDemo {
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}
[7]
Throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
You do this by including a throws clause in the method’s declaration.
A throws clause lists the types of exceptions that a method might throw. This is necessary
for all exceptions, except those of type Error or RuntimeException, or any of their
subclasses.
All other exceptions that a method can throw must be declared in the throws clause.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Example:
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block of another
try. Each time a try statement is entered, the context of that exception is pushed on the
stack. If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until all of the nested try
statements are exhausted. If no catch statement matches, then the Java run-time system
will handle the exception.
[8]
Here is an example that uses nested try statements:
class NestTry {
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{ // nested try block
if(a==1) a = a/(a-a); // division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
Methods of Throwable class
The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have
the methods defined by Throwable available to them.
Following figure list methods and description of Throwable class.
[9]
[10]
Types of Exception
Exceptions in Java are of two kinds, checked and unchecked.
Unchecked exceptions
Unchecked exception is a type of exception for that you have option that handle it, or
ignore it.
If you elect to ignore the possibility of an unchecked exception, then, as a result of that your
program will terminate.
If you elect to handle unchecked exceptions that occur then the result will depend on the
code that you have written to handle the exception.
Exceptions instantiated from RuntimeException and its subclasses are considered as
unchecked exceptions.
Checked exceptions
Checked exceptions are those that cannot be ignored when you write the code in your
methods.
Checked exceptions are so called because both the Java compiler and the JVM check to
make sure that the rules of Java are obeyed.
Problems causes to checked exceptions are:
Environmental error that cannot necessarily be detected by testing;
e.g, disk full
broken socket,
database unavailable, etc.
Checked exceptions must be handled at compile time. Only checked exceptions need
appear in throws clauses.
Exception classes in this category represent routine abnormal conditions that should be
anticipated and caught to prevent program termination.
All exceptions instantiated from the Exception class, or from subclasses, of Exception other
than RuntimeException and its subclasses, must either be:
1. Handled with a try block followed by a catch block, or
2. Declared in a throws clause of any method that can throw them
Following figure represents list of checked and unchecked exceptions
[11]
[12]
Create your own Exception
Although Java’s built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications.
This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of
Throwable). Your subclasses don’t need to actually implement anything—it is their
existence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have
the methods defined by Throwable available to them.
Following example create custom exception type.
// This program creates a custom exception type.
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
[13]
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Java.util package
The java.util package contains one of Java’s most powerful subsystems: collections.
A collection is a group of objects. The addition of collections caused fundamental
alterations in the structure and architecture of many elements in java.util.
Collections are a state-of-the-art technology that merits close attention by all Java
programmers.
In addition to collections, java.util contains a wide assortment of classes and interfaces that
support a broad range of functionality. These classes and interfaces are used throughout
the core Java packages and, of course, are also available for use in programs that you write.
Their applications include generating pseudorandom numbers, manipulating date and time,
observing events, manipulating sets of bits, and tokenizing strings.
Because of its many features, java.util is one of Java’s most widely used packages.
The java.util classes are listed here.
AbstractCollection (Java 2) EventObject PropertyResourceBundle
AbstractList (Java 2) GregorianCalendar Random
[14]
AbstractMap (Java 2) HashMap (Java 2) ResourceBundle
AbstractSequentialList (Java 2) HashSet (Java 2) SimpleTimeZone
AbstractSet (Java 2) Hashtable Stack
ArrayList (Java 2) IdentityHashMap StringTokenizer
Arrays (Java 2) LinkedHashMap Timer (Java 2, v1.3)
BitSet LinkedHashSet TimerTask (Java 2, v1.3)
Calendar LinkedList (Java 2) TimeZone
Collections (Java 2) ListResourceBundle TreeMap (Java 2)
Currency (Java 2, v1.4) Locale TreeSet (Java 2)
Date Observable Vector
Dictionary Properties WeakHashMap (Java 2)
EventListenerProxy PropertyPermission (Java 2)
java.util defines the following interfaces. Notice that most were added by Java 2.
Collection (Java 2) List (Java 2) RandomAccess
Comparator (Java 2) ListIterator (Java 2) Set (Java 2)
Enumeration Map (Java 2) SortedMap (Java 2)
EventListener Map.Entry (Java 2) SortedSet (Java 2)
Iterator (Java 2) Observer
Date, Time Zone, Calendar and the Gregorian Calendar classes
Date
The Date class encapsulates the current date and time. It is mainly used to manipulate
dates and time. This class supports the following constructors:
Date()
Date(long millisec)
The first constructor initializes the object with the current date and time.
The second constructor accepts one argument that equals the number of milliseconds that
have elapsed since midnight, January 1, 1970.
Different methods of this class and their description are given below:
Method Description
boolean after(Date date) This method returns true if the invoking Date object
contains a date that is later that the one specified by
date. Otherwise, it returns false.
boolean before(Date date) This method returns true if the invoking Date object
contains a date that is earliar that the one specified by
date. Otherwise, it returns false.
Object clone() This method duplicates the invoking object.
int comperTo(Date date) This method compares the value of the invoking object
[15]
with that of date. It will return 0 if the values are equals.
It will return a negative value if the invoking object is
earlier than date. It will return a positive value if the
invoking object is later than date.
int comperTo(Object obj) It operates identically to compareTo(Date) if obj is of
class Date. Otherwise, it throws a ClassCastException.
boolean equals(Object date) This method returns true if the invoking Date object
contains the same time and date as the one specified by
date. Otherwise, it returns false.
long getTime() This method returns the number of milliseconds that
have elapsed since January 1, 1970.
int hashCode() This method returns the hash code for the invoking
object.
Void setTime(long time) This method sets the time and date as specified by time,
which represents an elapsed time in milliseconds from
midnight, January,1, 1970.
String toString() This method converts the invoking Date object into a
string and returns the result.
Example:
import java.util.*;
class DateDemo
{
public static void main(String s[])
{
Date date=new Date();
System.out.println(date);
long msec=date.getTime();
System.out.println("Milliseconds since Jan 1,1970 GMT="+msec);
Date date2= new Date();
date2.setTime(1384698902429L);
System.out.println(date2); //17 nov 2010
if(date.after(date2))
System.out.println("First date is greater than second date");
else
System.out.println("First date is less than second date");
System.out.println(date.compareTo(date2));
}
}
Output:
Sun Sep 05 14:59:55 GMT 2010
Milliseconds since Jan 1,1970 GMT=1283698795529
Sun Nov 17 14:35:02 GMT 2013
First date is less than second date
-1
[16]
Calendar Class
Calendar is an abstract base class for converting between a Date object and a set of integer
fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific
instant in time with millisecond precision.)
Like other locale-sensitive classes, Calendar provides a class method, getInstance, for
getting a generally useful object of this type. Calendar's getInstance method returns a
Calendar object whose time fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance();
This class provides different constants that are explained below:
Fields Description
static int AM Value of the AM_PM field indicating the period of the day
from midnight to just before noon.
static int AM_PM Get and set whether the HOUR is before or after noon.
static int APRIL Value of the MONTH field indicating the fourth month of the
year.
static int AUGUST Value of the MONTH field indicating the eighth month of the
year.
static int DATE Get and set the date
static int DAY_OF_MONTH Get and set the day of the month.
static int DAY_OF_WEEK Get and set the day of the week.
static int
DAY_OF_WEEK_IN_MONTH
Get and set the ordinal number of the day of the week
within the current month.
static int DAY_OF_YEAR Get and set the day number within the current year.
static int DECEMBER Value of the MONTH field indicating the twelth month of the
year.
static int DST_OFFSET Get and set the daylight savings offset in milliseconds.
static int ERA Get and set the era, e.g., AD or BC in the Julian calendar.
static int FEBRUARY Value of the MONTH field indicating the second month of
the year.
static int FIELD_COUNT The number of distinct fields recognized by get and set.
protected int[]fields The field values for the currently set time for this calendar.
static int FRIDAY Value of the DAY_OF_WEEK field indicating Friday.
static int HOUR Get and set the hour of the morning or afternoon.
static int HOUR_OF_DAY Get and set the hour of the day.
protected boolean[] isSet The flags which tell if a specified time field for the calendar
is set.
[17]
protected Boolean
isTimeSet
True if then the value of time is valid.
static int JANUARY Value of the MONTH field indicating the first month of the
year.
static int JULY Value of the MONTH field indicating the seventh month of
the year.
static int JUNE Value of the MONTH field indicating the sixth month of the
year.
static int MARCH Value of the MONTH field indicating the third month of the
year.
static int MAY Value of the MONTH field indicating the fifth month of the
year.
static int MILLISECOND Get and set the millisecond within the second.
static int MINUTE Get and set the minute within the hour.
static int MONDAY Value of the DAY_OF_WEEK field indicating Monday.
static int MONTH Get and set the month.
Static int NOVEMBER Value of the MONTH field indicating the eleventh month of
the year.
static int OCTOBER Value of the MONTH field indicating the tenth month of the
year.
static int PM Value of the AM_PM field indicating the period of the day
from noon to just before midnight.
Static int SATURDAY Value of the DAY_OF_WEEK field indicating Saturday.
static int SECOND Get and set the second within the minute.
static int SEPTEMBER Value of the MONTH field indicating the ninth month of the
year.
static int SUNDAY Value of the DAY_OF_WEEK field indicating Sunday.
Static int THURSDAY Value of the DAY_OF_WEEK field indicating Thursday.
protected long time The currently set time for this calendar, expressed in
milliseconds after January 1, 1970, 0:00:00 GMT.
static int TUESDAY Value of the DAY_OF_WEEK field indicating Tuesday.
static int UNDECIMBER Value of the MONTH field indicating the thirteenth month of
the year.
static int WEDNESDAY Value of the DAY_OF_WEEK field indicating Wednesday.
static int
WEEK_OF_MONTH
Get and set the week number within the current month.
static int WEEK_OF_YEAR Get and set the week number within the current year.
[18]
static int YEAR Get and set the year.
static int ZONE_OFFSET Get and set the raw offset from GMT in milliseconds.
Methods of this class and their descriptions are given below:
Method Description
abstract void add(int field, int amount) Date Arithmetic function.
boolean after(Object when) Compares the time field records.
boolean before(Object when) Compares the time field records.
void clear() Clears the values of all the time fields.
void clear(int field) Clears the value in the given time field.
protected void complete() Fills in any unset fields in the time field list.
protected abstract void computeFields() Converts the current millisecond time value
time to field values in fields[].
protected abstract void computeTime() Converts the current field values in fields[]
to the millisecond time value time.
boolean equals(Object obj) Compares this calendar to the specified
object.
Int get(int field) Gets the value for a given time field.
int getActualMaximum(int field) Return the maximum value that this field
could have, given the current date.
int getActualMinimum(int field) Return the minimum value that this field
could have, given the current date.
int getFirstDayOfWeek() Gets what the first day of the week is; e.g.,
Sunday in US, Monday in France.
abstract int getGreatestMinimum(int field) Gets the highest minimum value for the
given field if varies.
static Calendar getInstance() Gets a calendar using the default time zone
and locale.
static Calendar getInstance(Locale aLocale) Gets a calendar using the default time zone
and specified locale.
static Calendar getInstance(TimeZone zone) Gets a calendar using the specified time
zone and default locale.
static Calendar getInstance(TimeZone zone,
Locale aLocale)
Gets a calendar with the specified time zone
and locale.
abstract int getLeastMaximum(int field) Gets the lowest maximum value for the
given field if varies.
abstract int getMaximum(int field) Gets the maximum value for the given time
[19]
field.
Int getMinimalDaysInFirstWeek() Gets what the minimal days required in the
first week of the year are; e.g., if the first
week is defined as one that contains the first
day of the first month of a year,
getMinimalDaysInFirstWeek returns 1.
abstract int getMinimum(int field) Gets the minimum value for the given time
field.
Date getTime() Gets this Calendar's current time.
long getTimeInMillis() Gets this Calendar's current time as a long.
TimeZone getTimeZone() Gets the time zone.
Int hashCode() Returns a hash code for this calendar.
protected int internalGet(int field) Gets the value for a given time field.
boolean isLenient() Tell whether date/time interpretation is to
be lenient.
boolean isSet(int field) Determines if the given time field has a
value set.
void set(int field, int value) Sets the time field with the given value.
void set(int year, int month, int date) Sets the values for the fields year, month,
and date.
void set(int year, int month, int date,
int hour, int minute)
Sets the values for the fields year, month,
date, hour, and minute.
void set(int year, int month, int date,
int hour, int minute, int second)
Sets the values for the fields year, month,
date, hour, minute, and second.
void setFirstDayOfWeek(int value) Sets what the first day of the week is; e.g.,
Sunday in US, Monday in France.
void setLenient(boolean lenient) Specify whether or not date/time
interpretation is to be lenient.
Void setMinimalDaysInFirstWeek(int value) Sets what the minimal days required in the
first week of the year are; For example, if
the first week is defined as one that contains
the first day of the first month of a year, call
the method with value 1.
void setTime(Date date) Sets this Calendar's current time with the
given Date.
void setTimeInMillis(long millis) Sets this Calendar's current time from the
given long value.
void setTimeZone(TimeZone value) Sets the time zone with the given time zone
value.
[20]
String toString() Return a string representation of this
calendar.
Example:
class CalDemo
{
public static void main(String s[])
{
Calendar cal=Calendar.getInstance();
cal.set(2009,10,3);
System.out.println(“Day of The week is:”+cal.DAY_OF_WEEK);
System.out.println(“Day of Month is:”+cal.DAY_OF_MONTH);
System.out.println(“Day of Year is :”+cal.DAY_OF_YEAR);
System.out.println(“First Day of the week is :”+cal.getFirstDayOfWeek());
System.out.println(“Date is :“+cal.getTime());
}
}
GregorianCalendar class
GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar
used by most of the world. The standard (Gregorian) calendar has 2 eras, BC and AD. Let’s
see the fields provide by this class.
static int AD Value of the ERA field indicating the common era (Anno Domini), also
known as CE.
static int BC Value of the ERA field indicating the period before the common era
(before Christ), also known as BCE.
Following table give some introduction about the methods provided by this class.
Method Description
void add(int field, int amount) Adds the specified (signed) amount of time to the
given time field, based on the calendar's rules.
boolean equals(Object obj) Compares this GregorianCalendar to an object
reference.
void setGregorianChange(Date date) Sets the GregorianCalendar change date.
[21]
TimeZone
Another time-related class is TimeZone. The TimeZone class allows you to work with time
zone offsets from Greenwich mean time (GMT), also referred to as Coordinated Universal
Time (UTC). It also computes daylight saving time.
TimeZone only supplies the default constructor.
Some methods defined by TimeZone are summarized in following Table
[22]
Collection Framework
Collection framework was introduced with the purpose of standardizing and having
interoperability between various data structures.
Here the data structures are used to manage instances and not for managing primitive
types.
For primitive types we only have arrays. Primitive data type may be used in collection by
using boxing and unboxing.
Collection framework has following important interfaces.
Collection Interfaces
The core collection interfaces are the interfaces used to manipulate collections, and to pass
them from one method to another.
The basic purpose of these interfaces is to allow collections to be manipulated
independently of the details of their representation.
The core collection interfaces are the heart and soul of the collections framework.
Collection
The Collection interface is the root of the collection hierarchy. A Collection represents a
group of objects, known as its element.
Some Collection implementations allow duplicate elements and others do not. Some are
ordered and others unordered.
The JDK doesn't provide any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This interface is the least
common denominator that all collections implement. Collection is used to pass collections
around and manipulate them when maximum generality is desired.
The operations which can be performed on a collection in general can be categorized into
(1) basic operations
(2) array operations and
(3) bulk operations.
[23]
[24]
Methods are divided in following groups
(1) Basic operations:
a. add
b. remove
c. size
d. clear
e. contains
f. isEmpty
g. iterator
(2) Array operations
a. toArray()
b. toArray(Object[] o)
(3) Bulk operations
a. addAll
b. removeAll
c. retainAll
d. containsAll
List
A List is an ordered collection (sometimes called a sequence).
Lists can contain duplicate elements.
The user of a List generally has precise control over where in the List each element is
inserted. The user can access elements by their integer index (position). If you've used
Vector, you're already familiar with the general flavor of List.
[25]
Set
A Set is a collection that cannot contain duplicate elements. As you might expect, this
interface models the mathematical set abstraction. It is used to represent sets like the cards
comprising a poker hand, the courses making up a student's schedule, or the processes
running on a machine.
SortedSet
A SortedSet is a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. The SortedSet interface is used
for things like word lists and membership rolls.
[26]
Using an Iterator
Before you can access a collection through an iterator, you must obtain one. Each of the
collection classes provides an iterator( ) method that returns an iterator to the start of the
collection. By using this iterator object, you can access each element in the collection, one
element at a time. In general, to use an iterator to cycle through the contents of a
collection, follow these steps:
(1) Obtain an iterator to the start of the collection by calling the collection’s iterator( )
method.
(2) Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
(3) Within the loop, obtain each element by calling next( ).
[27]
Map
A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key
can map to at most one value. If you've used Hashtable, you're already familiar with the
general flavor of Map.
The following interfaces support maps:
Interface Description
Map Maps unique keys to values.
Map.Entry Describes an element (a key/value pair) in a map. This is an inner
class of Map.
SortedMap Extends Map so that the keys are maintained in ascending order.
[28]
SortedMap
[29]
A SortedMap is a Map that maintains its mappings in ascending key order. It is the Map
analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and
telephone directories.
The Map.Entry Interface
The Map.Entry interface enables you to work with a map entry. Recall that the entrySet()
method declared by the Map interface returns a Set containing the map entries. Each of
these set elements is a Map.Entry object. Following table summarizes the methods
declared by this interface.
Several classes provide implementations of the map interfaces. The classes that can be used
for maps are summarized here:
Class Description
AbstractMap Implements most of the Map interface.
HashMap Extends AbstractMap to use a hash table.
TreeMap Extends AbstractMap to use a tree.
WeakHashMap Extends AbstractMap to use a hash table with weak keys.
LinkedHashMap Extends HashMap to allow insertion-order iterations.
IdentityHashMap Extends AbstractMap and uses reference equality when comparing
documents.
[30]
Enumeration and Iterator
The object returned by the iterator method deserves special mention. It is an Iterator ,
which is very similar to an Enumeration , but differs in two respects:
Iterator allows the caller to remove elements from the underlying collection during the
iteration with well-defined semantics.
Method names have been improved.
The first point is important: There was no safe way to remove elements from a collection
while traversing it with an Enumeration. The semantics of this operation were ill-defined,
and differed from implementation to implementation
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects.
Enumeration specifies the following two methods:
boolean hasMoreElements( )
Object nextElement( )
When implemented, hasMoreElements( ) must return true while there are still more
elements to extract, and false when all the elements have been enumerated.
nextElement( ) returns the next object in the enumeration as a generic Object reference.
That is, each call to nextElement( ) obtains the next object in the enumeration. The calling
routine must cast that object into the object type held in the enumeration.
Ex.of Enumeration Interface
import java.util.*;
[31]
class VectorDemo
{
public static void main(String s[])
{
Vector vector=new Vector();
vector.addElement(new Integer(5));
vector.addElement(new Float(-14.45f));
vector.addElement(new String(Hello));
vector.addElement(new Long(12000000000));
vector.addElement(new Double(-23.45e-11));
for (Enumeration e=vector.elements();e.hasMoreElements();)
{
System.out.println(e.nextElement());
}
}
}
Classes
Vector
Java doesn't include dynamically linked lists, queues, or other data structures of that type.
Instead, the designers of Java envisioned the Vector class, which handles the occasions
when you need to dynamically store objects.
The Vector class implements a growable array of objects. Like an array, it contains
components that can be accessed using an integer index.
Vector()
Vector(int initialCapacity)
Vector(int initialCapacity, int capacityIncrement)
The fields provided by this class are as given below:
Field Description
protected int
capacityIncrement
The amount by which the capacity of the vector is
automatically incremented when its size becomes greater
than its capacity.
protected int elementCount The number of valid components in this Vector object.
protected Object[]elementData The array buffer into which the components of the vector
are stored.
The methods provided by this class is given below:
Method Description
void add(int index, Object element) Inserts the specified element at the specified
position in this Vector.
[32]
boolean add(Object o) Appends the specified element to the end of this
Vector.
void addElement(Object obj) Adds the specified component to the end of this
vector, increasing its size by one.
int capacity() Returns the current capacity of this vector.
void clear() Removes all of the elements from this Vector.
Boolean contains(Object elem) Tests if the specified object is a component in this
vector.
void copyInto(Object[] anArray) Copies the components of this vector into the
specified array.
Object elementAt(int index) Returns the component at the specified index.
Enumeration elements() Returns an enumeration of the components of this
vector.
Void
ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to
ensure that it can hold at least the number of
components specified by the minimum capacity
argument.
Boolean equals(Object o) Compares the specified Object with this Vector for
equality.
Object firstElement() Returns the first component (the item at index 0) of
this vector.
Object get(int index) Returns the element at the specified position in this
Vector.
int hashCode() Returns the hash code value for this Vector.
int indexOf(Object elem) Searches for the first occurence of the given
argument, testing for equality using the equals
method.
int indexOf(Object elem, int index) Searches for the first occurence of the given
argument, beginning the search at index, and testing
for equality using the equals method.
void insertElementAt(Object obj,
int index)
Inserts the specified object as a component in this
vector at the specified index.
Boolean isEmpty() Tests if this vector has no components.
Object lastElement() Returns the last component of the vector.
int lastIndexOf(Object elem) Returns the index of the last occurrence of the
specified object in this vector.
int lastIndexOf(Object elem,
int index)
Searches backwards for the specified object, starting
from the specified index, and returns an index to it.
[33]
Object remove(int index) Removes the element at the specified position in
this Vector.
boolean remove(Object o) Removes the first occurrence of the specified
element in this Vector If the Vector does not contain
the element, it is unchanged.
Void removeAllElements() Removes all components from this vector and sets
its size to zero.
boolean
removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of
the argument from this vector.
void removeElementAt(int index) Deletes the component at the specified index.
protected void
removeRange(int fromIndex,
int toIndex)
Removes from this List all of the elements whose
index is between fromIndex, inclusive and toIndex,
exclusive.
Object set(int index,
Object element)
Replaces the element at the specified position in this
Vector with the specified element.
void setElementAt(Object obj,
int index)
Sets the component at the specified index of this
vector to be the specified object.
void setSize(int newSize) Sets the size of this vector.
int size() Returns the number of components in this vector.
Object[]toArray() Returns an array containing all of the elements in
this Vector in the correct order.
Object[] toArray(Object[] a) Returns an array containing all of the elements in
this Vector in the correct order; the runtime type of
the returned array is that of the specified array.
String toString() Returns a string representation of this Vector,
containing the String representation of each
element.
Void trimToSize() Trims the capacity of this vector to be the vector's
current size.
Example
import java.util.*;
class VectorDemo
{
public static void main(String s[])
{
Vector vector=new Vector();
vector.addElement(new Integer(5));
vector.addElement(new Float(-14.45f));
vector.addElement(new String("Hello"));
vector.addElement(new Long(12000000000L));
[34]
vector.addElement(new Double(-23.45e-11));
System.out.println("-------------");
System.out.println(vector);
String s1 = new String("String inserted");
vector.add(1,s1);
System.out.println(vector);
vector.removeElementAt(3);
System.out.println(vector);
}
}
Hashtable
This class implements a hashtable, which maps keys to values. Any non-null object can be
used as a key or as a value.
This class provides following constructure:
Hashtable()
Hashtable(int initialCapacity)
Hashtable(int initialCapacity, float loadFactor)
Hashtable(Map t)
Methods of this class and their description are given below:
Method Description
void clear() Clears this hashtable so that it contains no keys.
Object clone() Creates a shallow copy of this hashtable.
Boolean contains(Object value) Tests if some key maps into the specified value in
this hashtable.
Boolean containsKey(Object key) Tests if the specified object is a key in this
hashtable.
Boolean containsValue(Object value) Returns true if this Hashtable maps one or more
keys to this value.
Enumeration elements() Returns an enumeration of the values in this
hashtable.
boolean equals(Object o) Compares the specified Object with this Map for
equality, as per the definition in the Map interface.
Object get(Object key) Returns the value to which the specified key is
mapped in this hashtable.
int hashCode() Returns the hash code value for this Map as per the
definition in the Map interface.
boolean isEmpty() Tests if this hashtable maps no keys to values.
Enumeration keys() Returns an enumeration of the keys in this
hashtable.
[35]
Object put(Object key, Object value) Maps the specified key to the specified value in this
hashtable.
Void putAll(Map t) Copies all of the mappings from the specified Map
to this Hashtable These mappings will replace any
mappings that this Hashtable had for any of the
keys currently in the specified Map.
protected void rehash() Increases the capacity of and internally reorganizes
this hashtable, in order to accommodate and access
its entries more efficiently.
Object remove(Object key) Removes the key (and its corresponding value)
from this hashtable.
int size() Returns the number of keys in this hashtable.
String toString() Returns a string representation of this Hashtable
object in the form of a set of entries, enclosed in
braces and separated by the ASCII characters ", "
(comma and space).
Example
class HashClass
{
public static void main(String s[])
{
Hashtable h1=new Hashtable();
System.out.println(“ Is Table empty ?:”+h1.isEmpty());
h1.put(“the color of Apple is”,”red”);
h1.put(“the color of banana is”,”yellow”);
System.ot.println(“Data of HashTable:”+h1);
System.ot.println(“Value of red is:”+h1.get(“red”));
System.out.println(“ Is Table empty ?:”+h1.isEmpty());
System.out.println(“Remove from table is :”+h1.remove(“The color of
apple is”));
System.out.println(“Now Data of Hash table is :”,h1”);
}
}
StringTokenizer
The string tokenizer class allows an application to break a string into tokens. The
StringTokenizer methods do not distinguish among identifiers, numbers, and quoted
strings, nor do they recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at
creation time or on a per-token basis.
[36]
An instance of StringTokenizer behaves in one of two ways, depending on whether it was
created with the returnDelims flag having the value true or false:
If the flag is false, delimiter characters serve to separate tokens. A token is a
maximal sequence of consecutive characters that are not delimiters.
If the flag is true, delimiter characters are themselves considered to be tokens. A
token is thus either one delimiter character, or a maximal sequence of consecutive
characters that are not delimiters.
A StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
The following is one example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
this
is
a
test
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code. It is recommended that anyone seeking this functionality use the
split method of String or the java.util.regex package instead. There are three constructors:
StringTokenizer(String str)
StringTokenizer(String str, String delim)
StringTokenizer(String str, String delim, boolean returnDelims)
The first constructor constructs a string tokenizer for the specified string. Second
constructor constructs a string tokenizer for the specified string with specific delimiter. In
the third constructuctor, if returnDelims as true than the delimiters are also returned when
the string is parsed. Otherwise the delimiters are not returned.
Method Description
int countTokens() Calculates the number of times that this tokenizer's
nextToken method can be called before it generates
an exception.
boolean hasMoreElements() Returns the same value as the hasMoreTokens
method.
boolean hasMoreTokens() Tests if there are more tokens available from this
tokenizer's string.
Object nextElement() Returns the same value as the nextToken method,
except that its declared return value is Object rather
than String.
[37]
String nextToken() Returns the next token from this string tokenizer.
String nextToken(String delim) Returns the next token in this string tokenizer's string
Random
This class is used to generate Random number. This class defines two constructors as given
below:
Random();
Random(long seed);
This first version creates a number generator that uses the current time as the starting, or
seed value. The second form allows you to specify a seed value manually.
If you initiaze a Random object with a seed, you define the starting point for the random
sequence. If you use the same seed to initialize another Random object, extract the same
random sequence. If you want to generate different sequences, specify different seed
values. The easiest way to do this is to use the current time to seed a Random object. This
approach reduces the possibility of getting repeated sequences.
Method Description
Boolean nextBoolean() This method returns the next boolean number.
Void nextBytes(byte vals[]) This method fills vals with randomly generated values.
Double nextDouble() This method returns the next double random number.
Float nextFloat() This method returns the next float random number.
Double nextGaussian() This method returns the next Gaussian random
number.
int nextInt() This method returns the next int random number.
int nextInt(int n) This method returns the next int random number
within the range zero to n.
Long nextLong() This method returns the next long random number
Void setSeed(long newSeed) This method sets the seed value(that is, the starting
point for the random number generator) to that
specified by newSeed.
Example
Class RandomDemo
{
public static void main(String s[])
{
Random rnd = new Random();
int I,j;
for(I=0;I<10;I++)
{
j=rnd.nextInt(100);
System.out.println(j);
}
}
}
[38]
Regular Expressions, pattern and Matcher Classes.
A regular expression is a string of characters that describes a character sequence. This
general description, called a pattern, can then be used to find matches in other character
sequences. Regular expressions can specify wildcard characters, sets of characters, and
various quantifiers.
Thus, you can specify a regular expression that represents a general form that can match
several different specific character sequences.
There are two classes that support regular expression processing: Pattern and Matcher.
These classes work together.
Use Pattern to define a regular expression. Match the pattern against another sequence
using Matcher.
Pattern
The Pattern class defines no constructors. Instead, a pattern is created by calling the
compile( ) factory method. One of its forms is shown here:
static Pattern compile(String pattern)
Here, pattern is the regular expression that you want to use. The compile( ) method
transforms the string in pattern into a pattern that can be used for pattern matching by the
Matcher class. It returns a Pattern object that contains the pattern.
Once you have created a Pattern object, you will use it to create a Matcher. This is done by
calling the matcher( ) factory method defined by Pattern. It is shown here:
Matcher matcher(CharSequence str)
Here str is the character sequence that the pattern will be matched against. This is called
the input sequence. CharSequence is an interface that was added by Java 2, version 1.4 that
defines a read-only set of characters. It is implemented by the String class, among others.
Thus, you can pass a string to matcher( ).
public static Pattern compile(String regex);
public static Pattern compile(String regex, int flags);
public static boolean matches(String regex, CharSequence input);
public int flags();
public Matcher matcher(CharSequence input);
public String pattern();
public String[ ] split(CharSequence input);
public String[ ] split(CharSequence input, int limit);
Matcher
The Matcher class has no constructors. Instead, you create a Matcher by calling the
matcher( ) factory method defined by Pattern, as just explained. Once you have created a
Matcher, you will use its methods to perform various pattern matching operations.
Some methods of Matcher class
[39]
public Pattern pattern();
public int start();
public int start(int group);
public int end();
public int end(int group);
public boolean find();
public boolean find(int star t);
public String group();
public String group(int group);
public int groupCount();
public boolean lookingAt();
public boolean matches();
public String replaceAll(String replacement);
public String replaceFirst(String replacement);
public Matcher reset();
public Matcher reset(CharSequence input);
The simplest pattern matching method is matches( ), which simply determines whether the
character sequence matches the pattern. It is shown here:
boolean matches( )
It returns true if the sequence and the pattern match, and false otherwise. Understand that
the entire sequence must match the pattern, not just a subsequence of it.
To determine if a subsequence of the input sequence matches the pattern, use find( ). One
version is shown here:
boolean find( )
It returns true if there is a matching subsequence and false otherwise. This method can be
called repeatedly, allowing it to find all matching subsequences. Each call to find( ) begins
where the previous one left off.
You can obtain a string containing the last matching sequence by calling group( ). One of its
forms is shown here:
String group( )
The matching string is returned. If no match exists, then an IllegalStateException is thrown.
You can obtain the index within the input sequence of the current match by calling start( ).
The index one past the end of the current match is obtained by calling end( ). These
methods are shown here:
int start( )
int end( )
You can replace all occurrences of a matching sequence with another sequence by calling
replaceAll( ), shown here:
String replaceAll(String newStr)
Here, newStr specifies the new character sequence that will replace the ones that match
the pattern. The updated input sequence is returned as a string.
[40]
Example
import java.util.regex.*;
class RegExprSample
{
public static void main(String args[])
{
Pattern pat = Pattern.compile("W+");
Matcher mat = pat.matcher("W WW WWW");
while(mat.find())
System.out.println("Match: " + mat.group());
}
}
Output:
Match: W
Match: WW
Match: WWW
Scanner Class
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace. The resulting tokens may then be converted into values of different types using
the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
The scanner can also use delimiters other than whitespace. This example reads several
items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("s*fishs*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
Constructors of Scanner class
Scanner(File source)
Scanner(File source, String charsetName)
[41]
Scanner(InputStream source)
Scanner(InputStream source, String charsetName)
Scanner(Readable source)
Scanner(ReadableByteChannel source)
Scanner(ReadableByteChannel source, String charsetName)
Scanner(String source)
Methods of Scanner class
void close()
Pattern delimiter()
String next()
String next(Pattern pattern)
String next(String pattern)
BigDecimal nextBigDecimal()
BigInteger nextBigInteger()
BigInteger nextBigInteger(int radix)
boolean nextBoolean()
byte nextByte()
byte nextByte(int radix)
double nextDouble()
float nextFloat()
int nextInt()
int nextInt(int radix)
String nextLine()
long nextLong()
long nextLong(int radix)
short nextShort()
short nextShort(int radix)
int radix()
Scanner useDelimiter(Pattern pattern)
Scanner useDelimiter(String pattern)
Scanner useLocale(Locale locale)
Scanner useRadix(int radix)
The delimiter used by Scanner can be get and set by using the delimiter() and the
useDelimiter() menthods. radix() returns this scanner's default radix.
import java.io.*;
import java.util.Scanner;
public class MixedTypeInput
{
public static void main(String[] args)
{
[42]
double number;
Scanner in = new Scanner(System.in);
System.out.println("Enter your gross income: ");
if (in.hasNextInt())
{
number = (double)in.nextInt();
System.out.println("You entered " + number);
}
else if (in.hasNextDouble())
{
number = in.nextDouble();
System.out.println("You entered " + number);
}
else
System.out.println("Token not an integer or a real value.");
}
}
Varargs and the Formatter class
Varargs
The varargs, or variable arguments, feature allows a developer to declare that a method
can take a variable number of parameters for a given argument. The vararg must be the last
argument in the formal argument list.
Example:
public void write(String... records)
{
for (String record: records)
System.out.println(record);
}
write("line 1");
write("line 2", "line 3");
write("line 4", "line 5", "line 6", "line 7", "line 8", "line 9",
"line 10");
Public void printf(String format, Object… value)
System.out.printf(“%d %d %d”,value1,value2,value3);
[43]
Formatter Class
printf() method that was added to the PrintStream class by J2SE 5.0. Internally it uses the
java.util.Formatter class to format numerical values with specifiers similar to those used for
the printf() function in the C language. The java.util.Formatter class includes the method
format (String format, Object... args)
The java.util.Formatter class provides several constructors, each of which includes a
parameter for the destination of the formatted output. Destinations include OutputStream,
an instance of File, and any class that implements the new Appendable interface.
Some of the constructors of Formatter class
public Formatter()
public Formatter(Appendable a)
public Formatter(String fileName)
public Formatter(String fileName, String csn)
public Formatter(File file)
public Formatter(PrintStream ps)
public Formatter(OutputStream os)
public Formatter(OutputStream os, String csn)
Some methods of Formatter class
public Appendable out()
public String toString()
public void flush()
public void close()
public Formatter format(String format, Object... args)
Example:
import java.io.*;
import java.util.*;
public class FormatWriteApp
{
public static void main (String arg[]) {
// Send formatted output to the System.out stream.
Formatter formatter = new Formatter ((OutputStream)System.out);
formatter.format ("Text output with Formatter. %n");
formatter.format ("Primitives converted to strings: %n");
boolean a_boolean = false;
byte a_byte = 114;
int an_int = 1234567;
float a_float = 983.6f;
double a_double = -4.297e-15;
formatter.format ("boolean = %9b %n", a_boolean);
formatter.format ("byte = %9d %n", a_byte);
[44]
formatter.format ("int = %9d %n", an_int);
formatter.format ("float = %9.3f %n", a_float);
formatter.format ("double = %9.2e %n", a_double);
formatter.flush ();
formatter.close ();
}
}
Output:
Text output with Formatter.
Primitives converted to strings:
boolean = false
byte = 114
int = 1234567
float = 983.600
double = -4.30e-15

More Related Content

What's hot

Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programmingRaza Najam
 
Exception handler
Exception handler Exception handler
Exception handler dishni
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsWebStackAcademy
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaManoj_vasava
 

What's hot (19)

Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception handling
Exception handlingException handling
Exception handling
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Control statements
Control statementsControl statements
Control statements
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programming
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handler
Exception handler Exception handler
Exception handler
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 

Similar to Java Exception Handling

Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 

Similar to Java Exception Handling (20)

Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 

More from Abhishek Khune (16)

07 java collection
07 java collection07 java collection
07 java collection
 
Clanguage
ClanguageClanguage
Clanguage
 
Java Notes
Java NotesJava Notes
Java Notes
 
Threads
ThreadsThreads
Threads
 
Sorting
SortingSorting
Sorting
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Week0 introduction
Week0 introductionWeek0 introduction
Week0 introduction
 
Binary trees
Binary treesBinary trees
Binary trees
 
Applets
AppletsApplets
Applets
 
Clanguage
ClanguageClanguage
Clanguage
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Java unit2
Java unit2Java unit2
Java unit2
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Shared memory
Shared memoryShared memory
Shared memory
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

Java Exception Handling

  • 1. [1] Java Lecture Note Prepared By: Milan Vachhani Assistant Professor, MCA Department, B. H. Gardi College of Engineering and Technology, Rajkot M – 9898626213 milan.vachhani@gmail.com http://milanvachhani.blogspot.com & Research Scholar, Department of Computer Science, Saurashtra University, Rajkot Unit -3 Exception Handling An exception is an object that is generated at run-time to describe a problem encountered during the execution of a program. Some causes for an exception are integer division-by-zero, array index negative or out-of- bounds, illegal cast, interrupted I/O operation, unexpected end-of-file condition, missing file, incorrect number format. An exception is an abnormal condition that arises in a code sequence at run time or we can say an exception is a run-time error. In computer languages that do not support exception handling, errors must be checked and handled manually through the use of error codes. A java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Java exception handling is managed via five keywords: try, catch, throw, throws and finally. 1. Try: program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. 2. Catch: your code can catch this exception using catch and handle it in some rational manner. 3. Throw: system-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. 4. Throws: any exception that is thrown out of a method must be specified by a throws clause.
  • 2. [2] 5. Finally: any code that absolutely must be executed before a method returns is put in a finally block. General form: try { //block of code to monitor for errors… } catch(ExceptionType1 exOb) { // exception handling block } finally { // finally block } The try statement contains a block of statements enclosed by braces. This is the code you want to monitor for exceptions. If a problem occurs during its executing, an exception is thrown. Immediately following the try block is a sequence of catch blocks. Each of these begins with the catch keyword. An argument is passed to each catch block. That argument is the exception object that contains information about the problem. If a problem occurs during execution of the try block, the JVM immediately stops executing the try block and looks for a catch block that can process that type of exception. Any remaining statements in the try block are not executed. The search begins at the first catch block. If the type of the exception object matches the type of the catch block parameter, those statements are executed. Otherwise, the remaining catch clauses are examined in sequence for a type match. When a catch block completes executing, control passes to the statements in the finally block. The java compiler ensures that finally block executed in all circumstances. When a try block completes without problems, the finally block executes. Even if a return statement is included in a try block, the compiler ensures that the finally block is executed before the current method returns. The finally block is optional. However, in some applications it can provide a useful way to relinquish resources. For example, you may wish to close files or databases at this point. Each try block must have at least one catch or finally block. class ExceptionTest { public static void main(String args[]) { int a=10; int b=5; int c=5;
  • 3. [3] int x,y; try { X=a/(b-c); } catch(ArithmeticException e) { System.out.println(“Division by zero”); } finally { System.out.println(“This is finally block”); } Y=a/(b+c); System.out.println(“y=”+y); } } Output: Division by zero This is finally block Y=1 Displaying a Description of an Exception Throwable overrides the toString() method (defined by Object) so that it returns a string containing a description of the exception. You can display this description in a println() statement by simply passing the exception as an argument. For example, the catch block in the preceding program can be rewritten like this: catch (ArithmeticException e) { System.out.println(“Exception:” +e); A=0; } Multiple catch Clauses In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types:
  • 4. [4] class MultiCatch { public static void main(String args[]) { try { int a=args.length; System.out.println(“a=” +a); int b= 42/a; int c[]={1}; C[42]=99; } catch(ArithmeticException e) { System.out.println(“divide by zero:” +e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Array index oob:” +e); } } System.out.println(“After try/catch block”); } } When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. Further, in java, unreachable code is an error. For example, consider the following program: class SuperSubCatch { public static void main(String args[]) { try { int a=0; int b=42/a; } catch(Exception e) { System.out.println(“Generic Exception catch.”); } // ArithmeticException is a subclass of Exception.
  • 5. [5] catch(ArithmeticException e) { // error-unreachable System.out.println(“this is never reached.”); } } } If you try to compile this program, you will receive an error message stating that the second catch statement is unreachable because the exception has already been caught. Since ArithmeticException is a subclass of Exception, the first catch statement will handle all exception based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, revere the order of the catch statement. class ExceptionMulti { public static void main(String args[]) { int a[]={5,10}; int b=5; try { int x=a[2]/b-a[1]; } catch(ArithmeticException e) { System.out.println(“Division by zero”); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Array index error”); } catch(ArrayStoreException e) { System.out.println(“wrong data type”); } int y=a[1]/a[0]; System.out.println(“y=” +y); } }
  • 6. [6] Throw We saw that an exception was generated by the JVM when certain run-time problems occurred. It is also possible for our program to explicitly generate an exception. This can be done with a throw statement. Its form is as follows: throw object; Here, object must be of type java.lang.Throwable. Otherwise, a compiler error occurs. Inside a catch block, you may throw the same exception object that was provided as an argument. This can be done with the following syntax: catch(ExceptionType param) { throw param; } Alternatively, you may create and throw a new exception object as follows: throw new ExceptionType(args); Here, exceptionType is the type of the exception object and args is the optional argument list for its constructor. When a throw statement is encountered, a search for a matching catch block begins. Any subsequent statements in the same try or catch block are not executed. class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
  • 7. [7] Throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Example: class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Nested try Statements The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.
  • 8. [8] Here is an example that uses nested try statements: class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); try { // nested try block if(a==1) a = a/(a-a); // division by zero if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } Methods of Throwable class The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them. Following figure list methods and description of Throwable class.
  • 9. [9]
  • 10. [10] Types of Exception Exceptions in Java are of two kinds, checked and unchecked. Unchecked exceptions Unchecked exception is a type of exception for that you have option that handle it, or ignore it. If you elect to ignore the possibility of an unchecked exception, then, as a result of that your program will terminate. If you elect to handle unchecked exceptions that occur then the result will depend on the code that you have written to handle the exception. Exceptions instantiated from RuntimeException and its subclasses are considered as unchecked exceptions. Checked exceptions Checked exceptions are those that cannot be ignored when you write the code in your methods. Checked exceptions are so called because both the Java compiler and the JVM check to make sure that the rules of Java are obeyed. Problems causes to checked exceptions are: Environmental error that cannot necessarily be detected by testing; e.g, disk full broken socket, database unavailable, etc. Checked exceptions must be handled at compile time. Only checked exceptions need appear in throws clauses. Exception classes in this category represent routine abnormal conditions that should be anticipated and caught to prevent program termination. All exceptions instantiated from the Exception class, or from subclasses, of Exception other than RuntimeException and its subclasses, must either be: 1. Handled with a try block followed by a catch block, or 2. Declared in a throws clause of any method that can throw them Following figure represents list of checked and unchecked exceptions
  • 11. [11]
  • 12. [12] Create your own Exception Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions. The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them. Following example create custom exception type. // This program creates a custom exception type. class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } }
  • 13. [13] class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } } Output: Called compute(1) Normal exit Called compute(20) Caught MyException[20] Java.util package The java.util package contains one of Java’s most powerful subsystems: collections. A collection is a group of objects. The addition of collections caused fundamental alterations in the structure and architecture of many elements in java.util. Collections are a state-of-the-art technology that merits close attention by all Java programmers. In addition to collections, java.util contains a wide assortment of classes and interfaces that support a broad range of functionality. These classes and interfaces are used throughout the core Java packages and, of course, are also available for use in programs that you write. Their applications include generating pseudorandom numbers, manipulating date and time, observing events, manipulating sets of bits, and tokenizing strings. Because of its many features, java.util is one of Java’s most widely used packages. The java.util classes are listed here. AbstractCollection (Java 2) EventObject PropertyResourceBundle AbstractList (Java 2) GregorianCalendar Random
  • 14. [14] AbstractMap (Java 2) HashMap (Java 2) ResourceBundle AbstractSequentialList (Java 2) HashSet (Java 2) SimpleTimeZone AbstractSet (Java 2) Hashtable Stack ArrayList (Java 2) IdentityHashMap StringTokenizer Arrays (Java 2) LinkedHashMap Timer (Java 2, v1.3) BitSet LinkedHashSet TimerTask (Java 2, v1.3) Calendar LinkedList (Java 2) TimeZone Collections (Java 2) ListResourceBundle TreeMap (Java 2) Currency (Java 2, v1.4) Locale TreeSet (Java 2) Date Observable Vector Dictionary Properties WeakHashMap (Java 2) EventListenerProxy PropertyPermission (Java 2) java.util defines the following interfaces. Notice that most were added by Java 2. Collection (Java 2) List (Java 2) RandomAccess Comparator (Java 2) ListIterator (Java 2) Set (Java 2) Enumeration Map (Java 2) SortedMap (Java 2) EventListener Map.Entry (Java 2) SortedSet (Java 2) Iterator (Java 2) Observer Date, Time Zone, Calendar and the Gregorian Calendar classes Date The Date class encapsulates the current date and time. It is mainly used to manipulate dates and time. This class supports the following constructors: Date() Date(long millisec) The first constructor initializes the object with the current date and time. The second constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. Different methods of this class and their description are given below: Method Description boolean after(Date date) This method returns true if the invoking Date object contains a date that is later that the one specified by date. Otherwise, it returns false. boolean before(Date date) This method returns true if the invoking Date object contains a date that is earliar that the one specified by date. Otherwise, it returns false. Object clone() This method duplicates the invoking object. int comperTo(Date date) This method compares the value of the invoking object
  • 15. [15] with that of date. It will return 0 if the values are equals. It will return a negative value if the invoking object is earlier than date. It will return a positive value if the invoking object is later than date. int comperTo(Object obj) It operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. boolean equals(Object date) This method returns true if the invoking Date object contains the same time and date as the one specified by date. Otherwise, it returns false. long getTime() This method returns the number of milliseconds that have elapsed since January 1, 1970. int hashCode() This method returns the hash code for the invoking object. Void setTime(long time) This method sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January,1, 1970. String toString() This method converts the invoking Date object into a string and returns the result. Example: import java.util.*; class DateDemo { public static void main(String s[]) { Date date=new Date(); System.out.println(date); long msec=date.getTime(); System.out.println("Milliseconds since Jan 1,1970 GMT="+msec); Date date2= new Date(); date2.setTime(1384698902429L); System.out.println(date2); //17 nov 2010 if(date.after(date2)) System.out.println("First date is greater than second date"); else System.out.println("First date is less than second date"); System.out.println(date.compareTo(date2)); } } Output: Sun Sep 05 14:59:55 GMT 2010 Milliseconds since Jan 1,1970 GMT=1283698795529 Sun Nov 17 14:35:02 GMT 2013 First date is less than second date -1
  • 16. [16] Calendar Class Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision.) Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose time fields have been initialized with the current date and time: Calendar rightNow = Calendar.getInstance(); This class provides different constants that are explained below: Fields Description static int AM Value of the AM_PM field indicating the period of the day from midnight to just before noon. static int AM_PM Get and set whether the HOUR is before or after noon. static int APRIL Value of the MONTH field indicating the fourth month of the year. static int AUGUST Value of the MONTH field indicating the eighth month of the year. static int DATE Get and set the date static int DAY_OF_MONTH Get and set the day of the month. static int DAY_OF_WEEK Get and set the day of the week. static int DAY_OF_WEEK_IN_MONTH Get and set the ordinal number of the day of the week within the current month. static int DAY_OF_YEAR Get and set the day number within the current year. static int DECEMBER Value of the MONTH field indicating the twelth month of the year. static int DST_OFFSET Get and set the daylight savings offset in milliseconds. static int ERA Get and set the era, e.g., AD or BC in the Julian calendar. static int FEBRUARY Value of the MONTH field indicating the second month of the year. static int FIELD_COUNT The number of distinct fields recognized by get and set. protected int[]fields The field values for the currently set time for this calendar. static int FRIDAY Value of the DAY_OF_WEEK field indicating Friday. static int HOUR Get and set the hour of the morning or afternoon. static int HOUR_OF_DAY Get and set the hour of the day. protected boolean[] isSet The flags which tell if a specified time field for the calendar is set.
  • 17. [17] protected Boolean isTimeSet True if then the value of time is valid. static int JANUARY Value of the MONTH field indicating the first month of the year. static int JULY Value of the MONTH field indicating the seventh month of the year. static int JUNE Value of the MONTH field indicating the sixth month of the year. static int MARCH Value of the MONTH field indicating the third month of the year. static int MAY Value of the MONTH field indicating the fifth month of the year. static int MILLISECOND Get and set the millisecond within the second. static int MINUTE Get and set the minute within the hour. static int MONDAY Value of the DAY_OF_WEEK field indicating Monday. static int MONTH Get and set the month. Static int NOVEMBER Value of the MONTH field indicating the eleventh month of the year. static int OCTOBER Value of the MONTH field indicating the tenth month of the year. static int PM Value of the AM_PM field indicating the period of the day from noon to just before midnight. Static int SATURDAY Value of the DAY_OF_WEEK field indicating Saturday. static int SECOND Get and set the second within the minute. static int SEPTEMBER Value of the MONTH field indicating the ninth month of the year. static int SUNDAY Value of the DAY_OF_WEEK field indicating Sunday. Static int THURSDAY Value of the DAY_OF_WEEK field indicating Thursday. protected long time The currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT. static int TUESDAY Value of the DAY_OF_WEEK field indicating Tuesday. static int UNDECIMBER Value of the MONTH field indicating the thirteenth month of the year. static int WEDNESDAY Value of the DAY_OF_WEEK field indicating Wednesday. static int WEEK_OF_MONTH Get and set the week number within the current month. static int WEEK_OF_YEAR Get and set the week number within the current year.
  • 18. [18] static int YEAR Get and set the year. static int ZONE_OFFSET Get and set the raw offset from GMT in milliseconds. Methods of this class and their descriptions are given below: Method Description abstract void add(int field, int amount) Date Arithmetic function. boolean after(Object when) Compares the time field records. boolean before(Object when) Compares the time field records. void clear() Clears the values of all the time fields. void clear(int field) Clears the value in the given time field. protected void complete() Fills in any unset fields in the time field list. protected abstract void computeFields() Converts the current millisecond time value time to field values in fields[]. protected abstract void computeTime() Converts the current field values in fields[] to the millisecond time value time. boolean equals(Object obj) Compares this calendar to the specified object. Int get(int field) Gets the value for a given time field. int getActualMaximum(int field) Return the maximum value that this field could have, given the current date. int getActualMinimum(int field) Return the minimum value that this field could have, given the current date. int getFirstDayOfWeek() Gets what the first day of the week is; e.g., Sunday in US, Monday in France. abstract int getGreatestMinimum(int field) Gets the highest minimum value for the given field if varies. static Calendar getInstance() Gets a calendar using the default time zone and locale. static Calendar getInstance(Locale aLocale) Gets a calendar using the default time zone and specified locale. static Calendar getInstance(TimeZone zone) Gets a calendar using the specified time zone and default locale. static Calendar getInstance(TimeZone zone, Locale aLocale) Gets a calendar with the specified time zone and locale. abstract int getLeastMaximum(int field) Gets the lowest maximum value for the given field if varies. abstract int getMaximum(int field) Gets the maximum value for the given time
  • 19. [19] field. Int getMinimalDaysInFirstWeek() Gets what the minimal days required in the first week of the year are; e.g., if the first week is defined as one that contains the first day of the first month of a year, getMinimalDaysInFirstWeek returns 1. abstract int getMinimum(int field) Gets the minimum value for the given time field. Date getTime() Gets this Calendar's current time. long getTimeInMillis() Gets this Calendar's current time as a long. TimeZone getTimeZone() Gets the time zone. Int hashCode() Returns a hash code for this calendar. protected int internalGet(int field) Gets the value for a given time field. boolean isLenient() Tell whether date/time interpretation is to be lenient. boolean isSet(int field) Determines if the given time field has a value set. void set(int field, int value) Sets the time field with the given value. void set(int year, int month, int date) Sets the values for the fields year, month, and date. void set(int year, int month, int date, int hour, int minute) Sets the values for the fields year, month, date, hour, and minute. void set(int year, int month, int date, int hour, int minute, int second) Sets the values for the fields year, month, date, hour, minute, and second. void setFirstDayOfWeek(int value) Sets what the first day of the week is; e.g., Sunday in US, Monday in France. void setLenient(boolean lenient) Specify whether or not date/time interpretation is to be lenient. Void setMinimalDaysInFirstWeek(int value) Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call the method with value 1. void setTime(Date date) Sets this Calendar's current time with the given Date. void setTimeInMillis(long millis) Sets this Calendar's current time from the given long value. void setTimeZone(TimeZone value) Sets the time zone with the given time zone value.
  • 20. [20] String toString() Return a string representation of this calendar. Example: class CalDemo { public static void main(String s[]) { Calendar cal=Calendar.getInstance(); cal.set(2009,10,3); System.out.println(“Day of The week is:”+cal.DAY_OF_WEEK); System.out.println(“Day of Month is:”+cal.DAY_OF_MONTH); System.out.println(“Day of Year is :”+cal.DAY_OF_YEAR); System.out.println(“First Day of the week is :”+cal.getFirstDayOfWeek()); System.out.println(“Date is :“+cal.getTime()); } } GregorianCalendar class GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world. The standard (Gregorian) calendar has 2 eras, BC and AD. Let’s see the fields provide by this class. static int AD Value of the ERA field indicating the common era (Anno Domini), also known as CE. static int BC Value of the ERA field indicating the period before the common era (before Christ), also known as BCE. Following table give some introduction about the methods provided by this class. Method Description void add(int field, int amount) Adds the specified (signed) amount of time to the given time field, based on the calendar's rules. boolean equals(Object obj) Compares this GregorianCalendar to an object reference. void setGregorianChange(Date date) Sets the GregorianCalendar change date.
  • 21. [21] TimeZone Another time-related class is TimeZone. The TimeZone class allows you to work with time zone offsets from Greenwich mean time (GMT), also referred to as Coordinated Universal Time (UTC). It also computes daylight saving time. TimeZone only supplies the default constructor. Some methods defined by TimeZone are summarized in following Table
  • 22. [22] Collection Framework Collection framework was introduced with the purpose of standardizing and having interoperability between various data structures. Here the data structures are used to manage instances and not for managing primitive types. For primitive types we only have arrays. Primitive data type may be used in collection by using boxing and unboxing. Collection framework has following important interfaces. Collection Interfaces The core collection interfaces are the interfaces used to manipulate collections, and to pass them from one method to another. The basic purpose of these interfaces is to allow collections to be manipulated independently of the details of their representation. The core collection interfaces are the heart and soul of the collections framework. Collection The Collection interface is the root of the collection hierarchy. A Collection represents a group of objects, known as its element. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. The JDK doesn't provide any direct implementations of this interface: It provides implementations of more specific subinterfaces like Set and List. This interface is the least common denominator that all collections implement. Collection is used to pass collections around and manipulate them when maximum generality is desired. The operations which can be performed on a collection in general can be categorized into (1) basic operations (2) array operations and (3) bulk operations.
  • 23. [23]
  • 24. [24] Methods are divided in following groups (1) Basic operations: a. add b. remove c. size d. clear e. contains f. isEmpty g. iterator (2) Array operations a. toArray() b. toArray(Object[] o) (3) Bulk operations a. addAll b. removeAll c. retainAll d. containsAll List A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the List each element is inserted. The user can access elements by their integer index (position). If you've used Vector, you're already familiar with the general flavor of List.
  • 25. [25] Set A Set is a collection that cannot contain duplicate elements. As you might expect, this interface models the mathematical set abstraction. It is used to represent sets like the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine. SortedSet A SortedSet is a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. The SortedSet interface is used for things like word lists and membership rolls.
  • 26. [26] Using an Iterator Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps: (1) Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method. (2) Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. (3) Within the loop, obtain each element by calling next( ).
  • 27. [27] Map A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value. If you've used Hashtable, you're already familiar with the general flavor of Map. The following interfaces support maps: Interface Description Map Maps unique keys to values. Map.Entry Describes an element (a key/value pair) in a map. This is an inner class of Map. SortedMap Extends Map so that the keys are maintained in ascending order.
  • 29. [29] A SortedMap is a Map that maintains its mappings in ascending key order. It is the Map analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and telephone directories. The Map.Entry Interface The Map.Entry interface enables you to work with a map entry. Recall that the entrySet() method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object. Following table summarizes the methods declared by this interface. Several classes provide implementations of the map interfaces. The classes that can be used for maps are summarized here: Class Description AbstractMap Implements most of the Map interface. HashMap Extends AbstractMap to use a hash table. TreeMap Extends AbstractMap to use a tree. WeakHashMap Extends AbstractMap to use a hash table with weak keys. LinkedHashMap Extends HashMap to allow insertion-order iterations. IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents.
  • 30. [30] Enumeration and Iterator The object returned by the iterator method deserves special mention. It is an Iterator , which is very similar to an Enumeration , but differs in two respects: Iterator allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. The first point is important: There was no safe way to remove elements from a collection while traversing it with an Enumeration. The semantics of this operation were ill-defined, and differed from implementation to implementation The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. Enumeration specifies the following two methods: boolean hasMoreElements( ) Object nextElement( ) When implemented, hasMoreElements( ) must return true while there are still more elements to extract, and false when all the elements have been enumerated. nextElement( ) returns the next object in the enumeration as a generic Object reference. That is, each call to nextElement( ) obtains the next object in the enumeration. The calling routine must cast that object into the object type held in the enumeration. Ex.of Enumeration Interface import java.util.*;
  • 31. [31] class VectorDemo { public static void main(String s[]) { Vector vector=new Vector(); vector.addElement(new Integer(5)); vector.addElement(new Float(-14.45f)); vector.addElement(new String(Hello)); vector.addElement(new Long(12000000000)); vector.addElement(new Double(-23.45e-11)); for (Enumeration e=vector.elements();e.hasMoreElements();) { System.out.println(e.nextElement()); } } } Classes Vector Java doesn't include dynamically linked lists, queues, or other data structures of that type. Instead, the designers of Java envisioned the Vector class, which handles the occasions when you need to dynamically store objects. The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. Vector() Vector(int initialCapacity) Vector(int initialCapacity, int capacityIncrement) The fields provided by this class are as given below: Field Description protected int capacityIncrement The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. protected int elementCount The number of valid components in this Vector object. protected Object[]elementData The array buffer into which the components of the vector are stored. The methods provided by this class is given below: Method Description void add(int index, Object element) Inserts the specified element at the specified position in this Vector.
  • 32. [32] boolean add(Object o) Appends the specified element to the end of this Vector. void addElement(Object obj) Adds the specified component to the end of this vector, increasing its size by one. int capacity() Returns the current capacity of this vector. void clear() Removes all of the elements from this Vector. Boolean contains(Object elem) Tests if the specified object is a component in this vector. void copyInto(Object[] anArray) Copies the components of this vector into the specified array. Object elementAt(int index) Returns the component at the specified index. Enumeration elements() Returns an enumeration of the components of this vector. Void ensureCapacity(int minCapacity) Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument. Boolean equals(Object o) Compares the specified Object with this Vector for equality. Object firstElement() Returns the first component (the item at index 0) of this vector. Object get(int index) Returns the element at the specified position in this Vector. int hashCode() Returns the hash code value for this Vector. int indexOf(Object elem) Searches for the first occurence of the given argument, testing for equality using the equals method. int indexOf(Object elem, int index) Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method. void insertElementAt(Object obj, int index) Inserts the specified object as a component in this vector at the specified index. Boolean isEmpty() Tests if this vector has no components. Object lastElement() Returns the last component of the vector. int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this vector. int lastIndexOf(Object elem, int index) Searches backwards for the specified object, starting from the specified index, and returns an index to it.
  • 33. [33] Object remove(int index) Removes the element at the specified position in this Vector. boolean remove(Object o) Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged. Void removeAllElements() Removes all components from this vector and sets its size to zero. boolean removeElement(Object obj) Removes the first (lowest-indexed) occurrence of the argument from this vector. void removeElementAt(int index) Deletes the component at the specified index. protected void removeRange(int fromIndex, int toIndex) Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. Object set(int index, Object element) Replaces the element at the specified position in this Vector with the specified element. void setElementAt(Object obj, int index) Sets the component at the specified index of this vector to be the specified object. void setSize(int newSize) Sets the size of this vector. int size() Returns the number of components in this vector. Object[]toArray() Returns an array containing all of the elements in this Vector in the correct order. Object[] toArray(Object[] a) Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array. String toString() Returns a string representation of this Vector, containing the String representation of each element. Void trimToSize() Trims the capacity of this vector to be the vector's current size. Example import java.util.*; class VectorDemo { public static void main(String s[]) { Vector vector=new Vector(); vector.addElement(new Integer(5)); vector.addElement(new Float(-14.45f)); vector.addElement(new String("Hello")); vector.addElement(new Long(12000000000L));
  • 34. [34] vector.addElement(new Double(-23.45e-11)); System.out.println("-------------"); System.out.println(vector); String s1 = new String("String inserted"); vector.add(1,s1); System.out.println(vector); vector.removeElementAt(3); System.out.println(vector); } } Hashtable This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value. This class provides following constructure: Hashtable() Hashtable(int initialCapacity) Hashtable(int initialCapacity, float loadFactor) Hashtable(Map t) Methods of this class and their description are given below: Method Description void clear() Clears this hashtable so that it contains no keys. Object clone() Creates a shallow copy of this hashtable. Boolean contains(Object value) Tests if some key maps into the specified value in this hashtable. Boolean containsKey(Object key) Tests if the specified object is a key in this hashtable. Boolean containsValue(Object value) Returns true if this Hashtable maps one or more keys to this value. Enumeration elements() Returns an enumeration of the values in this hashtable. boolean equals(Object o) Compares the specified Object with this Map for equality, as per the definition in the Map interface. Object get(Object key) Returns the value to which the specified key is mapped in this hashtable. int hashCode() Returns the hash code value for this Map as per the definition in the Map interface. boolean isEmpty() Tests if this hashtable maps no keys to values. Enumeration keys() Returns an enumeration of the keys in this hashtable.
  • 35. [35] Object put(Object key, Object value) Maps the specified key to the specified value in this hashtable. Void putAll(Map t) Copies all of the mappings from the specified Map to this Hashtable These mappings will replace any mappings that this Hashtable had for any of the keys currently in the specified Map. protected void rehash() Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently. Object remove(Object key) Removes the key (and its corresponding value) from this hashtable. int size() Returns the number of keys in this hashtable. String toString() Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). Example class HashClass { public static void main(String s[]) { Hashtable h1=new Hashtable(); System.out.println(“ Is Table empty ?:”+h1.isEmpty()); h1.put(“the color of Apple is”,”red”); h1.put(“the color of banana is”,”yellow”); System.ot.println(“Data of HashTable:”+h1); System.ot.println(“Value of red is:”+h1.get(“red”)); System.out.println(“ Is Table empty ?:”+h1.isEmpty()); System.out.println(“Remove from table is :”+h1.remove(“The color of apple is”)); System.out.println(“Now Data of Hash table is :”,h1”); } } StringTokenizer The string tokenizer class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments. The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.
  • 36. [36] An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims flag having the value true or false: If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters. If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters. A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. The following is one example of the use of the tokenizer. The code: StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } Output: this is a test StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. There are three constructors: StringTokenizer(String str) StringTokenizer(String str, String delim) StringTokenizer(String str, String delim, boolean returnDelims) The first constructor constructs a string tokenizer for the specified string. Second constructor constructs a string tokenizer for the specified string with specific delimiter. In the third constructuctor, if returnDelims as true than the delimiters are also returned when the string is parsed. Otherwise the delimiters are not returned. Method Description int countTokens() Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception. boolean hasMoreElements() Returns the same value as the hasMoreTokens method. boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer's string. Object nextElement() Returns the same value as the nextToken method, except that its declared return value is Object rather than String.
  • 37. [37] String nextToken() Returns the next token from this string tokenizer. String nextToken(String delim) Returns the next token in this string tokenizer's string Random This class is used to generate Random number. This class defines two constructors as given below: Random(); Random(long seed); This first version creates a number generator that uses the current time as the starting, or seed value. The second form allows you to specify a seed value manually. If you initiaze a Random object with a seed, you define the starting point for the random sequence. If you use the same seed to initialize another Random object, extract the same random sequence. If you want to generate different sequences, specify different seed values. The easiest way to do this is to use the current time to seed a Random object. This approach reduces the possibility of getting repeated sequences. Method Description Boolean nextBoolean() This method returns the next boolean number. Void nextBytes(byte vals[]) This method fills vals with randomly generated values. Double nextDouble() This method returns the next double random number. Float nextFloat() This method returns the next float random number. Double nextGaussian() This method returns the next Gaussian random number. int nextInt() This method returns the next int random number. int nextInt(int n) This method returns the next int random number within the range zero to n. Long nextLong() This method returns the next long random number Void setSeed(long newSeed) This method sets the seed value(that is, the starting point for the random number generator) to that specified by newSeed. Example Class RandomDemo { public static void main(String s[]) { Random rnd = new Random(); int I,j; for(I=0;I<10;I++) { j=rnd.nextInt(100); System.out.println(j); } } }
  • 38. [38] Regular Expressions, pattern and Matcher Classes. A regular expression is a string of characters that describes a character sequence. This general description, called a pattern, can then be used to find matches in other character sequences. Regular expressions can specify wildcard characters, sets of characters, and various quantifiers. Thus, you can specify a regular expression that represents a general form that can match several different specific character sequences. There are two classes that support regular expression processing: Pattern and Matcher. These classes work together. Use Pattern to define a regular expression. Match the pattern against another sequence using Matcher. Pattern The Pattern class defines no constructors. Instead, a pattern is created by calling the compile( ) factory method. One of its forms is shown here: static Pattern compile(String pattern) Here, pattern is the regular expression that you want to use. The compile( ) method transforms the string in pattern into a pattern that can be used for pattern matching by the Matcher class. It returns a Pattern object that contains the pattern. Once you have created a Pattern object, you will use it to create a Matcher. This is done by calling the matcher( ) factory method defined by Pattern. It is shown here: Matcher matcher(CharSequence str) Here str is the character sequence that the pattern will be matched against. This is called the input sequence. CharSequence is an interface that was added by Java 2, version 1.4 that defines a read-only set of characters. It is implemented by the String class, among others. Thus, you can pass a string to matcher( ). public static Pattern compile(String regex); public static Pattern compile(String regex, int flags); public static boolean matches(String regex, CharSequence input); public int flags(); public Matcher matcher(CharSequence input); public String pattern(); public String[ ] split(CharSequence input); public String[ ] split(CharSequence input, int limit); Matcher The Matcher class has no constructors. Instead, you create a Matcher by calling the matcher( ) factory method defined by Pattern, as just explained. Once you have created a Matcher, you will use its methods to perform various pattern matching operations. Some methods of Matcher class
  • 39. [39] public Pattern pattern(); public int start(); public int start(int group); public int end(); public int end(int group); public boolean find(); public boolean find(int star t); public String group(); public String group(int group); public int groupCount(); public boolean lookingAt(); public boolean matches(); public String replaceAll(String replacement); public String replaceFirst(String replacement); public Matcher reset(); public Matcher reset(CharSequence input); The simplest pattern matching method is matches( ), which simply determines whether the character sequence matches the pattern. It is shown here: boolean matches( ) It returns true if the sequence and the pattern match, and false otherwise. Understand that the entire sequence must match the pattern, not just a subsequence of it. To determine if a subsequence of the input sequence matches the pattern, use find( ). One version is shown here: boolean find( ) It returns true if there is a matching subsequence and false otherwise. This method can be called repeatedly, allowing it to find all matching subsequences. Each call to find( ) begins where the previous one left off. You can obtain a string containing the last matching sequence by calling group( ). One of its forms is shown here: String group( ) The matching string is returned. If no match exists, then an IllegalStateException is thrown. You can obtain the index within the input sequence of the current match by calling start( ). The index one past the end of the current match is obtained by calling end( ). These methods are shown here: int start( ) int end( ) You can replace all occurrences of a matching sequence with another sequence by calling replaceAll( ), shown here: String replaceAll(String newStr) Here, newStr specifies the new character sequence that will replace the ones that match the pattern. The updated input sequence is returned as a string.
  • 40. [40] Example import java.util.regex.*; class RegExprSample { public static void main(String args[]) { Pattern pat = Pattern.compile("W+"); Matcher mat = pat.matcher("W WW WWW"); while(mat.find()) System.out.println("Match: " + mat.group()); } } Output: Match: W Match: WW Match: WWW Scanner Class A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. For example, this code allows a user to read a number from System.in: Scanner sc = new Scanner(System.in); int i = sc.nextInt(); The scanner can also use delimiters other than whitespace. This example reads several items in from a string: String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("s*fishs*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); prints the following output: 1 2 red blue Constructors of Scanner class Scanner(File source) Scanner(File source, String charsetName)
  • 41. [41] Scanner(InputStream source) Scanner(InputStream source, String charsetName) Scanner(Readable source) Scanner(ReadableByteChannel source) Scanner(ReadableByteChannel source, String charsetName) Scanner(String source) Methods of Scanner class void close() Pattern delimiter() String next() String next(Pattern pattern) String next(String pattern) BigDecimal nextBigDecimal() BigInteger nextBigInteger() BigInteger nextBigInteger(int radix) boolean nextBoolean() byte nextByte() byte nextByte(int radix) double nextDouble() float nextFloat() int nextInt() int nextInt(int radix) String nextLine() long nextLong() long nextLong(int radix) short nextShort() short nextShort(int radix) int radix() Scanner useDelimiter(Pattern pattern) Scanner useDelimiter(String pattern) Scanner useLocale(Locale locale) Scanner useRadix(int radix) The delimiter used by Scanner can be get and set by using the delimiter() and the useDelimiter() menthods. radix() returns this scanner's default radix. import java.io.*; import java.util.Scanner; public class MixedTypeInput { public static void main(String[] args) {
  • 42. [42] double number; Scanner in = new Scanner(System.in); System.out.println("Enter your gross income: "); if (in.hasNextInt()) { number = (double)in.nextInt(); System.out.println("You entered " + number); } else if (in.hasNextDouble()) { number = in.nextDouble(); System.out.println("You entered " + number); } else System.out.println("Token not an integer or a real value."); } } Varargs and the Formatter class Varargs The varargs, or variable arguments, feature allows a developer to declare that a method can take a variable number of parameters for a given argument. The vararg must be the last argument in the formal argument list. Example: public void write(String... records) { for (String record: records) System.out.println(record); } write("line 1"); write("line 2", "line 3"); write("line 4", "line 5", "line 6", "line 7", "line 8", "line 9", "line 10"); Public void printf(String format, Object… value) System.out.printf(“%d %d %d”,value1,value2,value3);
  • 43. [43] Formatter Class printf() method that was added to the PrintStream class by J2SE 5.0. Internally it uses the java.util.Formatter class to format numerical values with specifiers similar to those used for the printf() function in the C language. The java.util.Formatter class includes the method format (String format, Object... args) The java.util.Formatter class provides several constructors, each of which includes a parameter for the destination of the formatted output. Destinations include OutputStream, an instance of File, and any class that implements the new Appendable interface. Some of the constructors of Formatter class public Formatter() public Formatter(Appendable a) public Formatter(String fileName) public Formatter(String fileName, String csn) public Formatter(File file) public Formatter(PrintStream ps) public Formatter(OutputStream os) public Formatter(OutputStream os, String csn) Some methods of Formatter class public Appendable out() public String toString() public void flush() public void close() public Formatter format(String format, Object... args) Example: import java.io.*; import java.util.*; public class FormatWriteApp { public static void main (String arg[]) { // Send formatted output to the System.out stream. Formatter formatter = new Formatter ((OutputStream)System.out); formatter.format ("Text output with Formatter. %n"); formatter.format ("Primitives converted to strings: %n"); boolean a_boolean = false; byte a_byte = 114; int an_int = 1234567; float a_float = 983.6f; double a_double = -4.297e-15; formatter.format ("boolean = %9b %n", a_boolean); formatter.format ("byte = %9d %n", a_byte);
  • 44. [44] formatter.format ("int = %9d %n", an_int); formatter.format ("float = %9.3f %n", a_float); formatter.format ("double = %9.2e %n", a_double); formatter.flush (); formatter.close (); } } Output: Text output with Formatter. Primitives converted to strings: boolean = false byte = 114 int = 1234567 float = 983.600 double = -4.30e-15