Unit 3-Collections, Exception Handling and I - O
Unit 3-Collections, Exception Handling and I - O
autoboxing and unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as autoboxing and
vice-versa unboxing.
compareTo()
It compares two objects numerically and returns the result as -1, 0 or 1
parseInt()
It parses the String argument as a signed decimal Integer object.
parseFloat()
It parses the String argument as a Float object.
parseDouble()
It parses the String argument as a Double object.
parseLong()
It parses the String argument as a Long object.
parseByte()
It parses the String argument as a Byte object.
parseBoolean()
It parses the String argument as a Boolean object.
Collections in Java
Iterator interface provides the facility of iterating the elements in a forward direction only.
Iterator<T> iterator()
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.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
}System.out.println();}}
LinkedList
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+vec);
}
}
Stack
● The stack is the subclass of Vector.
● It implements the last-in-first-out data structure, i.e., Stack.
● The stack contains all of the methods of Vector class and also
provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.
import java.util.*;
public class StackExample{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Queue Interface
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
add(Element e) offer(Element e)
addAll(Collection<? extends E> c) offerFirst(Element e)
offerLast(Element e)
addFirst(Element e)
peek()
addLast(Element e) poll()
clear() pop()
clone() push(Element e)
contains(Obj) remove()
remove(Object o)
element()
removeAll(Collection<?> c)
getFirst() removeFirst()
getLast() removeFirstOccurrence(Object o)
isEmpty()
iterator() removeLast()
import java.util.*;
public class ArrayDequeExample{
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
for (String str : deque) {
System.out.println(str);
}
}
}
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents
the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most
one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
add(E e)
clear()
contains(Object o)
remove(Object o)
isEmpty()
size()
clone()
import java.util.*;
public class HashsetExample{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
} }
LinkedHashSet
● SortedSet is the alternate of Set interface that provides a total ordering on its
elements.
● The elements of the SortedSet are arranged in the increasing (ascending) order.
● The SortedSet provides the additional methods that inhibit the natural ordering of the
elements.
● The SortedSet can be instantiated as:
● Java TreeSet class implements the Set interface that uses a tree for storage.
● Like HashSet, TreeSet also contains unique elements.
● However, the access and retrieval time of TreeSet is quite fast.
● The elements in TreeSet stored in ascending order.
Methods of TreeSet
add(Object o)
addAll(Collection c)
Comparator comparator()
contains(Object o)
descendingIterator()
descendingSet()
first()
floor(E e)
headSet(Object toElement)
higher(E e)
lower(E e)
pollFirst()
pollLast()
remove(Object o)
import java.util.*;
public class TreesetExample{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
HashMap
Java HashMap class implements the Map interface which allows us to store key and value pair,
where keys should be unique. If you try to insert the duplicate key, it will replace the element of the
corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.
HashMap class is found in the java.util package.
V get(Object key)
V remove(Object key)
void clear()
boolean isEmpty()
int size()
Set<K> keySet()
Collection<V> values()
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Hashtable
Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such
exceptions to prevent abrupt termination of program. The term exception means exceptional
condition, it is a problem that may arise during the execution of program. A bunch of things can
lead to exceptions, including programmer error, hardware failures, files that need to be opened
Error:
Errors generally refer to more severe issues that occur at runtime or
compile-time and are usually outside the control of the program. They
indicate problems that the program can't easily recover from.
Exception class Hierarchy
Types of Exception
Exception are categorized into 3 category.
1. Checked Exception The exception that can be predicted by the
programmer.Example : File that need to be opened is not found. These type of
exceptions must be checked at compile time.
2. Unchecked Exception Unchecked exceptions are the class that extends
RuntimeException. Unchecked exception are ignored at compile time. Example :
ArithmeticException, NullPointerException, Array Index out of Bound
exception. Unchecked exceptions are checked at runtime.
3. Error Errors are typically ignored in code because you can rarely do anything
about an error. Example : if stack overflow occurs, an error will arise. This type
of error is not possible handle in code.
Exception Handling Mechanism
In java, exception handling is done using five keywords
1. try
2. catch
3. Throw
4. Throws
5. finally
try….catch
● Try is used to guard a block of code in which exception may occur.
● This block of code is called guarded region.
● A catch statement involves declaring the type of exception you are trying
to catch.
● If an exception occurs in guarded code, the catch block that follows the
try is checked, if the type of exception that occured is listed in the catch
block then the exception is handed over to the catch block which then
handles it.
class Excp
{
public static void main(String args[]) {
int a,b,c;
try {
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed"); } catch(ArithmeticException e)
{ System.out.println("Divided by zero"); }
System.out.println("After exception is handled");
}}
Multiple catch blocks:
A try block can be followed by multiple catch blocks. You can have any number
of catch blocks after a single try block.If an exception occurs in the guarded code
the exception is passed to the first catch block in the list. If the exception type of
exception, matches with the first catch block it gets caught, if not the exception is
passed down to the next catch block. This continue until the exception is caught
or falls through all catches.
class Excep
try {
int arr[]={1,2};
arr[2]=3/0;
} catch(ArithmeticException ae)
{ System.out.println("divide by zero");
} catch(ArrayIndexOutOfBoundsException e)
}}}
Nested try statement
● try statement can be nested inside another block of try.
● Nested try block is used when a part of a block may cause one error
while entire block may cause another error.
● In case if inner try block does not have a catch handler for a
particular exception then the outer try is checked for match.
class Excep
{ public static void main(String[] args) {
try {
int arr[]={5,0,1,2};
try {
int x=arr[3]/arr[1];
} catch(ArithmeticException ae)
{ System.out.println("divide by zero");
} arr[4]=3;
} catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("array index out of bound exception");
}}}
finally
● In Java, the finally keyword is used with try and catch blocks to ensure
that a block of code is executed regardless of whether an exception is
thrown or not.
● It is commonly used for code that needs to run after a try block, such as
closing resources (files, network connections, etc.) or performing cleanup
operations.
class Excp
{
public static void main(String args[]) {
int a,b,c;
try {
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed"); } catch(ArithmeticException e)
{ System.out.println("Divided by zero"); }
System.out.println("After exception is handled");
finally{System.out.println("Code is always executed”);}
}
}
throws
● The throws keyword is used for checked exceptions, which are exceptions that the
Java compiler requires to be either caught or declared in the method signature.
Checked exceptions are subclasses of Exception but not of RuntimeException.
● The throws clause is part of the method's signature. This means that if you override a
method, you must declare that it throws the same exceptions or subclasses of the
exceptions declared in the parent method's throws clause.
Creating Instance of Throwable class
There are two possible ways to get an instance of class Throwable,
1. Using a parameter in catch block.
2. Creating instance with new operator.
3. new NullPointerException("test");
This constructs an instance of NullPointerException with name test.
class Test{
static void check() throws ArithmeticException{
System.out.println("Inside check function");
throw new ArithmeticException("demo");}
public static void main(String args[]){
try{
check();}
catch(ArithmeticException e){
System.out.println("caught" + e);
}}}
throw Keyword
● throw keyword is used to throw an exception explicitly. Only object of Throwable
class or its sub classes can be thrown.
● Program execution stops on encountering throw statement, and the
● Syntax :
type method_name(parameter_list)throwsexception_list
class Test{
try{
catch(ArithmeticException e){
System.out.println("Exception caught");}}
avg();
}
User defined Exception
try {
checker.checkAge(age);
} catch( VotingException e) {
System.out.println(e.getMessage());
}
String class
String class is part of the java.lang package and is used to represent a sequence of
characters.
Strings in Java are immutable, which means once a String object is created, it cannot
be changed. Instead, operations on strings create new String objects.
Methods
1. int length()
2. boolean isEmpty()
3. char charAt(int index)
4. boolean contains(CharSequence sequence)
5. boolean equals(Object anObject)
6. boolean equalsIgnoreCase(String anotherString)
7. int indexOf(String str)
8. int lastIndexOf(String str)
9. String substring(int beginIndex)
10. String substring(int beginIndex, int endIndex)
11. String trim()
12. String toLowerCase()
13. String toUpperCase()
StringBuffer
sb.append(" World");
sb.append('!');
sb.delete(6, 17);
System.out.println("After delete: " + sb);
sb.reverse();
}
File Class
File class is part of the java.io package and provides an abstraction for files and
directories.
It allows you to work with files and directories on your filesystem, including
creating, deleting, and querying them.
canWrite()
canExecute()
canRead()
isFile()
getName()
listFiles()
import java. Io *;
class ReadTest{
public static void main(String[] args){
try{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null){
System.out.println(str);}
br.close();
fl.close();}
catch (IOException e)
{ e.printStackTrace(); }}
}
import java. Io *;
class WriteTest{
try{
fw.write(str);
fw.close();
fl.close();}
catch (IOException e)
{ e.printStackTrace(); }}}
DataInputStream Class
Methods:
dis.close();
Methods:
dos.writeInt(123);
dos.writeFloat(45.67f);
dos.writeUTF("Hello, World!");
dos.close();
} catch (IOException e) {
e.printStackTrace();
}}