SlideShare a Scribd company logo
Java Programming -
Collection
Oum Saokosal
Master’s Degree in information systems,Jeonju
University,South Korea
012 252 752 / 070 252 752
oumsaokosal@gmail.com
Contact Me
• Tel: 012 252 752 / 070 252 752
• Email: oumsaokosal@gmail.com
• FB Page: https://facebook.com/kosalgeek
• PPT: http://www.slideshare.net/oumsaokosal
• YouTube: https://www.youtube.com/user/oumsaokosal
• Twitter: https://twitter.com/okosal
• Web: http://kosalgeek.com
3
Agenda
•Building arrays
•Vectors and Hashtables
•Data structures introduced in Java 2
•Using wrappers to convert primitive data
types to objects
•Handling exceptions
4
Arrays
• Accessingarrays
• Accessarraysby supplying the indexin square bracketsafter the
variable name,variableName[index]
• The first indexis0, not 1
• Example
• Here, the argument to main is an array of Strings called args
public class Test {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}
> javac Test.java
> java Test Hello There
First argument is Hello
5
The Array length Field
• Arrays have a built-in field called length that storesthe size of
the array
• The length is one bigger than the biggest index, due to the fact that
the index starts at 0
• Example
public class Test2 {
public static void main(String[] args) {
System.out.println("Number of args is " +
args.length);
}
}
> javac Test2.java
> java Test2
Number of args is 0
> java Test2 Hello There
Number of args is 2
6
Building Arrays
• Arrays can be built in a one-step or two-
step process
1. The one-step process is of the following form:
type[] var = { val1, val2, ... , valN };
• For example:
int[] values = { 10, 100, 1000 };
Point[] points = { new Point(0, 0),
new Point(1, 2), ...
};
7
Building Arrays, cont.
2. With the two-step process, first allocate
an array of references:
type[] var = new type[size];
• For example:
int[] values = new int[7];
Point[] points = new Point[length];
• Second, populate the array
points[0] = new Point(...);
points[1] = new Point(...);
...
8
Multidimensional Arrays
•Multidimensional arrays are implemented as
an arrayof arrays
int[][] twoD = new int[64][32];
String[][] cats = {
{ "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted" , "red-point" }
};
9
Data Structures
• Java 1.0 introduced two synchronized data
structures in the java.util package
• Vector
• A stretchable(resizable) array of Objects
• Time to accessan element is constant regardlessof
position
• Time to insert element is proportionalto the size of the
vector
• Hashtable
• Stores key-value pairs as Objects
• Neither thekeysor values can be null
• Time to access/insert is proportionaltothe size of the
hashtable
10
UsefulVector Methods
• addElement / insertElementAt / setElementAt
• Add elementsto the vector
• removeElement / removeElementAt
• Removesan element from the vector
• firstElement / lastElement
• Returnsa reference to the first and last element,respectively
(without removing)
• elementAt
• Returnsthe element at the specified index
• indexOf
• Returnsthe indexof an element that equals the object specified
• contains
• Determinesif the vector containsan object
11
UsefulVector Methods (cont)
• elements
• Returns an Enumerationof objects in the vector
Enumeration elements = vector.elements();
while(elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
• size
• The number of elements in the vector
• capacity
• The number of elements the vector can hold
before becoming resized
12
Useful Hashtable Methods
• put / get
• Stores or retrievesa value in the hashtable
• remove / clear
• Removesa particular entry or all entriesfrom the hashtable
• containsKey / contains
• Determinesif the hashtable containsa particular key or element
• keys / elements
• Returnsan enumeration ofall keysor elements,respectively
• size
• Returnsthe number of elementsin the hashtable
• rehash
• Increasesthe capacity ofthe hashtable and reorganizesit
13
Collections Framework
•Additional data structures
Collection
Set
SortedSet
List
ArrayList
LinkedList
Vector*
HashSet
TreeSet
Map
SortedMap
HashMap
Hashtable*
TreeMap
Interface Concrete class *Synchronized Access
14
Collection Interfaces
• Collection
• Abstract classfor holding groupsofobjects
• Set
• Group of objectscontainingno duplicates
• SortedSet
• Set of objects(no duplicates)stored in ascending order
• Order is determined by a Comparator
• List
• Physically (versus logically)ordered sequence ofobjects
• Map
• Stores objects(unordered)identified by unique keys
• SortedMap
• Objectsstored in ascending order based on their key value
• Neither duplicate or null keysare permitted
15
Collections Class
• Use to create synchronized data structures
List list = Collection.synchronizedList(new ArrayList());
Map map = Collections.synchronizedMap(new HashMap());
• Provides useful (static) utility methods
• sort
• Sorts (ascending) theelementsin thelist
• max, min
• Returns the maximum or minimum element in the collection
• reverse
• Reverses the order of theelements in the list
• shuffle
• Randomly permutes theorder of the elements
16
WrapperClasses
•Each primitive data type has a
corresponding object (wrapperclass)
Primitive Corresponding
Data Type Object Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
17
Wrapper Uses
• Defines useful constants for each data type
• For example,
Integer.MAX_VALUE
Float.NEGATIVE_INFINITY
• Convert between data types
• Use parseXxx method to convert a String to
the correspondingprimitivedata type
try {
String value = "3.14e6";
double d = Double.parseDouble(value);
} catch (NumberFormatException nfe) {
System.out.println("Can't convert: " + value);
}
18
Exception Hierarchy
•Simplified Diagram of Exception
Hierarchy
Throwable
Error
IOException RuntimeException
Exception
…
19
ThrowableTypes
• Error
• A non-recoverableproblem that should not be
caught (OutOfMemoryError,
StackOverflowError, …)
• Exception
• An abnormalcondition that should be caught and
handled by the programmer
• RuntimeException
• Special case; does not have to be caught
• Usually the result of a poorly written program
(integer division by zero, array out-of-bounds,etc.)
• A RuntimeException is considereda bug
20
Multiple CatchClauses
• A single try can have more that one catch clause
• If multiple catch clauses are used, order them from
the most specific to the most general
• If no appropriatecatch is found,the exception is
handedto any outer try blocks
• If no catch clause is found within the method, then the
exception is thrown by the method
try {
...
} catch (ExceptionType1 var1) {
// Do something
} catch (ExceptionType2 var2) {
// Do something else
}
21
Try-Catch, Example
...
BufferedReader in = null;
String lineIn;
try {
in = new BufferedReader(new FileReader("book.txt"));
while((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
in.close();
} catch (FileNotFoundException fnfe ) {
System.out.println("File not found.");
} catch (EOFException eofe) {
System.out.println("Unexpected End of File.");
} catch (IOException ioe) {
System.out.println("IOError reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
}
22
The finally Clause
•After the final catch clause, an optional
finally clause may be defined
•The finally clause is always executed,
even if the try or catch blocks are
exited through a break, continue, or
return
try {
...
} catch (SomeException someVar) {
// Do something
} finally {
// Always executed
}
23
Thrown Exceptions
• If a potential exception is not handled in the
method, then the method must declare that
the exception can be thrown
public SomeType someMethod(...) throws SomeException {
// Unhandled potential exception
...
}
• Note: Multiple exception types (comma
separated) can be declared in the throws
clause
• Explicitly generating an exception
throw new IOException("Blocked by firewall.");
throw new MalformedURLException("Invalid protocol");

More Related Content

What's hot (20)

4 gouping object
4 gouping object4 gouping object
4 gouping object
Robbie AkaChopa
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
DneprCiklumEvents
 
Out ofmemoryerror what is the cost of java objects
Out ofmemoryerror  what is the cost of java objectsOut ofmemoryerror  what is the cost of java objects
Out ofmemoryerror what is the cost of java objects
Jean-Philippe BEMPEL
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
Mahmoud Samir Fayed
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
Suman Lata
 
Clojure class
Clojure classClojure class
Clojure class
Aysylu Greenberg
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
raksharao
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
Wojciech Pituła
 
The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184
Mahmoud Samir Fayed
 
Java 101
Java 101Java 101
Java 101
Manuela Grindei
 
Procedural Content Generation with Clojure
Procedural Content Generation with ClojureProcedural Content Generation with Clojure
Procedural Content Generation with Clojure
Mike Anderson
 
The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212
Mahmoud Samir Fayed
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
GeeksLab Odessa
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181
Mahmoud Samir Fayed
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
 
Java 104
Java 104Java 104
Java 104
Manuela Grindei
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
DneprCiklumEvents
 
Out ofmemoryerror what is the cost of java objects
Out ofmemoryerror  what is the cost of java objectsOut ofmemoryerror  what is the cost of java objects
Out ofmemoryerror what is the cost of java objects
Jean-Philippe BEMPEL
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
Mahmoud Samir Fayed
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
raksharao
 
The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184
Mahmoud Samir Fayed
 
Procedural Content Generation with Clojure
Procedural Content Generation with ClojureProcedural Content Generation with Clojure
Procedural Content Generation with Clojure
Mike Anderson
 
The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212
Mahmoud Samir Fayed
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
GeeksLab Odessa
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181
Mahmoud Samir Fayed
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
 

Viewers also liked (20)

Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - SwingJava OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with ExamplesJavascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
OUM SAOKOSAL
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for Android
OUM SAOKOSAL
 
Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo
Erika Hall
 
Java interface
Java interfaceJava interface
Java interface
BHUVIJAYAVELU
 
Measuring And Defining The Experience Of Immersion In Games
Measuring And  Defining The  Experience Of  Immersion In GamesMeasuring And  Defining The  Experience Of  Immersion In Games
Measuring And Defining The Experience Of Immersion In Games
OUM SAOKOSAL
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
OUM SAOKOSAL
 
ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)
OUM SAOKOSAL
 
Terminology In Telecommunication
Terminology In TelecommunicationTerminology In Telecommunication
Terminology In Telecommunication
OUM SAOKOSAL
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
OUM SAOKOSAL
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
Bible Tang
 
Kimchi Questionnaire
Kimchi QuestionnaireKimchi Questionnaire
Kimchi Questionnaire
OUM SAOKOSAL
 
Actionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other NoteActionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other Note
OUM SAOKOSAL
 
Java interface
Java interfaceJava interface
Java interface
Arati Gadgil
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
Rayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication SystemRayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication System
OUM SAOKOSAL
 
Python - Lecture 1
Python - Lecture 1Python - Lecture 1
Python - Lecture 1
Ravi Kiran Khareedi
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - SwingJava OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with ExamplesJavascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
OUM SAOKOSAL
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for Android
OUM SAOKOSAL
 
Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo
Erika Hall
 
Measuring And Defining The Experience Of Immersion In Games
Measuring And  Defining The  Experience Of  Immersion In GamesMeasuring And  Defining The  Experience Of  Immersion In Games
Measuring And Defining The Experience Of Immersion In Games
OUM SAOKOSAL
 
ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)
OUM SAOKOSAL
 
Terminology In Telecommunication
Terminology In TelecommunicationTerminology In Telecommunication
Terminology In Telecommunication
OUM SAOKOSAL
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
OUM SAOKOSAL
 
Kimchi Questionnaire
Kimchi QuestionnaireKimchi Questionnaire
Kimchi Questionnaire
OUM SAOKOSAL
 
Actionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other NoteActionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other Note
OUM SAOKOSAL
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
Rayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication SystemRayleigh Fading Channel In Mobile Digital Communication System
Rayleigh Fading Channel In Mobile Digital Communication System
OUM SAOKOSAL
 
Ad

Similar to Java OOP Programming language (Part 4) - Collection (20)

STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
Rajeev Uppala
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
Arpit Poladia
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
Nikunj Parekh
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
Nikunj Parekh
 
Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
Syed Afaq Shah MACS CP
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Learn advanced java programming
Learn advanced java programmingLearn advanced java programming
Learn advanced java programming
TOPS Technologies
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
Dr. SURBHI SAROHA
 
22.ppt
22.ppt22.ppt
22.ppt
BharaniDaran15
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
Ganesh Chittalwar
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
Ad

More from OUM SAOKOSAL (20)

Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Aggregate rank bringing order to web sites
Aggregate rank  bringing order to web sitesAggregate rank  bringing order to web sites
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
How to succeed in graduate school
How to succeed in graduate schoolHow to succeed in graduate school
How to succeed in graduate school
OUM SAOKOSAL
 
Google
GoogleGoogle
Google
OUM SAOKOSAL
 
E miner
E minerE miner
E miner
OUM SAOKOSAL
 
Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
Consumer acceptance of online banking an extension of the technology accepta...
Consumer acceptance of online banking  an extension of the technology accepta...Consumer acceptance of online banking  an extension of the technology accepta...
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
When Do People Help
When Do People HelpWhen Do People Help
When Do People Help
OUM SAOKOSAL
 
Mc Nemar
Mc NemarMc Nemar
Mc Nemar
OUM SAOKOSAL
 
Correlation Example
Correlation ExampleCorrelation Example
Correlation Example
OUM SAOKOSAL
 
Sem Ski Amos
Sem Ski AmosSem Ski Amos
Sem Ski Amos
OUM SAOKOSAL
 
Sem+Essentials
Sem+EssentialsSem+Essentials
Sem+Essentials
OUM SAOKOSAL
 
Path Spss Amos (1)
Path Spss Amos (1)Path Spss Amos (1)
Path Spss Amos (1)
OUM SAOKOSAL
 
How To Succeed In Graduate School
How To Succeed In Graduate SchoolHow To Succeed In Graduate School
How To Succeed In Graduate School
OUM SAOKOSAL
 
Actionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core ConceptActionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core Concept
OUM SAOKOSAL
 
Actionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And FlashActionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And Flash
OUM SAOKOSAL
 
Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3
OUM SAOKOSAL
 
Actionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display ListActionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display List
OUM SAOKOSAL
 
Actionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityActionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 Interactivity
OUM SAOKOSAL
 
Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Aggregate rank bringing order to web sites
Aggregate rank  bringing order to web sitesAggregate rank  bringing order to web sites
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
How to succeed in graduate school
How to succeed in graduate schoolHow to succeed in graduate school
How to succeed in graduate school
OUM SAOKOSAL
 
Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
Consumer acceptance of online banking an extension of the technology accepta...
Consumer acceptance of online banking  an extension of the technology accepta...Consumer acceptance of online banking  an extension of the technology accepta...
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
When Do People Help
When Do People HelpWhen Do People Help
When Do People Help
OUM SAOKOSAL
 
Correlation Example
Correlation ExampleCorrelation Example
Correlation Example
OUM SAOKOSAL
 
Path Spss Amos (1)
Path Spss Amos (1)Path Spss Amos (1)
Path Spss Amos (1)
OUM SAOKOSAL
 
How To Succeed In Graduate School
How To Succeed In Graduate SchoolHow To Succeed In Graduate School
How To Succeed In Graduate School
OUM SAOKOSAL
 
Actionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core ConceptActionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core Concept
OUM SAOKOSAL
 
Actionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And FlashActionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And Flash
OUM SAOKOSAL
 
Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3Actionscript 3 - Session 1 Introduction To As 3
Actionscript 3 - Session 1 Introduction To As 3
OUM SAOKOSAL
 
Actionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display ListActionscript 3 - Session 5 The Display Api And The Display List
Actionscript 3 - Session 5 The Display Api And The Display List
OUM SAOKOSAL
 
Actionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityActionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 Interactivity
OUM SAOKOSAL
 

Recently uploaded (20)

Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 

Java OOP Programming language (Part 4) - Collection

  • 1. Java Programming - Collection Oum Saokosal Master’s Degree in information systems,Jeonju University,South Korea 012 252 752 / 070 252 752 [email protected]
  • 2. Contact Me • Tel: 012 252 752 / 070 252 752 • Email: [email protected] • FB Page: https://facebook.com/kosalgeek • PPT: http://www.slideshare.net/oumsaokosal • YouTube: https://www.youtube.com/user/oumsaokosal • Twitter: https://twitter.com/okosal • Web: http://kosalgeek.com
  • 3. 3 Agenda •Building arrays •Vectors and Hashtables •Data structures introduced in Java 2 •Using wrappers to convert primitive data types to objects •Handling exceptions
  • 4. 4 Arrays • Accessingarrays • Accessarraysby supplying the indexin square bracketsafter the variable name,variableName[index] • The first indexis0, not 1 • Example • Here, the argument to main is an array of Strings called args public class Test { public static void main(String[] args) { System.out.println("First argument: " + args[0]); } } > javac Test.java > java Test Hello There First argument is Hello
  • 5. 5 The Array length Field • Arrays have a built-in field called length that storesthe size of the array • The length is one bigger than the biggest index, due to the fact that the index starts at 0 • Example public class Test2 { public static void main(String[] args) { System.out.println("Number of args is " + args.length); } } > javac Test2.java > java Test2 Number of args is 0 > java Test2 Hello There Number of args is 2
  • 6. 6 Building Arrays • Arrays can be built in a one-step or two- step process 1. The one-step process is of the following form: type[] var = { val1, val2, ... , valN }; • For example: int[] values = { 10, 100, 1000 }; Point[] points = { new Point(0, 0), new Point(1, 2), ... };
  • 7. 7 Building Arrays, cont. 2. With the two-step process, first allocate an array of references: type[] var = new type[size]; • For example: int[] values = new int[7]; Point[] points = new Point[length]; • Second, populate the array points[0] = new Point(...); points[1] = new Point(...); ...
  • 8. 8 Multidimensional Arrays •Multidimensional arrays are implemented as an arrayof arrays int[][] twoD = new int[64][32]; String[][] cats = { { "Caesar", "blue-point" }, { "Heather", "seal-point" }, { "Ted" , "red-point" } };
  • 9. 9 Data Structures • Java 1.0 introduced two synchronized data structures in the java.util package • Vector • A stretchable(resizable) array of Objects • Time to accessan element is constant regardlessof position • Time to insert element is proportionalto the size of the vector • Hashtable • Stores key-value pairs as Objects • Neither thekeysor values can be null • Time to access/insert is proportionaltothe size of the hashtable
  • 10. 10 UsefulVector Methods • addElement / insertElementAt / setElementAt • Add elementsto the vector • removeElement / removeElementAt • Removesan element from the vector • firstElement / lastElement • Returnsa reference to the first and last element,respectively (without removing) • elementAt • Returnsthe element at the specified index • indexOf • Returnsthe indexof an element that equals the object specified • contains • Determinesif the vector containsan object
  • 11. 11 UsefulVector Methods (cont) • elements • Returns an Enumerationof objects in the vector Enumeration elements = vector.elements(); while(elements.hasMoreElements()) { System.out.println(elements.nextElement()); } • size • The number of elements in the vector • capacity • The number of elements the vector can hold before becoming resized
  • 12. 12 Useful Hashtable Methods • put / get • Stores or retrievesa value in the hashtable • remove / clear • Removesa particular entry or all entriesfrom the hashtable • containsKey / contains • Determinesif the hashtable containsa particular key or element • keys / elements • Returnsan enumeration ofall keysor elements,respectively • size • Returnsthe number of elementsin the hashtable • rehash • Increasesthe capacity ofthe hashtable and reorganizesit
  • 13. 13 Collections Framework •Additional data structures Collection Set SortedSet List ArrayList LinkedList Vector* HashSet TreeSet Map SortedMap HashMap Hashtable* TreeMap Interface Concrete class *Synchronized Access
  • 14. 14 Collection Interfaces • Collection • Abstract classfor holding groupsofobjects • Set • Group of objectscontainingno duplicates • SortedSet • Set of objects(no duplicates)stored in ascending order • Order is determined by a Comparator • List • Physically (versus logically)ordered sequence ofobjects • Map • Stores objects(unordered)identified by unique keys • SortedMap • Objectsstored in ascending order based on their key value • Neither duplicate or null keysare permitted
  • 15. 15 Collections Class • Use to create synchronized data structures List list = Collection.synchronizedList(new ArrayList()); Map map = Collections.synchronizedMap(new HashMap()); • Provides useful (static) utility methods • sort • Sorts (ascending) theelementsin thelist • max, min • Returns the maximum or minimum element in the collection • reverse • Reverses the order of theelements in the list • shuffle • Randomly permutes theorder of the elements
  • 16. 16 WrapperClasses •Each primitive data type has a corresponding object (wrapperclass) Primitive Corresponding Data Type Object Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean
  • 17. 17 Wrapper Uses • Defines useful constants for each data type • For example, Integer.MAX_VALUE Float.NEGATIVE_INFINITY • Convert between data types • Use parseXxx method to convert a String to the correspondingprimitivedata type try { String value = "3.14e6"; double d = Double.parseDouble(value); } catch (NumberFormatException nfe) { System.out.println("Can't convert: " + value); }
  • 18. 18 Exception Hierarchy •Simplified Diagram of Exception Hierarchy Throwable Error IOException RuntimeException Exception …
  • 19. 19 ThrowableTypes • Error • A non-recoverableproblem that should not be caught (OutOfMemoryError, StackOverflowError, …) • Exception • An abnormalcondition that should be caught and handled by the programmer • RuntimeException • Special case; does not have to be caught • Usually the result of a poorly written program (integer division by zero, array out-of-bounds,etc.) • A RuntimeException is considereda bug
  • 20. 20 Multiple CatchClauses • A single try can have more that one catch clause • If multiple catch clauses are used, order them from the most specific to the most general • If no appropriatecatch is found,the exception is handedto any outer try blocks • If no catch clause is found within the method, then the exception is thrown by the method try { ... } catch (ExceptionType1 var1) { // Do something } catch (ExceptionType2 var2) { // Do something else }
  • 21. 21 Try-Catch, Example ... BufferedReader in = null; String lineIn; try { in = new BufferedReader(new FileReader("book.txt")); while((lineIn = in.readLine()) != null) { System.out.println(lineIn); } in.close(); } catch (FileNotFoundException fnfe ) { System.out.println("File not found."); } catch (EOFException eofe) { System.out.println("Unexpected End of File."); } catch (IOException ioe) { System.out.println("IOError reading input: " + ioe); ioe.printStackTrace(); // Show stack dump }
  • 22. 22 The finally Clause •After the final catch clause, an optional finally clause may be defined •The finally clause is always executed, even if the try or catch blocks are exited through a break, continue, or return try { ... } catch (SomeException someVar) { // Do something } finally { // Always executed }
  • 23. 23 Thrown Exceptions • If a potential exception is not handled in the method, then the method must declare that the exception can be thrown public SomeType someMethod(...) throws SomeException { // Unhandled potential exception ... } • Note: Multiple exception types (comma separated) can be declared in the throws clause • Explicitly generating an exception throw new IOException("Blocked by firewall."); throw new MalformedURLException("Invalid protocol");