0% found this document useful (0 votes)
44 views31 pages

JAVA Unit-3

The document discusses exception handling in Java. It defines that an exception is an abnormal condition that disrupts normal program flow. There are two main types of exceptions: checked exceptions which are compiled-time errors, and unchecked exceptions which are runtime errors. The document also discusses exception handling keywords like try, catch, finally, throw, throws. It provides examples of try-catch blocks to handle exceptions, as well as nested try blocks and multi-catch blocks.

Uploaded by

Mahir Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
44 views31 pages

JAVA Unit-3

The document discusses exception handling in Java. It defines that an exception is an abnormal condition that disrupts normal program flow. There are two main types of exceptions: checked exceptions which are compiled-time errors, and unchecked exceptions which are runtime errors. The document also discusses exception handling keywords like try, catch, finally, throw, throws. It provides examples of try-catch blocks to handle exceptions, as well as nested try blocks and multi-catch blocks.

Uploaded by

Mahir Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

Unit-3: Exception, Collection Framework

EXCEPTION HANDLING

 Exception
“Exception is an abnormal condition. In java, exception is an event that disrupts
the normal flow of the program. It is an object which is thrown at runtime.”

 What is exception handling


 The exception handling in java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can be
maintained.

 Hierarchy of Java Exception classes

 Types of Exception
 There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception.

 The sun microsystem says there are three types of exceptions:


1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions
1) Checked Exception
 The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException
etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
 The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time rather they are checked at runtime.
3) Error
 Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.

Built-in Exceptions
 Java defines several exception classes inside the standard packagejava.lang.

 The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs,
most exceptions derived from RuntimeException are automatically available.

 Java defines several other types of exceptions that relate to its various class
libraries. Following is the list of Java Unchecked RuntimeException.
Exception Description
ArithmeticException Arithmetic error, such as divide-
by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element
of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a
method.
IllegalMonitorStateException Illegal monitor operation, such as
waiting on an unlocked thread.
IllegalStateException Environment or application is in
incorrect state.
IllegalThreadStateException Requested operation not
compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-
bounds.
NegativeArraySizeException Array created with a negative
size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a
numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the
bounds of a string.
UnsupportedOperationException An unsupported operation was
encountered.

 Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ClassNotFoundException Class not found.

CloneNotSupportedException Attempt to clone an object that does not


implement the Cloneable interface.

IllegalAccessException Access to a class is denied.

InstantiationException Attempt to create an object of an abstract


class or interface.

InterruptedException One thread has been interrupted by another


thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.


 Java Exception Handling Keywords
 There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws

try-catch Blocks
try block
 Java try block is used to enclose the code that might throw an exception. It must
be used within the method.

 Java try block must be followed by either catch or finally block.


Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw exception
}finally{}
catch block
 Java catch block is used to handle the Exception. It must be used after the try
block only. You can use multiple catch block with a single try.
 Example
 Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{


public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
 Exception in thread main java.lang.ArithmeticException:/ by zero
Internal working of java try-catch block

 The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception
occurred).
 Causes the program to terminate.

 Java Multi catch block


 If you have to perform different tasks at the occurrence of different
Exceptions, use java multi catch block.
 Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task
1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("tas
k 2 completed");}
catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code...");


}
}
Output:task1 completed
rest of the code...
Rule: At a time only one Exception is occured and at a time
only one catch block is executed.
Rule: All catch blocks must be ordered from most specific to
most general i.e. catch for ArithmeticException must come
before catch for Exception .

 Java Nested try block


 The try block within a try block is known as nested try block in java.
 Sometimes a situation may arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

 Java nested try example


Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(
e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
 finally block
 Java finally block is a block that is used to execute important code or to
put "cleanup" code such as closing connection, closing a file stream etc.
 Java finally block is always executed whether exception is handled or
not.Java finally block must be followed by try or catch block.
Note: If you don't handle exception, before terminating the
program, JVM executes finally block(if any).

 Usage of Java finally


 Let's see the different cases where java finally block can be used.
Case 1
 Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 2
 Let's see the java finally example where exception occurs and not
handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
 Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main
java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).

 throw keyword
 The Java throw keyword is used to explicitly throw an exception.
 We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception.
We will see custom exceptions later.
 The syntax of java throw keyword is given below.
throw exception;
 For Example:
throw new IOException("sorry device error);
 Let us see the example to manually throw the ArithmeticException
otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

 throws keyword
 The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that
normal flow can be maintained.
 Exception Handling is mainly used to handle the checked exceptions. If
there occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code
being used.

 Syntax of java throws


return_type method_name() throws exceptions_name
{
//method code
}

 Let's see the example of java throws clause which describes that checked
exceptions can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception }
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

There are two cases:


1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.

Case2: You declare the exception


A)In case you declare the exception, if exception does not occur, the code
will be executed fine.
B)In case you declare the exception if exception occurs, an exception will
be thrown at runtime because throws does not handle the exception.

Q) Can we rethrow an exception?


Yes, by throwing same exception in catch block.

Difference between throw and throws in Java


There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:
No. throw throws
1) Java throw keyword is used to Java throws keyword is used to declare
explicitly throw an exception. an exception.
2) Checked exception cannot be Checked exception can be propagated
propagated using throw only. with throws.
3) Throw is followed by an Throws is followed by class.
instance.
4) Throw is used within the Throws is used with the method
method. signature.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.

Java throws example


void m()
{
throw new ArithmeticException("sorry");
}
Java throws example
void m()throws ArithmeticException
{
//method code
}
Java throw and throws example
void m()throws ArithmeticException
{
throw new ArithmeticException("sorry");
}
Difference between final, finally and finalize
 There are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
No. Final finally finalize
1) Final is used to apply Finally is used to Finalize is used to
restrictions on class, method place important perform clean up
and variable. Final class code, it will be processing just
can't be inherited, final executed whether before object is
method can't be overridden exception is garbage collected.
and final variable value can't handled or not.
be changed.
2) Final is a keyword. Finally is a block. Finalize is a
method.
Java final example
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
Java finally example
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
Java finalize example
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}

 Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
SN Methods with Description

1 public String getMessage()


Returns a detailed message about the exception that has occurred.
This message is initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable
object.

3 public String toString()


Returns the name of the class concatenated with the result of
getMessage()

4 public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err,
the error output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The
element at index 0 represents the top of the call stack, and the last
element in the array represents the method at the bottom of the call
stack.

6 public Throwable fillInStackTrace()


Fills the stack trace of this Throwable object with the current stack
trace, adding to any previous information in the stack trace.

 Declaring you own Exception:


 You can create your own exceptions in Java. Keep the following points in
mind when writing your own exception classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced
by the Handle or Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the
RuntimeException class.
 We can define our own Exception class as below:
class MyException extends Exception{
}
 You just need to extend the Exception class to create your own Exception class.
 These are considered to be checked exceptions.
 The following InsufficientFundsException class is a user-defined exception that
extends the Exception class, making it a checked exception. An exception class
is like any other class, containing useful fields and methods.
Example:
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
 To demonstrate using our user-defined exception, the following
CheckingAccount class contains a withdraw() method that throws an
InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount


{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following
result:
Depositing $500...
Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

Java Collections Framework


 The java.util package contains one of Java’s most powerful subsystems:
collections.

 A collection is a group of objects. Collections are a state-of-the-art technology that


merits close attention by all Java programmers.

 Collection framework represents a unified architecture for storing and


manipulating group of objects.

 All collections frameworks contain the following:


 Interfaces
 Implementations, i.e., Classes
 Algorithms
 Hierarchy of Collection Framework
 Let us see the hierarchy of collection framework. The java.util package
contains all the classes and interfaces for Collection framework.

 In addition to collections, java.util contains a wide assortment of classes


and interfaces that support a broad range of functionality. These classes
and interfaces are available for use in programs that you write.

 Their applications include generating pseudorandom numbers,


manipulating date and time, observing events, manipulating sets of bits,
and tokenizing strings. Because of its many features, java.util is one of
Java’s most widely used packages.

 The collections framework was designed to meet several goals:


 First, the framework had to be high-performance. The
implementations for the fundamental collections (dynamic arrays,
linked lists, trees, and hash tables) are highly efficient.
 Second, the framework had to allow different types of collections to
work in a similar manner and with a high degree of interoperability.
 Third, extending and/or adapting a collection had to be easy.
THE COLLECTION INTEFACES

 All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.

 Java Collection simply means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
SN Interfaces with Description
1 The Collection Interface
This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
2 The List Interface
This extends Collection and an instance of List stores an ordered
collection of elements.
3 The Set
This extends Collection to handle sets, which must contain unique
elements
4 The SortedSet
This extends Set to handle sorted sets
5 The Map
This maps unique keys to values.
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in ascending order.
8 The Enumeration
This is legacy interface and defines the methods by which you can
enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator.

 The standard collection classes are summarized in the following table:


SN Classes with Description
1 AbstractCollection
Implements most of the Collection interface.
2 AbstractList
Extends AbstractCollection and implements most of the List interface.
3 AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential
rather than random access of its elements.
4 LinkedList
Implements a linked list by extending AbstractSequentialList.
5 ArrayList
Implements a dynamic array by extending AbstractList.
6 AbstractSet
Extends AbstractCollection and implements most of the Set interface.
7 HashSet
Extends AbstractSet for use with a hash table.
8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.
9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.
10 AbstractMap
Implements most of the Map interface.
11 HashMap
Extends AbstractMap to use a hash table.
12 TreeMap
Extends AbstractMap to use a tree.
13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing
documents.

 Methods of Collection interface


 There are many methods declared in the Collection interface. They are as
follows:
No. Method Description
1 public boolean add(Object is used to insert an element in this
element) collection.
2 public boolean is used to insert the specified
addAll(collection c) collection elements in the invoking
collection.
3 public boolean is used to delete an element from this
remove(Object element) collection.
4 public boolean is used to delete all the elements of
removeAll(Collection c) specified collection from the invoking
collection.
5 public boolean is used to delete all the elements of
retainAll(Collection c) invoking collection except the
specified collection.
6 public int size() return the total number of elements in
the collection.
7 public void clear() removes the total no of element from
the collection.
8 public boolean is used to search an element.
contains(object element)
9 public boolean is used to search the specified
containsAll(Collection c) collection in this collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object matches two collection.
element)
14 public int hashCode() returns the hashcode number for
collection.

Java List Interface

 List Interface is the subinterface of Collection.It contains methods to insert


and delete elements in index basis.It is a factory of ListIterator interface.

 Java ArrayList class

 Java ArrayList class uses a dynamic array for storing the elements.It
extends AbstractList class and implements List interface.
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index
basis.
 In Java ArrayList class, manipulation is slow because a lot of shifting
needs to be occurred if any element is removed from the array list.
 Creating ArrayList object:
ArrayList al=new ArrayList();//creating old non-generic arraylist
OR
ArrayList<String> al=new ArrayList<String>();
//creating new generic arraylist
 Example of Java ArrayList class:
import java.util.*;
class TestCollection1{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();


al.add("value1");//adding object in arraylist
al.add("value2");
al.add("value3");
al.add("value4");

Iterator itr=al.iterator();//getting Iterator from arraylist


to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
value1
value2
value3
value4

 Two ways to iterate the elements of collection in java


1. By Iterator interface.
2. By for-each loop.

 In the above example, we have seen traversing ArrayList by Iterator. Let's see the
example to traverse ArrayList elements using for-each loop.
 Iterating the elements of Collection by for-each loop
import java.util.*;

class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("value1");
al.add("value2");
al.add("value3");
al.add("value4");

for(String obj:al)
System.out.println(obj);
}
}
Output: value1
value2
value3
value4

 User-defined class objects in Java ArrayList


class Student{
int rollno;
String name;
int age;

Student(int rollno,String name,int age){


this.rollno=rollno;
this.name=name;
this.age=age;
}
}

import java.util.*;

public class TestCollection3{


public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
ArrayList<Student> al=new ArrayList<Student>();

al.add(s1);//adding Student class object


al.add(s2);
al.add(s3);

Iterator itr=al.iterator();

//traversing elements of ArrayList object


while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25

 Example of addAll(Collection c) method


ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();


al2.add("Sonoo");
al2.add("Hanumat");
Output:
Ravi
Vijay
Ajay
Sonoo
Hanumat

 Example of removeAll() method


ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();


al2.add("Ravi");
al2.add("Hanumat");

al.removeAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
iterating the elements after removing the elements of al2...
Vijay
Ajay

 Example of retainAll() method


import java.util.*;
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");

al.retainAll(al2);

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi

 Java LinkedList class


 Java LinkedList class uses doubly linked list to store the elements. It
extends the AbstractList class and implements List and Deque interfaces.
 Java LinkedList class can contain duplicate elements.
 Java LinkedList class maintains insertion order.
 Java LinkedList class is non synchronized.
 In Java LinkedList class, manipulation is fast because no shifting needs
to be occurred. Java LinkedList class can be used as list, stack or queue.

 Java LinkedList Example


import java.util.*;
public class TestCollection7{
public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();


al.add("Ravi");
al.add("Vijay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay

 Difference between ArrayList and LinkedList

ArrayList LinkedList
1) ArrayList internally LinkedList internally uses doubly linked
uses dynamic array to store the list to store the elements.
elements.
2) Manipulation with ArrayList Manipulation with LinkedList is fasterthan
is slow because it internall ArrayList because it uses doubly linked list
y uses array. If any element is so no bit shifting is required in memory.
removed from the array, all the
bits are shifted in memory.
3) ArrayList class can act as a LinkedList class can act as a list and
list only because it implements queue both because it implements List and
List only. Deque interfaces.
4) ArrayList is better for storing LinkedList is better for manipulatingdata.
and accessingdata.

Java - The Set Interface


 A Set is a Collection that cannot contain duplicate elements. It models the
mathematical set abstraction.

 The Set interface contains only methods inherited from Collection and adds the
restriction that duplicate elements are prohibited.
 Set also adds a stronger contract on the behavior of the equals and hashCode
operations, allowing Set instances to be compared meaningfully even if their
implementation types differ.
 The methods declared by Set are summarized in the following table:
SN Methods with Description

1 add( )
Adds an object to the collection

2 clear( )
Removes all objects from the collection

3 contains( )
Returns true if a specified object is an element within the
collection

4 isEmpty( )
Returns true if the collection has no elements

5 iterator( )
Returns an Iterator object for the collection which may be used
to retrieve an object

6 remove( )
Removes a specified object from the collection

7 size( )
Returns the number of elements in the collection

 Example:
Set have its implementation in various classes like HashSet, TreeSet,
LinkedHashSet. Following is the example to explain Set functionality:
import java.util.*;

public class SetDemo {

public static void main(String args[]) {


int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);


System.out.println("The sorted list is:");
System.out.println(sortedSet);

System.out.println("The First element of the set is: "+


(Integer)sortedSet.first());
System.out.println("The last element of the set is: "+
(Integer)sortedSet.last());
}
catch(Exception e){}
}
}
This would produce the following result:
[amrood]$ java SetDemo
[34, 30, 60, 10, 22]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

 HashSet class
 uses hashtable to store the elements.It extends AbstractSet class and
implements Set interface.
 contains unique elements only.

 Difference between List and Set:


 List can contain duplicate elements whereas Set contains unique
elements only.

 Example of HashSet class:

HashSet<String> al=new HashSet<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Output:Ajay
Vijay
Ravi

 Java LinkedHashSet class:


 contains unique elements only like HashSet. It extends HashSet class and
implements Set interface.
 maintains insertion order.
 Example of LinkedHashSet class:
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Output:>Ravi
Vijay
Ajay

 Java TreeSet class


 contains unique elements only like HashSet. The TreeSet class implements
NavigableSet interface that extends the SortedSet interface.
 maintains ascending order.
 Example of TreeSet class:
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Output:Ajay
Ravi
Vijay

Java Enum [ enumeration ]


 Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc. The java enum constants are static and final
implicitly.
 It is available from JDK 1.5. Java Enums can be thought of as classes that have
fixed set of constants.
 Points to remember for Java Enum
o enum improves type safety
o enum can be easily used in switch
o enum can be traversed
o enum can have fields, constructors and methods
o enum may implement many interfaces but cannot extend any class
because it internally extends Enum class

 Simple example of java enum


class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);
}}

Output:WINTER
SPRING
SUMMER
FALL

Defining Java enum


 The enum can be defined within or outside the class because it is similar
to a class.
Java enum example: defined outside class
enum Season { WINTER, SPRING, SUMMER, FALL }
class EnumExample2{
public static void main(String[] args) {
Season s=Season.WINTER;
System.out.println(s);
}}
Output:WINTER

Java enum example: defined inside class


class EnumExample3{
enum Season { WINTER, SPRING, SUMMER, FALL; }
public static void main(String[] args) {
Season s=Season.WINTER;//enum type is required to
access WINTER
System.out.println(s);
}}
Output:WINTER

Initializing specific values to the enum constants


 The enum constants have initial value that starts from 0, 1, 2, 3 and so
on. But we can initialize the specific value to the enum constants by
defining fields and constructors. As specified earlier, Enum can have
fields, constructors and methods.
enum Season{
WINTER(5), SPRING(10), SUMMER(15), FALL(20);

private int value;


private Season(int value){
this.value=value;
}
}
public static void main(String args[]){
for (Season s : Season.values())
System.out.println(s+" "+s.value);
}
}

Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20

 Can we create the instance of enum by new keyword?


No, because it contains private constructors only.

 Java enum in switch statement


class EnumExample5{
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, T
HURSDAY, FRIDAY, SATURDAY}

public static void main(String args[]){


Day day=Day.MONDAY;

switch(day){
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}
}
}
Output:monday

Java Iterator
 The easiest way to display each element is to use an iterator, which is an object
that implements either the Iterator or the ListIterator interface.
 Iterator enables you to cycle through a collection, obtaining or removing
elements. ListIterator extends Iterator to allow bidirectional traversal of a list,
and the modification of elements.

 Each of the collection classes provides an iterator( ) method that returns an


iterator to the start of the collection. By using iterator object, you can access
each element in the collection, one element at a time.
 Steps to use iterator:
 Obtain an iterator to the start of the collection by calling the collection's
iterator( ) method.
 Set up a loop that makes a call to hasNext( ). Have the loop iterate as long
as hasNext( ) returns true.
 Within the loop, obtain each element by calling next( ).

 For collections that implement List, you can also obtain an iterator by calling
ListIterator.

 The Methods Declared by Iterator:


SN Methods with Description
1 boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false.
2 Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next
element.
3 void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made
to call remove( ) that is not preceded by a call to next( ).

 The Methods Declared by ListIterator:


SN Methods with Description
1 void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next
call to next( ).
2 boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false.
3 boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false.
4 Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not
a next element.
5 int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the
size of the list.
6 Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is
not a previous element.
7 int previousIndex( )
Returns the index of the previous element. If there is not a previous element,
returns -1.
8 void remove( )
Removes the current element from the list. An IllegalStateException is thrown if
remove( ) is called before next( ) or previous( ) is invoked.
9 void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to
either next( ) or previous( ).
Example:
import java.util.*;
public class IteratorDemo {

public static void main(String args[]) {


// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

// Use iterator to display contents of al


System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Modify objects being iterated


ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Now, display the list backwards


System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
This would produce the following result:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

 Implementing our own Custom Iterator

 We will create our own custom class and make it implement Iterable, so
that it returns an Iterator using which we can iterate the elements.
import java.util.ArrayList;
import java.util.Iterator;

public class AnimalIterator<String> implements Iterator<Object> {

private ArrayList<?> animal;


private int position;

public AnimalIterator(Animal animalBase) {


this.animal = animalBase.getAnimal();
}

@Override
public boolean hasNext() {
if (position < animal.size())
return true;
else
return false;
}

@Override
public Object next() {
Object aniObj = animal.get(position);
position++;
return aniObj;
}

@Override
public void remove() {
animal.remove(position);
}

}
package com.javapapers;

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

public class Animal implements Iterable<String> {

private ArrayList<String> animal = new ArrayList<String>();

public Animal(ArrayList animal){


this.animal = animal;
}

public ArrayList getAnimal() {


return animal;
}

@Override
public Iterator<String> iterator() {
return new AnimalIterator(this);
}

import java.util.ArrayList;

public class TestIterator {


public static void main(String args[]) {
ArrayList<String> animalList = new ArrayList();
animalList.add("Horse");
animalList.add("Lion");
animalList.add("Tiger");
Animal animal = new Animal(animalList);
for (String animalObj : animal) {
System.out.println(animalObj);
}
}
}
Output:
Horse
Lion
Tiger

You might also like