Exception in Java (5)
Exception in Java (5)
Check
Abnormal
statement Exception
Present/not
Exception Handled
Continue
or not
Uncheck exception :-
Exception which are not known to the compiler are known as uncheck
exception
It is not mandatory to handle uncheck exception
EXCEPTION HIERARCHY:-
Whenever exception occur a throwable type object will be created which will be
having reason &stack trace of the exception
THROWABLE
ERROR EXCEPTION
Package exception;
Public class p2
{
P s v m(s[]args)
{
Thread.sleep(1000);//interepted exception
}}
FINALLY BLOCK:-
Finally block is used to execute mandatory statements in java
Finally block will be executed in following situation.
1. Exception not accur.
2. Exception accur not handled
3. Exception accur and it is handled
We can have finally block in following situation.
Try with finally try&catch with finally try&multiple catch with finally
Try try try
{ { {
} } }
Finally catch( ) catch( )
{ { {
} } }
Finally catch( )
{ {
} }
Finally
{
}
Package exception
Public class p1
{
Public `static void main (string [ ] args)
{
try
{
S.O.Pln(“welcome to app”);
S.O.Pln(“10/10”);
}
Catch(arithmeticexception e)
{
S.O.Pln(“zero not allowed:…!”);
}
Finally
{
S.O.Pln(“Thank for using App”);
}
}
Using throw keywords:-
Throws is the keywords which is used to declare the exception.
Throws must be used with method declaration only.
If a check exception is not handle using try& catch block it must be
declared using throw.
If the called method is throwing an exception calling method must
handle(or) declare same exception.
If the super class method is throwing an exception than the sub class over
riding method must also declare same exception (or) its super class.
We can throw n-number of exception .
SYNTAX:-
{
//stmt
}
package deepika;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
}
public static void ram()throws
FileNotFoundException {
System.out.println("ram begin");
sita();
System.out.println("ram end");
}
public static void sita()throws
FileNotFoundException{
System.out.println("sita begin");
FileOutputStream out = new FileOutputStream("C:\\
java\\demo.text");
System.out.println("sita end");
}
}
Custom Exception:-
Exception created by the user are known as user defined exception (or)
custom exception.
We can create custom exception using throw keyword .
Steps to crete custom exception .
Step1:-
Create a class and extend to end any of the exception class.
Step2:-
Create a class Exception object using throw keywords.
Note:-
If the created class Extending to check than it is behaves like checked
Exception .
If the created class is extending to unchecked exception then is behaves
liked checked Exeption
package encapsulation;
}
class employee
{
int eid;
String ename;
double sal;
public employee(int id,String ename,double
sal)
{
this.eid=eid;
this.ename=ename;
if(sal<0)
{
throw new salaryexception();
}
else
{
this.sal=sal;
}}}
class testemployee
{
public static void main(String[] args) {
employee e1=new
employee(1,"smith",10.25);
THROW THROWS
It is used to stop the execution of
program and create an except object It is used to declar the exceptions
System.out.println(e1);}
collection
Collection framework is a set of classes, interface, which provides mechanism
to store and manipulate group of objects
In collection we can achieve all the operations that you perform on a data such
as searching, sorting ,insertion ,manipulation and deletion etc…
Using collection framework we can store only objects (non primitive types).we
cannot store primitive types. If we try to store primitive types ,it will be
implicitly converted to non-primitive types(auto boxing)
index yes No no
retrieval 1.iterator 1.iterator() 1.iterator()
2.listiterator 2.foreach 2.foreach()
3.foreach
Implementing 1.arraylist 1.priority queue 1.hashset
class 2.linkedlist 2.Array deque 2.treeset
3.vector 3.linkedhashset
4.stack
List Interface:-
List interface is the child interface of collection interface
It inhibits a list type data structure in which we can store the ordered
collection of objects
It can have duplicate values
It also provides methods like
s.no purpose Method signature
1. Add an element 1.add(int index, object o)
2.addall(int index ,collection c)
2. Searching an element Index of (object o)
import java.util.ArrayList;
public class p2 {
public static void main(String[] args) {
ArrayList a1=new ArrayList();
a1.add(40);
a1.add(20);
a1.add(10);
a1.add(30);
System.out.println(a1);
//remove object
a1.remove(Integer.valueOf(20));
System.out.println(a1);
//remove (index int)
a1.remove(1);
System.out.println(a1);
}
}
ITERATOR LISTITERATOR
Note:
In the iterator when we try to access an element using only next() and
if there is no element present.
Then we get NosuchElementException
1)using iterator()
Iterator i=a1.iterator();
While(i.hasnext())
{
System.out.println(i.next()+” ,”);
}
i.next();//nosuchelementexception
2)using listiterator()
Listiterator is=a1.listiterator(a1.size());
While(is.hasprevious())
{
System.out.println(is.prevoius()+”,”);
3)using the for each loop
For(object o:a1)
{
System.out.println(o+”,”);
}
4)using get(index)
System.out.println(a1.get(2));
Note:
Collection can be classified into two types.
1.non-Generic collection
2.Generic collection
Parameter Non – Generic Generic collection
collection
Syntax Arraylist List=new Arraylist<ReferenceType>
Arraylist() list=new
Arraylist<ReferenceType>()
Elements Heterogenous Homogeneous elements
elements
Retrieval Individual type No typecasting is needed
casting needs to bo
done at every
retrieved
Compile – Time Checked for type Checked for type safety at
Checking safety at runtime compile time
Note :
1.sort(reference)
2.sort(reference, comparator type object)
import java.util.*;
public class p1
{
public static void main(String[] args)
{
List<String> sList = new ArrayList<String>();
sList.add("s");
sList.add("u");
sList.add("r");
sList.add("y");
sList.add("a");
Collections.sort(sList); //sorts array list
for(String str: sList)
System.out.print(" "+str);
}
}
Linked List:
LinkedList implements the collection interface
It user doubly linked list internally to store the elements
It can store the duplicate elements
It maintains the insertion order.
It is not synchronized.
In Linkedlist the manipulation is fast because no shifting is
required.
Vector:
Vector uses a dynamic array to store the data elements.
It is synchronized and contains many methods that are not the part of
collection framework.
It is a thread safe
It is similar to arraylist but is slow when compared to arraylist.
Stack :
The stack is the subclass of vector
It implements the last-in-first-out data structure
The stack contains all of the methods of vector class and also provides
its methods like
1. Push(object)add objects
2. Pop()to remove objects
3. Peek()to see top objects
Queue Interface:
The interface queue is available in the java.util.package
It is used to keep the elements that are processed in the First in First
out(FIFO) manner.
It is an ordered list of objects, where insertion of elements occurs at
the end of the list, and removal of elements occur at the beginning of
the list.
Implementing classes,
ArrayDeque
PiriorityQueue
LinkedList
Implementations done by these classes are not thread safe. It is
required to have a thread safe implementation class below class is an
available option.
1. PirorityBlockingQueue
Method Description
Booleanoffer(object) It is used to insert the specified
element into this queue.
Object remove() It is used to retrieves and removes the
head of this queue.
Object poll() It is used to retrieves and removes the
head of this queue, or returns null if
this queue is empty.
Object element() It is used to retrieves but does not
remove the head of this queue.
Object peek() It is used to retrieves, but does not
remove the head of this queue, or
returns null if this queue is empty.
ad.offer(20);
ad.offer(30);
ad.offer(10);
ad.offer(40);
System.out.println(ad);
while(!ad.isEmpty())
{
System.out.print(ad.poll()+",");
}
System.out.println();
PriorityQueue<Integer>pq=new PriorityQueue<>();
pq.offer(20);
pq.offer(30);
pq.offer(10);
pq.offer(40);
System.out.println(pq);
while(!pq.isEmpty());
{
System.out.print(pq.poll()+",");
}
}
}
Set interface:
The set interface is present in java.util.package
It is an unordered collection of objects.
Duplicates values cannot be stored .
This interface contains the methods inherited from the collections
interface and adds a feature that restricts the insertion of the duplicate
elements.
Implementing classes
HashSet
Linked HashSet
TreeSet
Hashset:
Implements set interface.
The underlying data structure for hashset is Hashtable.
As it implements the set interface duplicate values are not allowed.
Object that you insert in hashset are not guaranteed to be inserted in
the same order objects are inserted based on their hash code.
NULL elements are allowed in hashset.
Hashset also implements serializable and doneable interfaces.
Linked Hashset:
Duplicate value are not allowed
Null elements are allowed in linked Hashset.
It is non- synchronized
It maintains insertion order.
Treeset:
Duplicate values are not allowed
Elements are sorted by default in ascending order.
Null elements are not allowed in treeset
It is non – synchronized
We can sort the elements in customized order using comparator.
import java.util.*;
public class p1
{
hs.add(20);
hs.add(40);
hs.add(10);
hs.add(30);
System.out.println(hs);
TreeSet<Integer>ts=new TreeSet<>();
ts.add(20);
ts.add(40);
ts.add(10);
ts.add(30);
System.out.println(ts);
for(int n:ts)
System.out.print(n+",");
System.out.println();
Iterator<Integer>l=ts.descendingIterator();
while(l.hasNext())
{
System.out.print(l.next()+",");
}
}
}
Map:
The map interface is present in java.util.package
Map contains values on the basic of key, ie,key and value pair. Each
key and value pair is known as an entry.
Map doesn’t allow duplicate keys, but you can have duplicate values.
Map is useful if you have to search , update or delete elements on the
basics of a key.
Map can’t be traversed, so you need to convert it into set using key
set() or entry set() method.
You cannot store duplicate keys, however if you try to store duplicate
key with another value , it will replace the value.
Implementing classes of map interface
o Hashmap
o LinkedHashmap
o Treemap
o Hashtable
Method of map Interface
S.NO Method signature Purpose
1 Put(key,value) Add an entry to the map
Replace the add value with new
value of an existing entry in the
map.
2 Put All(Map) Copies all the entries from the
given map into current map
3 Contains Key(key) Check whether the key is present
or not and returns Boolean value.
4 Contains Value(value) Checks whether the value is
present or not and returns Boolean
value.
5 Remove(key) If the key is present entry is
removed from the map and the
value is returned
If the key is not present nothing is
removed and null is returned
6 Clear() It removes all the entries in the
map.
7 Get(key) It return the value for the specified
key from the map, if the key is not
present it will return null.
8 Isempty() To check whether the map has
mappings or not. The return type
of this method is Boolean.
9 Values() It returns a collection of values
present in the map collection <v>.
10 Key set() It returns a set of keys present in
the map return type set <key>
11 Entry set() It returns a set of the entries
present in the map return type is
set <key, value>
12 Size() It returns the size or number of
entries inside the map.
HashMap:
It contains only unique keys
It may have one null keyand multiple null values
It is non- synchronized
It maintains no order.
Linked HashMap:
It contains unique elements
It may have one null key and multiple null values
It is non- synchronized
It maintains insertion order
TreeMap:
it contains only unique elements
it cannot have a null key but can have multiple null values
it is non synchronized
it maintains ascending order
Hashtable:
It contains unique elements
It doesn’t allow null key or value
It is synchronized.
import java.util.*;
public class p1
{
public static void main(String[] args)
{
HashMap<Integer,String>hm=new HashMap<>();
hm.put(1, "sheela");
hm.put(2,"leela");
hm.put(3,"laila");
hm.put(4,"mala");
System.out.println(hm);
//to search key
System.out.println(hm.containsKey(3));
//to search value
System.out.println(hm.containsValue("mala"));
//to get the value using key
System.out.println(hm.get(3));
//to iterate keys
Set<Integer>keys=hm.keySet();
Iterator I1=keys.iterator();
while(I1.hasNext());
{
System.out.print(I1.next()+",");
}
System.out.println();
//to iterate values
Collection<String>values=hm.values();
Iterator I2=values.iterator();
while(I2.hasNext())
{
System.out.print(I2.next()+",");
}