Professional Documents
Culture Documents
Pramod (Ansh)
Exception Handling
Pramod (Ansh)
Throwable
Exception
IOException
Error
RuntimeException
Pramod (Ansh)
Exception Handling
Three Categories Of Errors
Syntax Errors.
Logic Errors.
Runtime Errors.
Pramod (Ansh)
Exception Classes
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
VirtualMachineError
Error
AWTError
Pramod (Ansh)
System Errors
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
LinkageError
VirtualMachineError
Error
AWTError
Pramod (Ansh)
Exceptions
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
VirtualMachineError
Error
AWTError
Pramod (Ansh)
Keywords
Java supports exception handling with these keywords:
try,
throw and
catch.
Pramod (Ansh)
public class NoExceptionHandling
{
public static void main( String[] args )
{
int x = 1, y = 0, z = 0;
z = x / y;
System.out.println( x/y = + z );
}
Division by zero.
Pramod (Ansh)
public class HasExceptionHandling
{
public static void main( String[] args )
{
int x = 1, y = 0, z = 0;
try
{
z = x / y;
System.out.println( Not executed);
}
catch( Exception e )
{
System.out.println( Exception!);
}
System.out.println( x/y = + z );
Pramod (Ansh)
public class HasExceptionHandling
{
Any code you think might
public static
main(should
String[]
argsan)exception happens,
When
throw void
an exception
be
{
the remainder of the try
enclosed in a try block.
int x = 1, y = 0, z = 0;
block is abandoned. Variables
go out of scope. No return is
try
possible.
{
z = x / y;
System.out.println( Not executed);
}
catch( Exception e )
{
System.out.println( Exception!);
}
System.out.println( x/y = + z );
}
Every try block must be paired with at least one catch
}
blockoften more than one. The catch block will be
executed only if an exception occurs.
Pramod (Ansh)
public class HasExceptionHandling
{
public static void main( String[] args )
{
int x = 1, y = 0, z = 0;
try
{
z = x / y;
}
catch( NullPointerException npe )
{
System.out.println( Null Exception!);
}
catch( DivideByZeroException dbze )
{
System.out.println(
DivideByZeroException! + dbze.toString() );
}
Since the exception was caught, execution can resume.
System.out.println( Whoops! );
Pramod (Ansh)
The finally Block
Remember: if you use a try, then you must use
a catch .
The finally is optional .
Pramod (Ansh)
public class HasFinallyBlockToo
{
public static void main( String[] args )
{
int x = 1, y = 0, z = 0;
try
{
z = x / y;
}
catch( NullPointerException e )
{
System.out.println( Exception);
}
finally
Always, Always Always executes!
{
System.out.println( Always!);
}
Pramod (Ansh)
main method {
...
try {
...
invoke method1;
statement1;
}
catch (Exception1 ex1) {
Process ex1;
}
statement2;
}
method1 {
...
try {
...
invoke method2;
statement3;
}
catch (Exception2 ex2) {
Process ex2;
}
statement4;
}
method2 {
...
try {
...
invoke method3;
statement5;
}
catch (Exception3 ex3) {
Process ex3;
}
statement6;
}
An exception
is thrown in
method3
Pramod (Ansh)
class Simple{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Simple obj=new Simple();
obj.p();
System.out.println("normal flow...");
} }
Pramod (Ansh)
Throw Keyword
The throw keyword is used to explictily throw an
exception.
Throws Keyword
The throws keyword is used to declare an exception.
Pramod (Ansh)
class Itp{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to itp");
}
Pramod (Ansh)
class ThrowDemo1
{
static void play() throws Exception
{
System.out.println("before");
throw new IllegalAccessException("demo");
//System.out.println("after");
}
public static void main(String args[])
{
try
{
play();
}
catch(Exception e)
{
System.out.println("caught me: " +e);
}
}
Pramod (Ansh)
class ThrowDemo2
{
static void play()
{
try
{
System.out.println("before");
throw new IllegalAccessException("demo");
//System.out.println("after");
}
catch(Exception e)
{
System.out.println("Exception e"+e);
}
}
public static void main(String args[]) throws Exception
{
play();
}
}
Pramod (Ansh)
Thread
Pramod (Ansh)
Multitasking and Multithreading
Multitasking refers to a computer's ability to perform
multiple jobs concurrently
more than one program are running concurrently, e.g.,
UNIX
A thread is a single sequence of execution within a program
Multithreading refers to multiple threads of control within a
single program
each program can run multiple threads of control within
it, e.g., Web Browser
Pramod (Ansh)
Thread
Video Game
Process
video
networking
interaction
Pramod (Ansh)
Application Thread
When we execute an application:
The JVM creates a Thread object whose task is
defined by the main() method
It starts the thread
The thread executes the statements of the program
one by one until the method returns and the thread
dies
Pramod (Ansh)
Multiple Threads in an Application
Each thread has its private run-time stack
If two threads execute the same method, each will have
its own copy of the local variables the methods uses
However, all threads see the same dynamic memory
(heap)
Two different threads can act on the same object and
same static fields concurrently
Pramod (Ansh)
Creating Threads
There are two ways to create our own Thread
object
1. Subclassing the Thread class and instantiating a
new object of that class
2. Implementing the Runnable interface
Pramod (Ansh)
public class MyThread extends Thread
{
public MyThread( String n )
{
super( n );
System.out.println( MyThread Constructor );
}
public void run()
{
System.out.println( In run!\n );
}
}
public class TestMyThread
{
public static void main( String[] args )
{
main() will instantiate and start() all these threads. After they
have
} started, the methods immediately return and the thread main()
dies. However the entire application doesnt die until the last thread
does.
Pramod (Ansh)
class NewThread implements Runnable {
Thread t;
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run() {
System.out.println("Exiting child thread.");
}
}
class ThreadDemo1 {
public static void main(String args[]) {
new NewThread();
System.out.println("Main thread );
}}
Pramod (Ansh)
void start()
Thread Methods
void run()
The new thread beg
ins its life inside this method
sleep()
During this sleep time the thread does not use any
resources of the processor.
Pramod (Ansh)
Pramod (Ansh)
Synchronization
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() { c++; }
public synchronized void decrement() { c--; }
public synchronized int value() { return c; }
}
The synchronized keyword on a method means that if this is already locked
anywhere
(on this method or elsewhere) by another thread,
we need to wait till this is unlocked before entering the method
Reentrant
is allowed
Pramod (Ansh)
Thread Methods
wait() and notify():
suspend() and resume():
join():
yield():
Pramod (Ansh)
FILE HANDLING
(I/O STREAMS)
Pramod (Ansh)
Files and Streams: definition
Filesthese exist on a local file system
Streamsthese represent a stream of characters
coming from some location.
Pramod (Ansh)
Files and Streams
Before you can read from a file, you must open it.
After you are done reading from a file, you must close
it.
There are two common varieties of reading:
reading characters ( a character is 16 bits long)
reading bytes ( a byte is 8 bits long)
Pramod (Ansh)
Reading Characters
Pramod (Ansh)
Reading Characters
When we say we want to read characters, it means we never
want to move things like images.
Each of the bubbles in the list below represents a Java class that
is designed to read a certain type of character. Each of these is
designed for a particular case.
Pramod (Ansh)
Writing Characters
Pramod (Ansh)
Writing Characters
When we are writing characters, the same idea applies.
Each of the bubbles in the list below represents a Java class that is
designed to write a certain type of character. Each of these is
designed for a particular case.
Pramod (Ansh)
Reading Bytes
Pramod (Ansh)
Reading Bytes
Below is the list of classes you use when you want to
read at a finer grain than just characters. That would
be bytes.
Pramod (Ansh)
Writing Bytes
Pramod (Ansh)
Writing Bytes
Below is the list of classes you use when you want to
write bytes.
Pramod (Ansh)
For Input
Pramod (Ansh)
import java.io.*;
class fio
{
public static void fi()throws IOException
{ String s;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter any String");
s=br.readLine();
Pramod (Ansh)
For Output
Pramod (Ansh)
public static void fo()throws IOException
{
FileInputStream fis=new FileInputStream("savefio.txt");
DataInputStream dis=new DataInputStream(fis);
while(dis.available()!=0)
{
System.out.println(dis.readLine());
}
}
Pramod (Ansh)
Pramod (Ansh)
public static void app()throws IOException
{
String s;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter any String");
s=br.readLine();
FileOutputStream fos=new FileOutputStream("savefio.txt",true);
PrintStream ps=new PrintStream(fos);
ps.println(s);
ps.close();
Pramod (Ansh)
Collection
Pramod (Ansh)
What is the Collections framework?
Collections framework provides two things:
implementations of common high-level data structures: e.g. Maps, Sets, Lists,
etc.
An organized class hierarchy with rules/formality for adding new
implementations
Pramod (Ansh)
Definition of collection
A collection sometimes called a container is
simply an object that groups multiple elements into a
single unit.
Collections are used to store, retrieve, manipulate, and
communicate aggregate data.
Pramod (Ansh)
History
Pre Java SDK1.2, Java provided a handful of data
structures:
Hashtable
Vector
Bitset
These were for the most part good and easy to use, but
they were not organized into a more general framework.
SDK1.2 added the larger skeleton which organizes a
much more general set of data structures.
Legacy datastructures retrofitted to new model.
Generic types/autoboxing added in 1.5
Pramod (Ansh)
Collections-related Interface hierarchy
Collection
List
Set
Map
Iterator
SortedMap
ListIterator
SortedSet
The Collection inteface stores groups of Objects, with duplicates
allowed
The Set interface extends Collection but forbids duplicates
The List interface extends Collection, allows duplicates,
and introduces positional indexing.
Map is a separate hierarchy
Pramod (Ansh)
Collections Interface and Classes
Pramod (Ansh)
Array
Most efficient way to hold references to objects.
data
index
Car Car
0
Car
2
Car
4
Advantages
array know the type it holds, i.e., compile-time type checking.
array know its size, i.e., ask for the length.
array can hold primitive types directly.
Disadvantages
An array can only hold one type of objects (including primitives).
Arrays are fixed size.
Pramod (Ansh)
Array, Example
class Car{};
Car[] cars1;
Car[] cars2 = new Car[10];
// Aggregated initialization
Car[] cars3 = {new Car(), new Car(), new Car(), new Car()};
cars1 = {new Car(), new Car(), new Car()};
Pramod (Ansh)
Pramod (Ansh)
List
Set
Map
ArrayList
HashSet
HashMap
Vector
TreeSet
Hashtable
LinkedList
LinkedHashSet TreeMap
LinkedHashMap
Queue
PriorityQueue
Utility
Collections
Arrays
Pramod (Ansh)
Collection
List - List of things, it care about index of the object.
Set - Unique things, no duplicate allowed
Map - Things with a unique id(key)
Queue - Things arranged by the order in which they
are to be processed.
Pramod (Ansh)
ArrayList and LinkedList Classes
The classes ArrayList and LinkedList implement the List interface.
ArrayList is an array based implementation where elements can be
accessed directly via the get and set methods.
Default choice for simple sequence.
LinkedList is based on a double linked list
Gives better performance on add and remove compared to
ArrayList.
Gives poorer performance on get and set methods compared
ArrayList.
Pramod (Ansh)
Syntax of ArrayList, Vector and LinkedList
List
Create
Add
Traverse
ArrayList
ArrayList
name=new
ArrayList();
name.add("name1"); name.get(0);
name.add("name2");
Vector
Vector name=new
Vector(5);
same as above+
name.get(0);
name.addElement("n
ame1");
LinkedList
LinkedList
name=new
LinkedList(5);
Pramod (Ansh)
ArrayList, Example
import java.util.*;
class ITP{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add("Myzeal");
al.add("IT");
al.add("ITP");
for(Object obj:al)
System.out.println(obj);
}
}
Pramod (Ansh)
ArrayList Method
addAll
removeAll()
retainAll()
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add("Myzeal");
al.add("IT");
al.add("ITP");
ArrayList al2=new ArrayList();
al2.add(Ansh");
al2.add(Pramod");
al.addAll(al2);
for(Object obj:al)
System.out.println(obj);
}}
Pramod (Ansh)
LinkedList, Example
import java.util.*;
class ITP{
public static void main(String args[]){
LinkedList al=new LinkedList();
al.add("Myzeal");
al.add("IT");
al.add("ITP");
for(Object obj:al)
System.out.println(obj);
}
}
Pramod (Ansh)
Method of List
Pramod (Ansh)
void
boolean
boolean
boolean
void
boolean
Pramod (Ansh)
boolean
boolean
Object
int
int
boolean
Iterator
containsAll(Collection c)
Returns true if this list contains all of the elements of the specified collection.
equals(Object o)
Compares the specified object with this list for equality.
get(int index)
Returns the element at the specified position in this list.
hashCode()
Returns the hash code value for this list.
indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or
-1 if this list does not contain this element.
isEmpty()
Returns true if this list contains no elements.
iterator()
Returns an iterator over the elements in this list in proper sequence.
Pramod (Ansh)
int
lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element,
or -1 if this list does not contain this element.
ListIterator listIterator()
Returns a list iterator of the elements in this list (in proper sequence).
ListIterator listIterator(int index)
Returns a list iterator of the elements in this list (in proper sequence),
starting at the specified position in this list.
Object
remove(int index)
Removes the element at the specified position in this list (optional
operation).
boolean
remove(Object o)
Removes the first occurrence in this list of the specified element (optional
operation).
boolean
removeAll(Collection c)
Removes from this list all the elements that are contained in the specified
collection (optional operation).
Pramod (Ansh)
boolean
Object
int
List
Object[]
Object[]
retainAll(Collection c)
Retains only the elements in this list that are contained in the specified collection
(optional operation).
set(int index, Object element)
Replaces the element at the specified position in this list with the specified element
(optional operation).
size()
Returns the number of elements in this list.
subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive,
and toIndex, exclusive.
toArray()
Returns an array containing all of the elements in this list in proper sequence.
toArray(Object[] a)
Returns an array containing all of the elements in this list in proper sequence; the
runtime type of the returned array
is that of the specified array.
Pramod (Ansh)
Difference between ArrayList, Vector and LinkedList
ArrayList
Vector
LinkedList
ArrayList is a growable
array.
same as ArrayList.
Pramod (Ansh)
Collection: Iterator
ListIterator Interface is used to traverse the element in backward and
forward direction.
public boolean hasNext();
public Object next();
public boolean hasPrevious();
public Object previous();
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add("Myzeal");
al.add("IT");
al.add("ITP");
ListIterator itr=al.listIterator();
while(itr.hasNext()){
System.out.println(itr.next());
}}
}
Pramod (Ansh)
Set Interface
Set Interface also extends the Collection Interface. Set mean that it does
not allow duplicate element i.e it care about uniqueness. There are three
classes that implements Set interface
HashSet
TreeSet
LinkedHashSet
Pramod (Ansh)
HashSet and TreeSet implement the interface Set.
HashSet
Implemented using a hash table.
No ordering of elements.
add, remove, and contains methods constant time complexityO(c).
TreeSet
Implemented using a tree structure.
Guarantees ordering of elements.
add, remove, and contains methods logarithmic time complexity
O(log (n)), where n is the number of elements in the set.
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
HashSet al=new HashSet();
al.add("Myzeal");
al.add("IT");
al.add("Myzeal");
al.add("ITP");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
LinkedHashSet al=new LinkedHashSet();
al.add("Myzeal");
al.add("IT");
al.add("Myzeal");
al.add("ITP");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
TreeSet al=new TreeSet();
al.add("Myzeal");
al.add("IT");
al.add("Myzeal");
al.add("ITP");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }
Pramod (Ansh)
Method Of Set
Pramod (Ansh)
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.
Pramod (Ansh)
int
boolean
hashCode()
Returns the hash code value for this collection.
isEmpty()
Returns true if this collection contains no elements.
Iterator
iterator()
Returns an iterator over the elements in this collection.
boolean
remove(Object o)
Removes a single instance of the specified element from this collection, if it is
present (optional operation).
boolean
removeAll(Collection c)
Removes all this collection's elements that are also contained in the specified
collection (optional operation).
Pramod (Ansh)
boolean
int
retainAll(Collection c)
Retains only the elements in this collection that are contained in the
specified collection (optional operation).
size()
Returns the number of elements in this collection.
Object[]
toArray()
Returns an array containing all of the elements in this collection.
Object[]
toArray(Object[] a)
Returns an array containing all of the elements in this collection; the runtime
type of the returned array is that of the specified array.
Pramod (Ansh)
Difference between HashSet, TreeSet and LinkedHashSet
HashSet
TreeSet
LinkedHashSet
It is an Ordered
version of HashSet
and no duplicates.
It is heterogeneous.
It is homogeneous.
It is heterogeneous.
Pramod (Ansh)
Queue
public boolean add(object);
public boolean offer(object);
public remove();
public poll();
public element();
public peek();
Pramod (Ansh)
Map Interface
Map Interface also extends the Collection Interface. Map mean that it
cares about the unique identifier i.e Map maps the unique key(ID) to a
specific value.The Map implementation let do things like search value
based on the key. The Map interface is implemented by
HashMap
Hashtable
TreeMap
LinkedHashMap
Pramod (Ansh)
Pramod (Ansh)
Syntax of HashMap, Hashtable, TreeMap and LinkedHashMap
Map
Create
Add
Traverse
HashMap
name.put ("name1",
"Peter"); name.add
("name2", "James");
Hashtable
same as above
Enumeration e
=name.elements();
TreeMap
same as above
LinkedHashMap
same as above
Pramod (Ansh)
HashMap
A HashMap contains values based on the key. It
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
HashMap hm=new HashMap();
hm.put(100,"Myzeal");
hm.put(101,"IT");
hm.put(102,"ITP");
Set set=hm.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
} }}
Pramod (Ansh)
LinkedHashMap
A LinkedHashMap contains values based on the key. It
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
LinkedHashMap hm=new LinkedHashMap();
hm.put(100,"Myzeal");
hm.put(101,"IT");
hm.put(102,"ITP");
Set set=hm.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
} }}
Pramod (Ansh)
TreeMap
A TreeMap contains values based on the key. It
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
TreeMap hm=new TreeMap();
hm.put(100,"Myzeal");
hm.put(102,"IT");
hm.put(101,"ITP");
hm.put(103,"Training");
Set set=hm.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
} } }
Pramod (Ansh)
Hashtable
A Hashtable contains values based on the key. It
implements the Map interface and extends Dictionary
class.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
Pramod (Ansh)
import java.util.*;
class ITP{
public static void main(String args[]){
Hashtable hm=new Hashtable();
hm.put(100,"Myzeal");
hm.put(102,"IT");
hm.put(101,"ITP");
hm.put(103,"Training");
Set set=hm.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
}}}
Pramod (Ansh)
Method Of Map
Pramod (Ansh)
void
clear()
Removes all mappings from this map (optional operation).
Set
containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
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.
Object get(Object key)
Returns the value to which this map maps the specified key.
int
hashCode()
Returns the hash code value for this map.
Pramod (Ansh)
boolean
Set
Object
isEmpty()
Returns true if this map contains no key-value mappings.
keySet()
Returns a set view of the keys contained in this map.
put(Object key, Object value)
Associates the specified value with the specified key in this map (optional operation).
void
putAll(Map t)
Copies all of the mappings from the specified map to this map (optional operation).
Object
remove(Object key)
Removes the mapping for this key from this map if it is present (optional operation).
int
Collection
size()
Returns the number of key-value mappings in this map.
values()
Returns a collection view of the values contained in this map.
Pramod (Ansh)
HASHMAP VS LINKEDHASHMAP VS TREEMAP
HashMap does not maintain any particular order. In
other words there is no ordering on keys or values.
TreeMap sorts the keys in natural order.
LinkedHashMap preserves the insertion order.
Pramod (Ansh)
Difference between HashMap, Hashtable, TreeMap and LinkedHashMap
HashMap
Hashtable
A HashMap is
unsorted and
unordered Map.
A Hashtable is a
legacy class.
Inherit from
Inherit from Map.
SortedMap.But
fromJava 6 onwards
TreeMap implements
NavigableMap
TreeMap
LinkedHashMap
Pramod (Ansh)
Generics