Java Reference
In-Depth Information
Break/Continue
break
and
continue
control loop iterations.
break
is used to quit the loop altogether.
It causes all the looping to stop from that point. On the other hand,
continue
just
causes the current iteration to stop, and the loop resumes with the next iteration.
Listing 3.9 demonstrates how these are used.
Listing 3.9
Break/Continue
for(student in students) {
if(student.name == "Jim") {
foundStudent = student;
break
; // stops the loop altogether,
//no more students are checked
}
}
for(book in Books ) {
if(book.publisher == "Addison Wesley") {
insert book into bookList;
continue
; // moves on to check next book.
}
insert book into otherBookList;
otherPrice += book.price;
}
Type Operators
The
instanceof
operator allows you to test the class type of an object, whereas
the
as
operator allows you to cast an object to another class. One way this is use-
ful is to cast a generalized object to a more specific class in order to perform a
function from that more specialized class. Of course, the object must inherently
be that kind of class, and that is where the
instanceof
operator is useful to test
if the object is indeed that kind of class. If you try to cast an object to a class that
that object does not inherit from, you will get an exception.
In the following listing, the
printLower()
function will translate a string to lower-
case, but for other types of objects, it will just print it as is. First, the generic object
is tested to see if it is a
String
. If it is, the object is cast to a
String
using the
as
oper-
ator, and then the
String
's
toLowerCase()
method is used to convert the output to
all lowercase. Listing 3.10 illustrates the use of the
instanceof
and
as
operators.
Listing 3.10
Type Operators
function printLower(object: Object ) {
if(object
instanceof
String) {
Search WWH ::
Custom Search