Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 139

Core Java

Collections
Java 1.5 features
Exceptions and Error handling

Core Java | Muralidhar V


1
Agenda

we will cover the following three modules:


 Collections
 Java 1.5 features
 Exceptions and Error handling

2 Core Java | Muralidhar V


Objectives

At the end of Day , you should be able to:


 Define collections
 Explain features of Java 1.5
 Describe exceptions as well as error handling

3 Core Java | Muralidhar V


Core Java

Collections

Core Java | Muralidhar V


4
Objectives

After completion of this module, you should be able to:


 Explain the limitations of array.
 Understand Java framework hierarchy.
 Interpret hoe to use iterator interface to traverse a collection.
 Set interface, Hashset, and Treeset.
 List interface, ArrayList, and LinkedList
 Explain vector and stack.
 Define map, hashmap and treemap.
 Differentiate between collections and array classes.

5 Core Java | Muralidhar V


Limitations of array

 Arrays do not grow while applications demand otherwise.


 Inadequate support for
– inserting,
– deleting,
– sorting, and
– searching operations.

6 Core Java | Muralidhar V


Collections

 A collection is an object that contains a group of objects within it. These


objects are called the elements of the collection.
 The elements of a collection are objects of same class.
 Collections can grow to any size unlike arrays.
 Java Collection Framework supports two types of collections named
collections maps.

7 Core Java | Muralidhar V


Collection framework

Collections Framework provides a unified system for organizing and


handling collections and is based on four elements:
Interfaces that characterize common collection types
Abstract Classes which can be used as a starting point for custom collections
and which are extended by the JDK implementation classes.
Classes which provide implementations of the Interfaces.
Algorithms that provide behaviors commonly required when using collections
i.e. search, sort, iterate, etc.
Another item in collections framework is the Iterator interface.
An iterator gives you a general-purpose, standardized way of accessing the
elements within a collection, one at a time.

8 Core Java | Muralidhar V


Collection framework hierarchy

Collection

Interface

Class
Set List Queue
Interface
Implementation
Inheritance
HashSet ArrayList Vector

SortedSet
LinkedList

Stack
TreeSet

9 Core Java | Muralidhar V


Collection framework hierarchy (continued)

Map

HashMap TreeMap

10 Core Java | Muralidhar V


Collection interface

 The Collection interface is the root interface for


– storing a collection of objects, and
– processing a collection of objects

11 Core Java | Muralidhar V


Collection interface methods

+add(element: Object): boolean


+addAll(collection: Collection): boolean
+clear(): void
+contains(elment: Object): boolean
+containsAll(collection: Collection):boolean
+equals(object: Object): boolean
+hashcode(): int
+isEmpty(): boolean
+iterator(): Iterator
+remove(element: Object): boolean
+removeAll(collection: Collection): boolean
+retainAll(collection: Collection): boolean
+size(): int
+toArray(): Object[]
+toArray(array: Object[]): Object[]

12 Core Java | Muralidhar V


Collection interface mostly used methods

 boolean add (Object o)


– Ensures that this collection contains the specified element (optional operation).
 boolean addAll(Collection c)
– Adds all of the elements in the specified collection to this collection (optional
operation).
 void clear()
– Removes all of the elements from this collection (optional operation).
 boolean contains(Object o)
– Returns true if this collection contains the specified element.
 Boolean containsAll(Collection c)
– Returns true if this collection contains all of the elements in the specified collection.
 boolean equals(Object o)
– Compares the specified object with this collection for equality.
13 Core Java | Muralidhar V
Set interface

 Mathematically a set is a collection of non-duplicate elements


 The Set interface is used to represent a collection which does not contain
duplicate elements
 The Set interface extends the Collection interface.
 No new methods or constants
 Stipulates that an instance of Set contains no duplicate elements.
 The classes that implement Set must ensure that no duplicate elements can
be added to the set.
 That is no two elements e1 and e2 can be in the set such that e1.equals(e2)
is true.

14 Core Java | Muralidhar V


Set interface (continued)

public interface Set<E> extends Collection<E> {


// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();

15 Core Java | Muralidhar V


Set interface (continued)

// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional

// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
}

16 Core Java | Muralidhar V


Set interface (continued)

 The Java platform contains three general-purpose Set implementations:


HashSet, TreeSet, and LinkedHashSet.
 HashSet:This is an unsorted, unordered Set. This may be chosen when
order of the elements are not important .
 LinkedHashSet:This is ordered. The elements are linked to one another
(Double-Linked). This will maintain the list in the order in which they were
inserted.
 TreeSet:This is a sorted set. The elements in this will be in ascending order in
the natural order. You can also define a custom order by means of a
Comparator passed as a parameter to the constructor.

17 Core Java | Muralidhar V


Example: HashSet, LinkedHashSet, TreeSet

import java.util.*;
public class SetInterfaceEx{
public static void main(String[] args) {
int a[] = {5,2,9,4,1};
Set <Integer> hs = new HashSet<Integer>();
for(int i=0;i<a.length;i++) hs.add(new Integer(a[i]));
System.out.println(hs.size() + " The HashSet is " + hs);
Set <Integer> lhs = new LinkedHashSet<Integer>();
for(int i=0;i<a.length;i++) lhs.add(new Integer(a[i]));
System.out.println(hs.size() + " The LinkedHashSet is " + lhs);
Set <Integer> ts = new TreeSet<Integer>();
for(int i=0;i<a.length;i++) ts.add(new Integer(a[i]));
System.out.println(hs.size() + " The TreeSet is " + ts);
}
}

18 Core Java | Muralidhar V


What to choose and when

 HashSet is a good choice for representing sets if you don't care about
element ordering. But if ordering is important, then LinkedHashSet or
TreeSet are better choices. However, LinkedHashSet or TreeSet come with
an additional speed and space cost.
 Iteration over a LinkedHashSet is generally faster than iteration over a
HashSet.
 Tree-based data structures get slower as the number of elements get larger
 HashSet and LinkedHashSet do not represent their elements in sorted order
 Because TreeSet keeps its elements sorted, it can offer other features such
as the first and last methods,i.e the lowest and highest elements in a set,
respectively.

19 Core Java | Muralidhar V


Enumeration interface

 The Enumeration interface defines a way to traverse all the members of a


collection of objects.
 The hasMoreElements() method checks to see if there are more elements
and returns a boolean.

 If there are more elements, nextElement() will return the next element as an
Object.
 If there are no more elements when nextElement() is called, the runtime
NoSuchElementException will be thrown.

20 Core Java | Muralidhar V


Enumeration interface in action

import java.util.Enumeration;
import java.util.Vector;
public class MainClass {
public static void main(String args[]) throws
Exception {
Vector v = new Vector();
v.add("a");
v.add("b");
v.add("c");
Enumeration e = v.elements();
while (e.hasMoreElements()) {
Object o = e.nextElement();
System.out.println(o);
}
}
}
21 Core Java | Muralidhar V
Iterator interface

 Iterator is a special object to provide a way to access the elements of a


collection sequentially.
 Iterator implements one of two interfaces: Iterator or ListIterator
 An Iterator is similar to the Enumeration interface, Iterators differ from
enumerations in two ways:
– Iterators allow the caller to remove elements from the underlying collection during the
iteration with well-defined semantics.
– Method names have been improved.
 boolean hasNext()
Returns true if the iteration has more elements. 
 Object next()
Returns the next element in the iteration. 
 void remove()
Removes from the underlying collection the last element returned by the iterator (optional
operation).
22 Core Java | Muralidhar V
Iterator interface in action

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class MainClass {


public static void main(String[] a) {
Collection c = new ArrayList();
c.add("1");
c.add("2");
c.add("3");
Iterator i = c.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
23 Core Java | Muralidhar V
The SortedSet interface and the TreeSet class

 SortedSet is a subinterface of Set, which guarantees that the elements in the


set are sorted.
 TreeSet is a concrete class that implements the SortedSet interface. You can
use an iterator to traverse the elements in the sorted order.
 The elements can be sorted in two ways.
– One way is to use the Comparable interface. Objects can be compared using by
the compareTo() method. This approach is referred to as a natural order.
– The other way is to specify a comparator for the elements in the set if the class for
the elements does not implement the Comparable interface, or you don’t want to
use the compareTo() method in the class that implements the Comparable
interface. This approach is referred to as order by comparator

24 Core Java | Muralidhar V


Using TreeSet to sort elements in a set

Using HashSet
Set hashSet = new HashSet();
hashSet.add(“Yellow”);
hashSet.add(“White ”);
hashSet.add(“Green”);
hashSet.add(“Orange”);
System.out.println(“An unsorted set of strings”);
System.out.println(hashSet + “\n”);
Output: An unsorted set of strings
[Orange, Green, White, Yellow]
Using TreeSet
Set treeSet = new TreeSet(hashSet);
System.out.println(“Sorted set of strings”);
System.out.println(treeSet + “\n”);
Output: A sorted set of strings

[Green, Orange, White, Yellow]

25 Core Java | Muralidhar V


The list interface

 A list allows duplicate elements in a collection


 Where duplicate elements are to be stored in a collection, list can be used.
 A list also allows to specify where the element is to be stored.
 The user can access the element by index.
 The List interface allows to create a list of elements
 The List interface extends the Collection interface

26 Core Java | Muralidhar V


The list interface (continued)

 A List interface has the following methods


+add(index: int, element: Object) : boolean
+addAll(index: int, collection: Collection) : boolean
+get(index: int) : Object
+indexOf(element: Object) : int
+lastIndexOf(element: Object) : int
+listIterator() : ListIterator
+listIterator(startIndex: int) : ListIterator
+remove(index: int) : int
+set(index: int, element: Object) : Object
+subList(fromIndex: int, toIndex: int) : List

27 Core Java | Muralidhar V


Using ArrayList and LinkedList

 ArrayList and LinkedList are two implementations of List interface.


 This example creates an array list filled with numbers, and inserts new
elements into the specified location in the list.
 The example also creates a linked list from the array list, inserts and removes
the elements from the list.
 Finally, the example traverses the list forward and backward.

28 Core Java | Muralidhar V


Using ArrayList and LinkedList (continued)

ArrayList arrayList = new ArrayList();


arrayList.add(new Integer(1));
arrayList.add(new Integer(2));
arrayList.add(new Integer(3));
arrayList.add(0, new Integer(10));
arrayList.add(3, new Integer(20));
System.out.println(arrayList);
Output:
[10,1,2,20,3]

29 Core Java | Muralidhar V


Using ArrayList and LinkedList (continued)

LinkedList linkedList = new LinkedList(arrayList);


linkedList.add(1, “A”); //[10,“A”, 1, 2, 20]
linkedList.removeLast(); //[10,“A”, 1, 2]
linkedList.addFirst(“B”); //[“B”, 10,“A”, 1, 2]
System.out.println(linkedList);
Output:
[“B”, 10, “A”, 1, 2, 20]

30 Core Java | Muralidhar V


ArrayList vs. LinkedList

 ArrayList provides support random access through an index without inserting


or removing elements from any place other than an end.
 LinkedList provides support for random access through an index with
inserting and deletion elements from any place .
 If your application does not require insertion or deletion of elements, the Array
is the most efficient data structure.

31 Core Java | Muralidhar V


The Vector class

List
 The Vector class implements a
growable array of objects.
Vector  Like an array, it contains
+addElement(element: Object) : void components that can be accessed
+capacity() : void using an integer index.
+copyInto(anArray: Object[]) : void
+elementAt(index: int) : Object
+elements() : Enumeration
 However, the size of a Vector can
+ensureCapacity() : void grow or shrink as needed to
+firstElement() : int
+insertElementAt(index: int) : void accommodate adding and removing
+lastElement() : Object items after the Vector has been
+removeAllElements() : void
+removeElement(element: Object) : void created.
+removeElementAt(index: int) : void
+setElementAt(element: Object, index: int) : void
+setSize(newSize: int) : void
+trimToSize() : void

32 Core Java | Muralidhar V


The Stack class

 The Stack class represents a last-in-


Vector first-out (LIFO) stack of objects. The
elements are accessed only from
the top of the stack. You can
retrieve, insert, or remove an
Stack element from the top of the stack.

+empty() : boolean
+peek() : Object
+pop() : Object
+push(element: Object) : void
+search(element: Object) : int

33 Core Java | Muralidhar V


Using vector and stack

 This example presents two programs to rewrite Example 5.2, using a vector
and a stack instead of an array, respectively.
 The program reads student scores from the keyboard, stores the scores in the
vector, finds the best scores, and then assigns grades for all the students.
 A negative score signals the end of the input.

34 Core Java | Muralidhar V


Map interface

 A Map is a storage that maps keys to values. There cannot be duplicate keys
in a Map and each key maps to at most one value.
 The Map interface is not an extension of Collection interface. Instead the
interface starts of it’s own interface hierarchy.
 for maintaining key-value associations. The interface describes a mapping
from keys to values, without duplicate keys, by definition.
 The Map interface maps keys to the elements. The keys are like indexes. In
List, the indexes are integer. In Map, the keys can be any objects.

35 Core Java | Muralidhar V


Map interface (continued)

 void clear()
– Removes all mappings from this map (optional operation).
 boolean containsKey(Object key)
– Returns true if this map contains a mapping for the specified key.
 boolean containsValue(Object value)
– Returns true if this map maps one or more keys to the specified value.
 Set<Map.Entry<K,V>> entrySet()
– Returns a set view of the mappings contained in this map.
 boolean equals(Object o)
– Compares the specified object with this map for equality.
 V get(Object key)

Returns the value to which this map maps the specified key.
 int hashCode()
– Returns the hash code value for this map.

Core Java | Muralidhar V


Map interface (continued)

 boolean isEmpty()
– Returns true if this map contains no key-value mappings.
 Set<K> keySet()
– Returns a set view of the keys contained in this map.
 V put(K key, V value)

Associates the specified value with the specified key in this map (optional
operation).
 void putAll(Map<? extends K,? extends V> t)
– Copies all of the mappings from the specified map to this map (optional operation).
 V remove(Object key)
– Removes the mapping for this key from this map if it is present (optional operation).

 int size()
– Returns the number of key-value mappings in this map.
 Collection<V> values()
– Returns a collection view of the values contained in this map.

Core Java | Muralidhar V


HashMap and TreeMap

 The HashMap and TreeMap classes are two concrete implementations of the
Map interface. Both will require key &value. Keys must be unique.
 The HashMap class is efficient for locating a value, inserting a mapping, and
deleting a mapping.
 The TreeMap class, implementing SortedMap, is efficient for traversing the
keys in a sorted order.
 HashMap allows null as both keys and values
 TreeMap is slower than HashMap
 TreeMap allows us to specify an optional Comparator object during its
creation. This comparator decides the order by which the keys need to be
sorted.

38 Core Java | Muralidhar V


Example: Map interface
import java.util.*;
class MapEx{
public static void main(String args[]) {
Map<String,String> map = new HashMap<String,String>();
map.put ("1", "one");
map.put ("2", "two");
System.out.println(map.size() ); //print 2
System.out.println(map.get("1") ); //print "one"
Set keys = map.keySet(); // print the keys
for (Object object : keys) { System.out.println(object); }
}
}
39 Core Java | Muralidhar V
The array class
Arrays
+asList(a: Object[]) : List
 The Collections class contains +binarySearch(a: byte[],key: byte) : int
+binarySearch(a: char[], key: char) : int
various static methods for +binarySearch(a: double[], key: double) : int
+binarySearch(a,: float[] key: float) : int
operating on collections and +binarySearch(a: int[], key: int) : int
+binarySearch(a: long[], key: long) : int
maps, for creating synchronized +binarySearch(a: Object[], key: Object) : int
+binarySearch(a: Object[], key: Object, c: Comparator) : int
collection classes, and for +binarySearch(a: short[], key: short) : int
+equals(a: boolean[], a2: boolean[]) : boolean
creating read-only collection +equals(a: byte[], a2: byte[]) : boolean
classes. +equals(a: char[], a2: char[]) : boolean
+equals(a: double[], a2: double[]) : boolean
+equals(a: float[], a2: float[]) : boolean
+equals(a: int[], a2: int[]) : boolean
+equals(a: long[], a2: long[]) : boolean
+equals(a: Object[], a2: Object[]) : boolean
+equals(a: short[], a2: short[]) : boolean
+fill(a: boolean[], val: boolean) : void
+fill(a: boolean[], fromIndex: int, toIndex: int, val: boolean) : void

Overloaded fill method for char, byte, short, int, long, float, double,
and Object.

+sort(a: byte[]) : void


+sort(a: byte[], fromIndex: int, toIndex: int) : void

Overloaded sort method for char, short, int, long, float, double, and
Object.

40 Core Java | Muralidhar V


Example: Using the array class

 This example demonstrates using the methods in the Arrays class. The
example creates an array of int values, fills part of the array with 50, sorts it,
searches for an element, and compares the array with another array.
 (See the Companion site)

TestArrays
41 Core Java | Muralidhar V
Ordering the objects
Comparable interface and Comparator Interface

42 Core Java | Muralidhar V


Comparable and comparator

 Objects in applications do appear in collections


 Object collections in application may need sorting /ordering
 The equal method of the Object class does not help in comparing the objects
 To provide for ordering/sorting of the objects Java API provides two interfaces
Comparable and Comparator
– Comparable interface is in java.lang
– Comparator interface is in java.util

43 Core Java | Muralidhar V


Implementing comparable interface

public class Student implements Comparable {

public Student(String name, int score) {...}

public int compareTo(Object o)


throws ClassCastException {...}

public static void main(String args[]) {...}


}

44 Core Java | Muralidhar V


Constructor for students

 This is the same for both methods—nothing new here


– public Student(String name, int score) {
this.name = name;
this.score = score;
}
 Sorting students according to their score
 Comparisons happen between two objects
 Whatever kind of collection they may or may not be in

45 Core Java | Muralidhar V


The main method: Version 1

public static void main(String args[]) {


TreeSet<Student> set = new TreeSet<Student>();

set.add(new Student("Ann", 87));


set.add(new Student("Bob", 83));
set.add(new Student("Cat", 99));
set.add(new Student("Dan", 25));
set.add(new Student("Eve", 76));

Iterator<Student> iter = set.iterator();


while (iter.hasNext()) {
Student s = iter.next();
System.out.println(s.name + " " + s.score);
}
}

46 Core Java | Muralidhar V


Using the Treeset

 In the main method we have the line


– TreeSet set = new TreeSet();
 Later we use an iterator to print out the values in order, and get the following
result:
– Dan 25
– Eve 76
– Bob 83
– Ann 87
– Cat 99
 How did the iterator know that it should sort Students by score, rather than,
say, by name?

47 Core Java | Muralidhar V


Implementing comparable <T>

 public class Student implements Comparable


 This means it must implement the method
public int compareTo(Object o)
 Notice that the parameter is an Object
 In order to implement this interface, our parameter must also be an Object,
even if that’s not what we want
 public int compareTo(Object o) throws ClassCastException {
if (o instanceof Student)
return score - ((Student)o).score;
else
throw new ClassCastException("Not a Student!");
}
 A ClassCastException should be thrown if we are given a non-Student
parameter
48 Core Java | Muralidhar V
An improved method

 Since casting an arbitrary Object to a Student may throw a


classCastException for us, we don’t need to throw it explicitly:

– public int compareTo(Object o) throws ClassCastException {


return score - ((Student)o).score;
}

 Moreover, since classCastException is a subclass of RuntimeException, we


don’t even need to declare that we might throw one:

– public int compareTo(Object o) {


return score - ((Student)o).score;
}

49 Core Java | Muralidhar V


Using a separate comparator

 In the program just finished, Student implemented Comparable


– Students were sorted only by their score
– If students are to be sorted another way, such as by name its not possible
– Because there can be only one method of same signature
 The problem is solved by placing comparison method in a separate class that
implements Comparator instead of Comparable
– Comparator can be used provide sorting by more than one variable
– Comparator requires a definition of compare and equal methods
–  int compare (T object1, T object2)
– Compares its two arguments for order
– boolean equals(Object obj)
Indicates whether some other object is "equal to" this comparator.

50 Core Java | Muralidhar V


Outline of student comparator

import java.util.*;
public class StudentComparator
implements Comparator<Student> {
public int compare(Student s1, Student s2) {...}
public boolean equals(Object o1) {...}
}

 Note: When we are using this Comparator, we don’t need the compareTo
method in the Student class
 Because of generics, our compare method can take Student arguments
instead of just Object arguments

51 Core Java | Muralidhar V


The compare method

public int compare(Student s1, Student s2) {


return s1.score – s2.score;
}

 This differs from compareTo(Object o) in Comparable in these ways:


 The name is different
 It takes both objects as parameters, not just one
 We have to either use generics, or check the type of both objects
 If our parameters are Objects, they have to be cast to Students

52 Core Java | Muralidhar V


The somecomparator.equals method

 Ignore this method!


– This method is not used to compare two Students—it is used to compare two
Comparators
– Even though it’s part of the Comparator interface, you don’t actually need to
override it
 Implementing an interface requires you to have a definition for every method in the
interface--so how can this be an exception?
 Because you do have a definition, inherited from Object !
– In fact, it’s always safe to ignore this method
– The purpose is efficiency—you can replace one Comparator with an equal but
faster one

53 Core Java | Muralidhar V


The main method

 The main method is just like before, except that instead of


TreeSet<Student> set = new TreeSet<Student>();

 We have
Comparator<Student> comp = new StudentComparator();
TreeSet<Student> set = new TreeSet<Student>(comp);

54 Core Java | Muralidhar V


When to use each

 The Comparable interface is simpler and less work


– Your class implements Comparable
– You provide a public int compareTo(Object o) method
– Use no argument in your TreeSet or TreeMap constructor
– You will use the same comparison method every time
 The Comparator interface is more flexible but slightly more work
– Create as many different classes that implement Comparator as you like
– You can sort the TreeSet or TreeMap differently with each
 Construct TreeSet or TreeMap using the comparator you want
– For example, sort Students by score or by name

55 Core Java | Muralidhar V


Sorting differently

 Suppose you have students sorted by score, in a TreeSet you call


studentsByScore
 Now you want to sort them again, this time by name

 Comparator<Student> myStudentNameComparator =
new MyStudentNameComparator();

 TreeSet studentsByName =
new TreeSet(myStudentNameComparator);

 studentsByName.addAll(studentsByScore);

56 Core Java | Muralidhar V


Core Java

Java 1.5 Features

Core Java | Muralidhar V


57
Objectives

After completion of this module, you should be able to:


 Explain generic classes
 Understand new approach to loops – for / in statements
 Define static imports
 Define arrays, string builder, queues and overriding return type
 Describe annotation
 Explain output formatting – format() and printf()
 Understand autoboxing of primitive types and enumerated types
 Variable length of arguments

58 Core Java | Muralidhar V


Java 1.5 Features: Agenda

 Generic classes
 New approach to loops – for / in statements
 Static imports
 Arrays, string builder, queues and overriding return type
 Annotation
 Output formatting – format() and printf()
 Autoboxing of primitive types
 Enumerated types
 Variable length of arguments

59 Core Java | Muralidhar V


Generic classes

 Similar in usage to C++ templates, but do NOT generate code for each
implementation
 Ensure stored/retrieved type of objects
 Check done at compile-time – avoid nasty casting surprises during runtime
 Generics are removed from compiled classes – backward compatilibity, no
additional code
 Can be used in legacy code to check for place where incorrect type is inserted
 Access to “template” class methods without casting

60 Core Java | Muralidhar V


Generics are type safe

 Big advantage: collections are now type safe


 For example, you can create a Stack that holds only Strings as follows:
– Stack<String> names = new Stack<String>();
 You can write methods that require a type-safe collection as follows:
– void printNames(Stack<String> names) {
 String nextName = names.pop(); // no casting needed!
 names.push("Hello"); // works just the same as before
 names.push(Color.RED); // compile-time error!

61 Core Java | Muralidhar V


What generics are and aren’t
 You can almost think of generics as defining new types--for example a
Stack<String> is a stack of strings
 In Java 1.4,
– String s = myStack.pop(); will not compile
– String s = (String)myStack.pop(); compiles, with runtime check
– myStack.push(Color.RED); compiles with no complaint
 In Java 5, String s = myStack.pop();
– Compiles with no runtime check if myStack was declared as Stack<String>
– Does not compile if myStack was declared any other way
– myStack.push(Color.RED); is a compiler error (= syntax error)
 However, generics are instructions to the compiler only
– You can still say: if (thing instanceof Stack) ...
but you cannot say: if (thing instanceof Stack<String>) ...
– This is called erasure--the type information is “erased” at runtime
62 Core Java | Muralidhar V
A closer look at generic type safety

 Type safe? Only sort of...


– Stack<Integer> stack1 = new Stack<Integer>();
– Stack stack2 = stack1; // stack2 is alias of stack1
– stack2.push(Color.RED);// legal--stack2 is a plain stack
– Integer xxx = stack1.pop(); // ClassCastException !

 A little more explanation...


– Java 5 is upwardly compatible with Java 1.4
– So old programs must continue to work
– Hence you can have non-generic stacks (and stack assignment)
– When you use a generic collection, you should make it generic everywhere, not just in the
places that Java would otherwise report an error
– Eclipse will provide warnings for many unsafe cases, so pay close attention to those
warnings!

63 Core Java | Muralidhar V


Iterators

 An iterator gives you every element of a collection, one at a time


 The collection has a type iterator(); factory method to return a new iterator to return
objects of the given type
 The method boolean hasNext() tells you if there are more objects
 The method type next() returns the next object
 The method void remove() deletes the last object gotten

 Example:
– Iterator iter = integerStack.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}

64 Core Java | Muralidhar V


Enhanced for loop

 Instead of
void cancelAll(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask tt = (TimerTask) i.next();
tt.cancel();
}
}
 You will be able to use:
void cancelAll(Collection<TimerTask> c) {
for (TimerTask task : c)
task.cancel();
}
 What does the JDK 1.5 compiler handle automatically for us?
 Not everyone likes this syntax! How else could it have been done?
 void cancelAll(Collection<TimerTask> c) {
foreach TimerTask task of c) //C# notation
task.cancel();
}
65 Core Java | Muralidhar V
Static import

 Enables one to refer to static constants from a class without needing to inherit
from it.
 If only used occasionally this technique is not very useful, but in complex
cases this technique help simplify coding.

66 Core Java | Muralidhar V


Example: Static import

// imports static members of package


import static java.lang.Math.ceil

// imports all static members of package


import static java.lang.Math.*

double x, y;
x = ceil(y); // can use method name directly

67 Core Java | Muralidhar V


Array class additions

 hashCode
– Returns a hash code based on the contents of the specified array.
– For any two arrays a and b such that Arrays.equals(a, b) is it also the case that
Arrays.hashCode(a) == Arrays.hashCode(b)
 deepEquals
– Returns true if the two specified arrays are deeply equal to one another.
 toString
– Returns a string representation of the contents of the specified array. String
representation is a list of the array’s elements, enclosed in square brackets (“[]”).
Adjacent elements separated by “, “

68 Core Java | Muralidhar V


StringBuilder

 An improvement upon StringBuffer


 Allows quicker concatenation of strings.
 Why use it?
– Creating new Strings in a loop can be inefficient because of the number new
objects that are created and discarded.
– StringBuilder.append(<type> <value>)
– StringBuilder.insert(<type> <value>)
 No synchronization! Not safe for use by multiple threads

69 Core Java | Muralidhar V


Interface queue

 Extends Collection
 Designed for holding elements prior to processing.
 Typically ordered in a FIFO manner.
 Main Methods
– remove() and pull()
 Both return the head of the queue.
 When empty, the remove() method throws an exception while poll() returns null.

70 Core Java | Muralidhar V


Overriding Return Types (Covariant Return Types)

 Allows the user to have a method in inherited class with same signature as in
parent’s class but differing only in return types.
 Makes programs more readable and solves casting problem
class Shape
{
public Shape transform(int x, int y)
}

class Rectangle extends Shape


{
public Rectangle transform(int x, int y)
}

71 Core Java | Muralidhar V


Annotations

 Add annotations (metadata) using @


– Annotate types, methods, fields for documentation, code generation, runtime services
– Provides built-in & custom annotations
 @Target, @Overrides, @Documented…
– Can control availability of annotations
 Source code, class file, runtime in JVM

 Example
/* @author Jack */
public final class AnnotationsTest {
@Overrides
public String toString(int i) { return “ x “ };
}

72 Core Java | Muralidhar V


Output formatting -printf().

 Most of the common C printf formatters are available.


 For example:
System.out.printf("Hello:%s%n", name);
System.out.printf("Number of group members:%3d%n", num);

 In addition, some Java classes like Date and BigInteger also have formatting
rules. See the java.util.Formatter class for more information.

73 Core Java | Muralidhar V


Autoboxing of primitive types

 Before
 ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();

 5.0 version:
 ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);

74 Core Java | Muralidhar V


Autoboxing

 Java distinguishes between primitive types and Objects


– Primitive types, i.e., int, double, are compact, support arithmetic operators
– Object classes (Integer, Double) have more methods: Integer.toString()
– You need a “wrapper” to use Object methods:
Integer ii = new Integer( i ); ii.hashCode()
– Similarly, you need to “unwrap” an Object to use primitive operation
int j = ii.intValue() * 7;
 Java 1.5 makes this automatic:
– Before:
– ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();
– After:
– ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
75 Core Java | Muralidhar V
Enumerations

 An enumeration, or “enum,” is simply a set of constants to represent various


values
 Here’s the old way of doing it:
 public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;
 This is a nuisance, and is error prone as well
 Here’s the new way of doing it:
 enum Season { winter, spring, summer, fall }

76 Core Java | Muralidhar V


Enumerated Types

 Similar to enum types in C, Pascal etc. and HashTable, keyset


 Enums are classes, extends java.lang.Enum
 Enums are final, can’t be subclassed.
 Only one Constructor and is protected.
 Implement java.lang.Comparable: compareTo()
 Implement Serializable

77 Core Java | Muralidhar V


Advantages of the new enum?

 They provide compile-time type safety


– int enums don't provide any type safety at all
 They provide a proper name space for the enumerated type
– With int enums you have to prefix the constants to get any semblance of a name
space.
 They're robust
– int enums are compiled into clients, and you have to recompile clients if you add,
remove, or reorder constants.
 Printed values are informative
– If you print an int enum you just see a number.
 Because they're objects, you can put them in collections.
 Because they're essentially classes, you can add arbitrary fields and methods
78 Core Java | Muralidhar V
Formatted output

 Similar to C/C++ printf and scanf:


– System.out.printf("name count%n"); //newline
– System.out.printf("%s %5d%n", user,total);
 See the java.util.Formatter class for more information
 Supports formats for dates, etc:
– System.out.format("Local time: %tT",
– Calendar.getInstance()); // -> "Local time: 13:34:18"
 Like C's sprintf(3), Strings may be formatted using String.format:
– import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;
Calendar c = new GregorianCalendar(1995, MAY, 23); String s =
String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

79 Core Java | Muralidhar V


Varargs

 Allows an unlimited number of parameters for a method


 The parameters must all be the same type (can be Object though)
 You can mix varargs and regular arguments
 Varargs must be the last argument
 Varargs are never null

80 Core Java | Muralidhar V


Example: Vararg

public void myMethod(String... args) {


for (int i = 0; i < args.length; i++) {
System.out.println(“The value at position “ + i + “ is “
+ args[i]);
}
}
Same as:
public void myMethod(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(“The value at position “ + i + “ is “
+ args[i]);
}
}

81 Core Java | Muralidhar V


Example: Vararg

myMethod(“a”);
myMethod(“a”, “b”, “c”, “d”, “e”);
myMethod();

Easier than writing:


myMethod(new String[]{“a”, “b”, “c”, “d”, “e”});

82 Core Java | Muralidhar V


More varargs

public void myMixedMethod(int age, String name, Address


address, String... aliases) {
}

myMixedMethod(42, “Kokila Rani”, address, “Hello Java”,


“B”, “VoidMain”);
myMixedMethod(42, “Mohua Dey”, address);

83 Core Java | Muralidhar V


More varargs (continued)

 The only use we found for varargs to date is for testing


 It is only a 15 character savings and minimal readability savings
 Java has added printf type functionality to the JDK that uses varargs

String.format(“Your test average is %5.2f”, average);

84 Core Java | Muralidhar V


Scanner class

 Provides basic input functionality for reading data from system console or any
data stream
 Following example reads a String from standard input and expects a following
int value:
 Scanner s=Scanner.create(System.in);
String param= s.next();
int value=s.nextInt();
s.close();
– Scanner methods next and nextInt block if no data is available
– Supports regular expression based search
 To process more complex input, pattern matching algorithms are available
from class java.util.Formatter

85 Core Java | Muralidhar V


Methods of Java.util.Scanner

 Finally, Java has a fairly simple way to read input


– Scanner sc = Scanner.create(System.in);
– boolean b = sc.nextBoolean();
– byte by = sc.nextByte();
– short sh= sc.nextShort();
– Int i = sc.nextInt();
– long l = sc.nextLong();
– float f = sc.nextFloat();
– double d = sc.nextDouble();
– String s = sc.nextLine();
 By default, whitespace acts as a delimiter, but you can define other delimiters
with regular expressions
86 Core Java | Muralidhar V
Additional features

 Threading
– There are many new features for controlling synchronization and threading which
increase performance and prevent that you have to write synchronization
primitives yourself.
 Monitoring and Profiling API
– It is now easier to observe what's going on inside the JVM
 Unicode 4.0
 RMI
– rmicis no longer needed to generate stubs/skeletons.
 New skin for Swing

87 Core Java | Muralidhar V


Reference

 Java 5 Tiger
http://java.sun.com/j2se/1.5.0/
 Complete docs
http://java.sun.com/j2se/1.5.0/docs/index.html
 New (fancy) features
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
 Nice and short article about features
http://www.winplanet.com/article/2574-3801.htm

88 Core Java | Muralidhar V


Core Java

Exceptions and Error Handling

89 Core Java | Muralidhar V


Objectives

After completion of this module, you should be able to:


 Explain exceptions.
 Define uses, types, and categories of exceptions.
 Identify the various types of exceptions in Java
 Implement exception handling using try, catch, throws, throw and finally
clauses
 Describe exception propagation and implement user-defined exceptions

90 Core Java | Muralidhar V


Exceptions and Error Handling: Agenda

 Why Use Exceptions


 About Exceptions
 Uses of Exceptions
 Types of Errors
 Categories of Exceptions
 Identify the various types of exceptions in Java
 Implementing Exception Handling using try, catch, throws, throw and finally
clauses .
 Exception Propagation
 Implement user-defined exceptions

91 Core Java | Muralidhar V


Why Use Exceptions

 In earlier programming language, the things that leads to confusion


– Error Detection
– Error Reporting
Take an
– Error Handling Example of
reading an entire
file into memory

92 Core Java | Muralidhar V


Why Use Exceptions (continued)

Steps To Be
readFile Followed For
{ Reading a File
in the memory
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}

93 Core Java | Muralidhar V


Why Use Exceptions (continued)

Can U Guess
the potential
Errors in this
operation

 What happens if the file can't be opened?


 What happens if the length of the file can't be determined?
 What happens if enough memory can't be allocated?
 What happens if the read fails?
 What happens if the file can't be closed?

94 Core Java | Muralidhar V


Why Use Exceptions (continued)

close the file;


errorCodeType read the file into memory;
if (theFileDidntClose && errorCode == 0)
if (readFailed)
readFile To{ Answer this question {errorCode = -4;
{ your program should have }
errorCode = -1;
}
initialize errorCode = 0; error
}
detection, reporting, else
{

open the file;


and handling mechanism errorCode = errorCode and -4;
else
{
thaterrorCode
will =look
-2; like: }
if (theFileIsOpen) }
}
else
{ } {
else
determine the length of the file; {
errorCode = -5;
}
if (gotTheFileLength) errorCode = -3;
}
return errorCode;
}
{
allocate that much memory;
if (gotEnoughMemory)
{

95 Core Java | Muralidhar V


Why Use Exceptions (continued)

Exception helps
readFile { To Solve this
catch
try { problem
(memoryAllocationFailed)
open the file; {
determine its size; doSomething;
allocate that much memory; }
read the file into memory; catch (readFailed)
close the file; {
}catch (fileOpenFailed) doSomething;
{ }
doSomething; catch (fileCloseFailed)
} {
catch(sizeDeterminationFailed) doSomething;
{ }
doSomething; }
}
96 Core Java | Muralidhar V
What is exception?

An exception can be defined as an abnormal event that occurs during


program execution and disrupts the normal flow of instructions.

97 Core Java | Muralidhar V


Uses of exception

 Consistent error reporting style.


 Easy to pass errors up the stack.
 Pinpoint errors better in stack trace.
– As long as you “fail fast” and throw as soon as you find a problem.
 Wrap useful information up in your exception classes, use that information
later when handling the exception.
 Exceptions don’t always have to be errors, maybe your program can cope
with the exception and keep going!
 Separating error handling code from Regular code.

98 Core Java | Muralidhar V


Types of errors

1. Compile Time Error

2. Run Time Error

99 Core Java | Muralidhar V


Exception occurrence reason

1. Running out of memory.

2. Resource allocation errors.

3. Inability to find files.

4. Problem in network connectivity.

100 Core Java | Muralidhar V


Exception occurrence levels

 Hardware/operating system level.


– Arithmetic exceptions; divide by 0, under/overflow.
– Memory access violations; segment fault, stack over/underflow.
 Language level.
– Type conversion; illegal values, improper casts.
– Bounds violations; illegal array indices.
– Bad references; null pointers.
 Program level.
– User defined exceptions.

101 Core Java | Muralidhar V


Categories of exceptions

1. Built in Exceptions

1.a Checked Exceptions

1.b Unchecked Exceptions

2. User Defined Exceptions

102 Core Java | Muralidhar V


Checked exceptions

 Checked exceptions are so called because both the Java compiler and the
Java virtual machine check to make sure this rule is obeyed.
 The checked exceptions that a method may raise are part of the method's
signature.
 Every method that throws a checked exception must advertise it in the
throws clause in its method definition, and
 Every method that calls a method that advertises a checked exception must
either handle that exception (with try and catch) or must in turn advertise that
exception in its own throws clause.

103 Core Java | Muralidhar V


Unchecked exceptions

 Raised implicitly by system because of illegal execution of program.


 Do not need to announce the possibility of exception occurrence.
 When unchecked exception occurred, if programmer does not deal with it, it
would be processed by default exception handler.
 Throw-able is base class for Exception and Error class.

104 Core Java | Muralidhar V


Java exception hierarchy

Object

Throwable

Error Exception

Virtual
Machine Error RuntimeException …

105 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

(Checked Exceptions)
ArrayIndexOutOfBoundExceptio
n

(Unchecked Exceptions)

Occurs when an attempt is made to access an array element


beyond the index of the array.

106 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

(Checked Exceptions)

ArithmeticException
(Unchecked Exceptions)

Occurs when you make an arithmetic error, such as dividing


a number by zero.

107 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

(Checked Exceptions)
NumberFormat
Exception

(Unchecked Exceptions)

Occurs when you want to convert a string in an incorrect


format to a numeric format.

108 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

(Checked Exceptions)

NullPointerException
(Unchecked Exceptions)

Occurs when an application tries to use an object without


allocating memory to it or calls a method of a null object.

109 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

(Checked Exceptions)

ClassCastException
(Unchecked Exceptions)

Occurs when you assign a reference variable of a class to


an incompatible reference variable of another class.

110 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

(Checked Exceptions)
NoSuchMethod

Exception

(Unchecked Exceptions)

Occurs when you call a method that does not exist.

111 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

IOException
(Checked Exceptions)

(Unchecked Exceptions)

When performing IO operation.

112 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException ClassNotFound

Exception

(Checked Exceptions)

(Unchecked Exceptions)

Occurs when the Java run time system is unable to find the
class referred.

113 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException IllegalAccess

Exception

(Checked Exceptions)

(Unchecked Exceptions)

Occurs when you want to refer a class that is not


accessible.

114 Core Java | Muralidhar V


Java exception hierarchy (continued)

Exception

RuntimeException

InterruptedException
(Checked Exceptions)

(Unchecked Exceptions)

Thrown when a thread is waiting, sleeping, or otherwise


paused for a long time.

115 Core Java | Muralidhar V


Implementing exception handling

1. try

2. catch

3. throws

4. throw

5. finally

116 Core Java | Muralidhar V


Implementing exception handling

 Using try and catch statements


– The try block encloses the statements that might raise an exception within it and
defines the scope of the exception handlers associated with it.
– The catch block is used as an exception-handler. You enclose the code that you
want to monitor inside a try block to handle a run time error.

117 Core Java | Muralidhar V


Implementing exception handling using try and catch

try

{ Example
// Statements that cause an exception.

catch(ExceptionName obj)

// Error handling code.

118 Core Java | Muralidhar V


Implementing exception handling continued

public class UnitRate


{
public void calculatePerUnitRate() Arithmetic error occurred and
{ passed to exception handler i.e.
int qty=20, rate=0,punit=0;
try
{
punit=qty/rate;
}catch(ArithmeticException ae)
{ System.out.println(“The product rate cannot be Zero, So Per Unit Rate
Displayed Below is Invalid ”);
}
System.out.println(“The Per Unit Rate is = “+punit);
}
}
119 Core Java | Muralidhar V
Using multiple catch statement/blocks

 A single try block can have zero, one or many catch blocks.
 The multiple catch blocks generate unreachable code error.
 If the first catch block contains the Exception class object then the
subsequent catch blocks are never executed. If this happen it is known as
unreachable code problem.
 To avoid unreachable code error, the last catch block in multiple catch blocks
must contain the Exception class object.

120 Core Java | Muralidhar V


Example: Using multiple catch statement/blocks

try {
// dangerous code here!
}
Order Matters!
catch(ArithmeticException e) { Less general
// Specific error handling here first!
}
catch(RuntimeException e) {
// More general error handling here
}

121 Core Java | Muralidhar V


Using finally clause

• The finally block is used to process certain statements, no matter


whether an exception is raised or not.

try
Syntax of
{ finally block
// Block of code
}
finally
{
// Block of code that is always executed
irrespective of an exception being raised or
not.
}
122 Core Java | Muralidhar V
Try-catch-finally statement

try {
// …
} catch (ExceptionType1 identifier) {
// …
} catch (ExceptionType2 identifier) {
// …
} finally {
// …
}

123 Core Java | Muralidhar V


Throwing an exception

 The throw statement causes termination of the normal flow of control of the
Java code and stops the execution of the subsequent statements if an
exception is thrown when the throw statement is executed.

 The throw clause transfers the control to the nearest catch block handling
the type of exception object throws.

 The following syntax shows how to declare the throw statement:

 throw ThrowableObj
public double divide(int dividend, int divisor) throws ArithmeticException {
if(divisor == 0) {
throw new ArithmeticException(“Divide by 0 error”);
}
return dividend / divisor;
}
124 Core Java | Muralidhar V
Using throws exceptions

 The throws statement is used by a method to specify the types of


exceptions the method throws.

 If a method is capable of raising an exception that it does not handle, the


method must specify that the exception has to be handled by the calling
method.

 This is done using the throws statement.

[modifiers] returntype methodName(params) throws e1, ... ,en { }

void readData() throws IOException

125 Core Java | Muralidhar V


Exception propagation
1. public class UnitRate {
2. void calculatePerUnitRate() {
3. int qty = 25, rate = 0,punit=0; ArithmeticException Occurred

4. punit = qty / rate;


5. }
6. void callPerUnitRate() {
7. calculatePerUnitRate(); Output by Default Exception
Handler
8. }
9. public static void main(String[] args) {
10. UnitRate ur = new UnitRate();
java.lang.ArithmeticException: / by zero
11. ur.callPerUnitRate();
at UnitRate.calculatePerUnitRate(UnitRate.java:4)
12. }
at UnitRate.callPerUnitRate(UnitRate.java:7)
13. }
at UnitRate.main(UnitRate.java:11)
126 Core Java | Muralidhar V
Exercise: Exception propagation

1. public class ExerciseException {


2. public static void main(String[] args) {
3. try {
4. happy1();
Write down the
5. }
Print Stack Trace
6. catch(Exception e) {
for the
7. e.printStackTrace();
ExerciseException
8. }
class
9. }
10. public static void happy1() throws Exception {
11. happy2();
12. }
13. public static void happy2() throws Exception {
14. happy3();
15. }
16. public static void happy3() throws Exception {
17. throw new Exception(“Be Happy Exception Prevents U!");
18. }
19. }
127 Core Java | Muralidhar V
User defined exceptions: Creating your own exceptions

 Defining your own exceptions let you handle specific exceptions that are
tailor-made for your application.
 Steps to Create a User Defined Exception
– Create a class that extend from a right kind of class from the
Exception Hierarchy.
– Let’s make a DivideByZeroException for use by our UnitRate class.

128 Core Java | Muralidhar V


User defined exceptions (continued)

public class DivideByZeroException extends ArithmeticException


{
public DivideByZeroException()
{
super("Divide by 0 error");
}
}

Here we extended
ArithmeticException.

129 Core Java | Muralidhar V


Summary

 Errors can be broadly categorized into two groups on the basis of whether the
compiler is able to handle the error or not, such as compile time errors and run
time errors.
 An exception is a run time error that can be defined as an abnormal event that
occurs during the execution of a program and disrupts the normal flow of
instructions.
 In Java, the Throwable class is the superclass of all the exception classes. It is
the class at the top position in the exception class hierarchy. The Exception class
and the Error class are two direct subclasses of the Throwable class.
 The built-in exceptions in Java are divided into two types on the basis of the
conditions where the exception is raised:
– Checked Exceptions or Compiler-enforced Exceptions
– Unchecked exceptions or Runtime Exceptions

130 Core Java | Muralidhar V


Assertion

 An assertion is a statement in the JavaTM programming language that


enables test the assumptions about program.
 Each assertion contains a boolean expression that is assumed to be true.
When execyted if the boolean expression is false, the system will throw an
error.
 Writing assertions while programming is one of the quickest and most
effective ways to detect and correct bugs. As an added benefit, assertions
serve as internal documentation, thus enhancing maintainability.

131 Core Java | Muralidhar V


Assertion (continued)

 The assertion statement has two forms.


 assert Expression1 ;

where Expression1 is a boolean expression. When the system runs the assertion, it
evaluates Expression1 and if it is false throws an AssertionError with no detail
message.
 assert Expression1 : Expression2 ;
– Where Expression1 is a boolean expression and Expression2 is an expression that
has a value. (It cannot be an invocation of a method that is declared void.)
– This form of asssert statement provides a detail message for the AssertionError. The
system passes the value of Expression2 to the appropriate AssertionError constructor,
which uses the string representation of the value as the error's detail message.
 Like all uncaught exceptions, assertion failures are generally labeled in the stack
trace with the file and line number from which they were thrown.

132 Core Java | Muralidhar V


Compilation: Enabling & disabling of assertions

 In order for the javac compiler to accept code containing assertions, you must
compile the code with the following
 javac -source 1.4 MyClass.java
 To enable assertions use -enableassertions, or -ea, option at runtime. To
disable assertions use -disableassertions, or -da. Specify the granularity with
the arguments provided at runtime.
– no arguments - Enables or disables assertions in all classes except system classes.
– packageName -   Enables or disables assertions in the named package and any
subpackages.
– …   - Enables or disables assertions in the unnamed package in the current working
directory.
– className -    Enables or disables assertions in the named class

133 Core Java | Muralidhar V


Summary (continued)

 You can handle exception using


– try
– catch
– throws
– throw
– finally
 You use multiple catch blocks to throw more than one type of exception.
 The finally clause is used to execute the statements that need to be executed
whether or not an exception has been thrown.
 The throw statement causes termination of the normal flow of control of the
Java code and stops the execution of subsequent statements after the throw
statement.
 The throws clause is used by a method to specify the types of exceptions the
method throws.
 You can create your own exception classes to handle the situations specific to
an application.

134 Core Java | Muralidhar V


Review questions

1. The two subclasses of the Throwable class are:


a. Exception class and Error class
b. Exception class and Object class
c. Error class and RunTimeException class
d. Exception class and RunTimeException class

2. The Throwable class is the sub class of _______ class.


a. Exception
b. Error
c. Object
d. RunTimeException

135 Core Java | Muralidhar V


Review questions (continued)

3. Which exception occurs when you try to create an object of


an abstract class or interface?
a. ClassNotFoundException

b. IllegalAccessException

c. InstantiationException

d. NoSuchMethodException

136 136 BasicJava - Day| Muralidhar


Core Java 3 V
Review questions (continued)

4. Consider the statements:


Statement A: The scope of the catch block is restricted to the
statements in the preceding try block only.
Statement B: A try block must have at least one catch block
that follows it immediately.

Which of the following options is true?

• Statement A is true and statement B is false


• Statement A is false and statement B is true
• Both, statements A and B, are true
• Both, statements A and B, are false

137 137 BasicJava - Day| Muralidhar


Core Java 3 V
Questions

138 Core Java | Muralidhar V


Summary

At the end of Day we see that you are now able to:
 Define collections
 Explain features of Java 1.5
 Describe exceptions as well as error handling

139 Core Java | Muralidhar V

You might also like