Unit 13 - Exceptions and For-Each loops
Download
Report
Transcript Unit 13 - Exceptions and For-Each loops
“for each” loops
Exceptions
1
AP Computer Science A – Healdsburg High School
Overview of the “for each” loop
Purpose
The basic for loop was extended in
Java 5 to make iteration over arrays
and other collections more convenient.
This newer for statement is called the
enhanced for or for-each (because it is
called this in other programming
languages).
2
AP Computer Science A – Healdsburg High School
Comparison of the “for each” loop
// Syntax of traditional for loop
for (int i = 0; i < arr.length; i++)
{
type var = arr[i];
body-of-loop
}
// Syntax of for each loop
for (type var : arr)
{
body-of-loop
}
3
AP Computer Science A – Healdsburg High School
Example of the “for each” loop
// Syntax of traditional for loop
double[ ] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (int i = 0; i < ar.length; i++)
{
// i indexes each element successively.
sum += ar[i];
}
4
// Syntax of for each loop
double[ ] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (double d : ar)
{
// d gets successively each value in ar.
sum += d;
AP Computer Science A – Healdsburg High School
}
Drawbacks of the “for each” loop
1. Only access. Elements can not be assigned to or
removed from collection.
2. Only single structure. It's not possible to traverse two
structures at once, eg, to compare two arrays.
3. Only single element. Use only for single element access,
eg, not to compare successive elements.
4. Only forward. It's possible to iterate only forward by
single steps.
5. At least Java 5. Don't use it if you need compatibility
with versions before Java 5.
5
AP Computer Science A – Healdsburg High School
Exceptions
Purpose
An exception is a run-time event that
signals an abnormal condition in the
program.
You all have seen the little messages
that come up on the little black
screen… Caused by an exception!!
6
AP Computer Science A – Healdsburg High School
Exceptions: the 4 you need to know
1. ArithmeticException
Purpose
Thrown in case of an arithmetic error
(example, division by 0)
2. ArrayIndexOutOfBounds
Purpose
Thrown when an array index is negative
or greater than array.length-1
7
AP Computer Science A – Healdsburg High School
Exceptions: the 4 you need to know
3. NullPointerException
Purpose
Thrown when you forget to initialize an
object-type variable and try to call its
method.
8
4. ClassCastException
Purpose
Thrown when you are trying to cast an
object into a class that it does not
belong.
AP Computer Science A – Healdsburg High School