Documente Academic
Documente Profesional
Documente Cultură
if switch
break
continue,
try!catch!finally" #
$ %
& '
try catch finally
"
Supplementary Objectives
) *
+ #
if )
if-else )
switch )
Simple if Statement
if # '
if ( )
( #
/ 0
/ 0
if # / 0
( true / 0 if "
# ( false if
#
1 23
if
( # if
'
if (catIsAway()) { // Block
getFishingRod();
goFishing();
}
& / 0
# / > true
) / > boolean
' (a=b) #
#
a b
& if ( ;"
{}" 4
if-else Statement
if-else # '
if ( )
1
else
2
( # #
/ 0 ( true / 10
if
" # ( false
/ 20
else " #
( # # else 5
if
1 23
( # if-else
'
if (emergency)
operate();
else
joinQueue();
if (catIsAway()) {
getFishingRod();
goFishing();
} else
playWithCat();
) if
{} if if
4" " # if
" -" # -"
6 '
#
// (A)
if (temperature > upperLimit) { // (1) Block notation.
if (danger) soundAlarm(); // (2)
} else // Goes with if at (1).
turnHeaterOn();
// (B)
if (temperature > upperLimit) // (1) Without block notation.
if (danger) soundAlarm(); // (2)
else turnHeaterOn(); // Goes with if at (2).
// (C)
if (temperature > upperLimit) // (1)
if (danger) // (2)
soundAlarm();
else // Goes with if at (2).
turnHeaterOn();
else else # if
# else
- if-else 6 if-else # if
if-else * else
if true
if ( 7"#
3" 8" false 7" true (
# else ( else
switch Statement
- switch
( #'
switch ( ) {
case 1
: 1
case 2
: 2
case n
: n
default:
9:
: #
switch
switch # case -
i # case 6 switch
4
( case 6 switch #
default
1 28 # switch
switch
case # 6
# case switch
) 7; ;<" ( case
switch & case boolean long !
switch
= '
See no evil.
Speak no evil.
Hear no evil.
( > 23 howMuchAdvice
switch 3" dispenseAdvice() #
# howMuchAdvice LOTS_OF_ADVICE ( switch
8" -
7" - ;"
break 2" switch
break 2" #
# > break switch
switch ) 2; 3?8" (
howMuchAdvice MORE_ADVICE 7" ;"
LITTLE_ADVICE ;" 4
default #
case #
" case case
case LITTLE_ADVICE > 23 #
;" 2"
break switch
}
}
= '
) case #
> 27 switch 3"
switch case
# #
) # case
switch ( # switch ) switch
# case # case
#
) ;2 387" ( > 27 switch
8" # switch
# switch 4 break
switch #
! " switch
= '
Thanksgiving.
Yellow leaves in the fall.
Review Questions
# # @
) #
# if
# # #
# if else
# a#
" # b#
# #
) #
if
# (a b boolean (a = b)
if
4 if if else
= # boolean
if
# # # @
void test(int x) {
switch (x) {
case 1:
case 2:
case 0:
default:
case 4:
}
}
) #
x switch
# case 0 case 1
switch
# #
$ switch case
# switch @
) #
# "4
" #
. '
while
do-while
for
#
while for # do-while
while Statement
while
while ( )
while
true false
# # (
false # ( # while
% boolean #
while # 1 27
while
while # #
while (noSignOfLife())
keepLooking();
) #
;"
do-while Statement
do-while
do
while ( );
do-while
false false
# #
& 1 2; # do-
while
$ do-while
do-while (
while do-while ( #
# 3"
" 8"
do { // (2)
mice.play();
} while (cat.isAway());
for Statement
for ( !
# #
#'
for ( ; ; )
/ 0 %
/ 0 / 0 boolean
true 5 #
# # for 4 "
/ 0
& / 0
for 1 22 % #
6 while '
while ( ) {
for
# int
int sum = 0;
int[] array = {12, 23, 5, 7, 19};
for (int index = 0; index < array.length; index++) // (1)
sum += array[index];
index % / 0 (
/ 0 for
for # / 0 /
0 / 0 / 0
3" # # / 0
) !
i j k int 4
/ 0 for
A# # #
int String" 6
for (int i = 0, String str = "@"; ... ; ...) ...; // (3) Compile time error.
/ 0 !
) ;7 337" 1 8" #
/ 0 # !
# & i j k #
+ # / 0
2" # 1 B"
!
/ 0 !
# for !
/ 0 ! # /
0
4 for! 4 #
( / 0
true C C (;;) #
"
'
break
continue
return
try-catch-finally
throw
assert
Labeled Statements
4
4 #
# #
L1: if (i > 0) {
L1: System.out.println(i); // (1) Not OK. Label redeclared.
}
4 '
4 '
4 # ! break continue
#
break Statement
break # '
> 2; # break
switch break break 7"
for # j 6 2 switch ;"
for
$ break
class BreakOut {
int n = 2;
switch (n) {
case 1: System.out.println(n); break;
case 2: System.out.println("Inner for loop: ");
for (int j = 0; j < n; j++)
if (j == 2)
break; // (3) Terminate loop. Control to (4).
else
System.out.println(j);
default: System.out.println("default: " + n); // (4) Continue here.
}
}
}
= '
1 1.0
2 1.4142135623730951
3 1.7320508075688772
Inner for loop:
0
1
default: 2
4 break break
- #
( #
# '
out:
{ // (1) Labeled block
// ...
if (j == 10) break out; // (2) Terminate block. Control to (3).
System.out.println(j); // Rest of the block not executed if j == 10.
// ...
}
// (3) Continue here.
( > 22 # 6
3E # for 3" 8"
outer 3" break 7" 2"#
outer"
%# " break
class LabeledBreakOut {
public static void main(String[] args) {
int[][] squareMatrix = {{4, 3, 5}, {2, 1, 6}, {9, 7, 8}};
int sum = 0;
outer: // label
for (int i = 0; i < squareMatrix.length; ++i){ // (1)
for (int j = 0; j < squareMatrix[i].length; ++j) { // (2)
if (j == i) break; // (3) Terminate this loop.
// Control to (5).
System.out.println("Element[" + i + ", " + j + "]: " +
squareMatrix[i][j]);
sum += squareMatrix[i][j];
if (sum > 10) break outer;// (4) Terminate both loops.
// Control to (6).
} // end inner loop
// (5) Continue with outer loop.
} // end outer loop
// (6) Continue here.
= '
Element[1, 0]: 2
Element[2, 0]: 9
sum: 11
continue Statement
break continue # '
& continue
class Skip {
public static void main(String[] args) {
for (int i = 1; i <= 5; ++i) {
if (i == 4) continue; // (1) Control to (2).
// Rest of loop body skipped when i has the value 4.
System.out.println(i + "\t" + Math.sqrt(i));
// (2). Continue with increment expression.
} // end for
}
}
= '
1 1.0
2 1.4142135623730951
3 1.7320508075688772
5 2.23606797749979
4 continue # >
continue
( > 2? continue 7" 2"#
5 #
continue ;" B"#
#
class LabeledSkip {
public static void main(String[] args) {
int[][] squareMatrix = {{4, 3, 5}, {2, 1, 6}, {9, 7, 8}};
int sum = 0;
outer: // label
for (int i = 0; i < squareMatrix.length; ++i){ // (1)
for (int j = 0; j < squareMatrix[i].length; ++j) { // (2)
if (j == i) continue; // (3) Control to (5).
System.out.println("Element[" + i + ", " + j + "]: " +
squareMatrix[i][j]);
sum += squareMatrix[i][j];
if (sum > 10) continue outer; // (4) Control to (6).
// (5) Continue with inner loop.
} // end inner loop
// (6) Continue with outer loop.
} // end outer loop
System.out.println("sum: " + sum);
}
}
= '
Element[0, 1]: 3
Element[0, 2]: 5
Element[1, 0]: 2
Element[1, 2]: 6
Element[2, 0]: 9
sum: 25
return Statement
return
" # return
# void !void
& # void
/
) 7; BB" 4
23 !void return 4 void
return D #
F return
> 2<
return % 23
# return
return ; #
+ return
public static void main (String[] args) { // (1) void method can use return.
if (args.length == 0) return;
output(checkValue(args.length));
}
static void output(int value) { // (2) void method need not use return.
System.out.println(value);
return 'a'; // Not OK. Cannot return a value.
}
Review Questions
# # @
class MyClass {
public static void main(String[] args) {
boolean b = false;
int i = 1;
do {
i++;
b = ! b;
} while (b);
System.out.println(i);
}
}
) #
# b
do-while
# # b = ! b #
# # # 1#
" # # # 2#
# # # 3#
& # # # @
) # #
# 9
# # 10
# 11
" # 9
# 10
# 11
' for @
) #
+ # # @
class MyClass {
) #
# for 3"
# # for 8"
# for 7"
# # #
#
# # # #
, # # @0
) #
while () break;
if (true) { break; }
- G # # # #
@
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
if (i == j) {
continue outer;
}
System.out.println("i=" + i + ", j=" + j);
}
) # #
i=1, j=0
# i=0, j=1
i=1, j=2
i=2, j=2
i=3, j=3
i=3, j=2
# # @
class MyClass {
public static void main(String[] args) {
for (int i = 0; i<10; i++) {
switch(i) {
case 0:
System.out.println(i);
}
if (i) {
System.out.println(i);
}
}
}
}
) #
# # switch switch
# # # if
# # # 0 10 #
" # # # 0#
# # # 0 # #
# # # 1 10 #
# max() #
@
// (1)
int max(int x, int y) {
return (if (x > y) { x; } else { y; });
}
// (2)
int max(int x, int y) {
return (if (x > y) { return x; } else { return y; });
}
// (3)
int max(int x, int y) {
switch (x < y) {
case true:
return y;
default:
return x;
};
}
// (4)
int max(int x, int y) {
if (x>y) return x;
return y;
}
) #
( 3"
# ( 8"
( 7"
" ( ;"
G # # @
class MyClass {
public static void main(String[] args) {
int k=0;
int l=0;
for (int i=0; i <= 3; i++) {
k++;
if (i == 2) break;
l++;
}
System.out.println(k + ", " + l);
}
}
) #
# # 3, 3 #
# 4, 3 # break continue
# break
$ @
) # #
{{}}
# { continue; }
#! !
# 4
# #
# # # #! !
try!catch!finally
) .
HI - J" > #
"
> "
> # # #
#
>
# #
4
# F
> 2J (
( '
main() # printAverage() #
3"
computeAverage()
?"
,) "
= '
Computing average.
Average = 100 / 20 = 5
Exit printAverage().
Exit main().
> > 2J 1
2B > # #
#
System.out.println() B" 1 2B
'main() printAverage() computeAverage() 2
computeAverage() ?" 1 2B
# 6 1 2B
& ) "
( 3" > 2J
#'
Computing average.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Average1.computeAverage(Average1.java:18)
at Average1.printAverage(Average1.java:10)
at Average1.main(Average1.java:5)
1 2? 4 # return ?"
computeAverage() 4
sum/number E
.HI ArithmeticException C
> C 3<2"
.
HI
' .
1 2? # #
# ( 1 2? computeAverage()
# # return
?" ) #
#
#
# printAverage()"
# ;" 2"
printAverage() #
main()" # main()
8" main() )
# F
#
# # # 4
#
( # !
) #
"
( #
.
( . ! ! " .
HI . 8)+K'
+ . ( /
Throwable String
4 # !
Throwable # 6 '
String getMessage()
void printStackTrace()
L
6 # # #
# PrintStream PrintWriter
# printStackTrace()
String toString()
$ #
# getMessage()
Class Exception
Exception # # #
( RuntimeException
"= Exception
(
:=! IOException
FileNotFoundException EOFException" G,(! AWTException"
Class RuntimeException
$ ! ! ArrayIndexOutOfBounds Exception"
% NullPointerException"
ClassCastException" IllegalArgumentException" %
ArithmeticException" NumberFormatException"
java.lang.RuntimeException # Exception
4
Class Error
AssertionError java.lang.Error .
) 23E 8E<" = java.lang.Error
LinkageError" ThreadDeath"
VirtualMachineError"
#
# # 1 2<" Error
" #
RuntimeException " #
4
# # super()
# &
* # 6
# #
// Constructor
public EvacuateException(Date d, Zone z, TransportMode t) {
// Call the constructor of the superclass
super("Evacuation of zone " + z);
// ...
}
// Methods
// ...
}
) 6
<statements>
}
, try-catch-finally 0 1
4 #
1 try % catch finally catch
finally # * # try
4 try # catch finally >
catch catch
# #
Throwable
try Block
try #
try
1 try catch
finally 3" 1 2J"
1 try catch
D D catch 8" 1 2J" (
catch # finally
7" 1 2J"
catch Block
= try catch 4
catch #
catch ) BB 8BE" catch
catch
= catch
# (
4 catch # finally
# finally # catch
#
- try-catch 2
Computing average.
Average = 100 / 20 = 5
Exit printAverage().
Exit main().
= # printAverage(100, 0) 3"
'
Computing average.
java.lang.ArithmeticException: / by zero
at Average2.computeAverage(Average2.java:24)
at Average2.printAverage(Average2.java:11)
at Average2.main(Average2.java:5)
Exception handled in printAverage().
Exit printAverage().
Exit main().
- / " 3 4
printAverage(100, 0)
ArithmeticException # computeAverage() 1
1 233# computeAverage()
printAverage() # catch B"
& J" try!catch #
J" 8" ) 8 1 2J
/ " 3 4
/ " 3 4
= '
Computing average.
java.lang.ArithmeticException: / by zero
at Average3.computeAverage(Average3.java:30)
at Average3.printAverage(Average3.java:17)
at Average3.main(Average3.java:6)
Exception handled in main().
Exit main().
catch 4
* catch
) BB 8BE" ( catch * 6
* javac catch
# catch catch
# # #
catch 3" 8" # # ' Exception #
# ArithmeticException
...
// Compiler complains
catch (Exception e) { // (1) superclass
System.out.println(e);
} catch (ArithmeticException e) { // (2) subclass
System.out.println(e);
}
...
finally Block
( try finally
# catch # ) finally #
!
"
4 try!finally # #
#
try sumNumbers() #
calculateAverage() # finally #
try 4 calculateAverage()
sumNumbers() sum calculateAverage()
catch
( finally #
return break try catch #
finally 1 2J 3<J"
( # try
catch finally
( #
catch # catch # "
finally
( finally # #
D # try catch # (
#
try-catch-finally 2
Computing average.
Average = 100 / 20 = 5
Finally done.
Exit printAverage().
Exit main().
= # printAverage(100, 0) 3"
'
Computing average.
java.lang.ArithmeticException: / by zero
at Average4.computeAverage(Average4.java:26)
at Average4.printAverage(Average4.java:11)
at Average4.main(Average4.java:5)
Exception handled in printAverage().
Finally done.
Exit printAverage().
Exit main().
= finally
> 237
printAverage() finally B"
ArithmeticException # J" (
& > 238
> 237
try-finally 2
= '
Computing average.
Finally done.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Average5.computeAverage(Average5.java:21)
at Average5.printAverage(Average5.java:10)
at Average5.main(Average5.java:4)
Computing average.
Average = 100 / 20 = 5
Finally done.
Average: 10
Exit main().
= # printAverage(100, 0) 3"
'
Computing average.
Finally done.
Average: 0
Exit main().
throw ;
/ 0 Throwable
4 NullPointerException # / 0
null Throwable # # 4
# *
#
catch try
try
4 finally try
( #
( # catch
= '
Computing average.
Finally in printAverage().
java.lang.ArithmeticException: Integer division by 0
at Average7.computeAverage(Average7.java:35)
at Average7.printAverage(Average7.java:19)
at Average7.main(Average7.java:6)
Exception handled in main().
Finally in main().
Exit main().
... someMethod(...)
throws ! 1
, ! 2
,..., ! n
{ ... }
> ! i
# throws =
# throws
* *
* ) B3 88B" throws
A % ) <8 773
4 # throw
#
# # (
try #
try #
throws
# throws
#
# # ( #
& throws
4 # > 23B
IntegerDivisionByZero 33" Exception
& throws 2
System.out.println("Computing average.");
if (number == 0) // (9)
throw new IntegerDivisionByZero("Integer Division By Zero");
return sum/number; // (10)
}
}
= '
Computing average.
IntegerDivisionByZero: Integer Division By Zero
at Average8.computeAverage(Average8.java:33)
at Average8.printAverage(Average8.java:22)
at Average8.main(Average8.java:7)
Exception handled in main().
Finally done in main().
Exit main().
throws
# #
throws ( # A B
C# D throws A B C
* D ( printAverage()
Exception IntegerDivisionByZero throws
( throws
# #
L # #
#
4 #
) B8 877" # #
throws @
" throws
#
throws 4 #
# # #
) # *
" # #
class A {
// ...
class B extends A {
// ...
protected void superclassMethodX()
throws FirstException, ThirdException { /* ... */ } // (2)
// ...
( superclassMethodX A B
throws B 8"
3"
Review Questions
# # # # @
) #
# 5
# # 1 4
# 1 2 4
" # 1 4 5
# 1 2 4 5
# 3 5
& G # # @
) # #
( # #
# ( # # "The end"
# # ArrayIndexOutOfBoundsException
" ( # #
( # # #
"The end"
' # # @
) #
# main()
# RuntimeException
# # # re
# # # #
java.lang.RuntimeException #
" # # # #
java.lang.NullpointerException #
# # # #
+ @
) # #
( #
#
# 4 #
main() #
" 4 # #
finally # #
try
, # # # #
@
) #
# 5
# # 1 4
# 1 2 4
" # 1 4 5
# 1 2 4 5
# 3 5
- # # # # @
) #
# 2 # InterruptedException.
# # 1 2
# 1 2 3
" # 2 3
# 3 2
# 1 3
# # # @
}
}
class B extends A {}
) #
main() # B
catch main() B
A
f()
# throws # @
class A {
// InterruptedException is a direct subclass of Exception.
void f() throws ArithmeticException, InterruptedException {
div(5, 5);
}
int div(int i, int j) throws ArithmeticException {
return i/j;
}
}
) #
# & # ArithmeticException
& # InterruptedException
& # ArithmeticException
InterruptedException
# # @
class A {
void f() throws ArithmeticException {
//...
}
}
try {
obj.f();
} catch (ArithmeticException e) {
return;
} catch (Exception e) {
System.out.println(e);
throw new RuntimeException("Something wrong here");
}
}
// InterruptedException is a direct subclass of Exception.
void f() throws InterruptedException {
//...
}
}
) #
main() # RuntimeException
# f() MyClass #
ArithmeticException f() A
f() MyClass # #
InterruptedException f() A #
" # catch(ArithmeticException) #
catch(Exception)
M # catch
& # # # #
5.10 Assertions
4 .
>
true # ( false #
"( #
",
* #
# # assert '
( 838" assert #
1 237 # 6 # '
assert 36
# "4
( ( true
assert A# false AssertionError #
( AssertionError
( false
AssertionError
" AssertionError
(
void #
7"
assert time > 0.0 : "Time is not a positive value: " + time; // (3)
7" 6 # '
if (time <= 0.0) throw new AssertionError("Time is not a positive value: " + time);
'
assert time >0.0 : "Time is not a positive value: " + time; // (3)
double speed = distance / time;
assert speed >= 0.0; // (4)
return speed;
}
}
Compiling Assertions
# .
8)>3; 4 # # javac
# #
# assert #
assert #
# # '
H # #
# * assert (# # # assert
( # # assert #
" # - Legacy
# '
> #
6
# # java #
# -enableassertions -ea #
disableassertions -da
# 28
# 7 # " # 8
7
-ea 4 !
-da
-ea:<package name>... 4
-da:<package name>...
-ea:... 4 #
-da:...
-ea:<class name> 4
-da:<class name>
-ea
4 . 1
java.* 4 .
HI
& # .
8)>3;! #
4 %
4 ! " Speed
( 6 # -ea -da
>java Speed
Speed (km/h): -4.0
7" #
#
#
4 # Trickster
wizard # 1 ;7 38?
# ! #
wizard.pandorasBox wizard.pandorasBox.artifacts
Trickster
... # & !
6
# ! #
Trickster
& #
# # Trickster
# #
wizard.pandorasBox.artifacts.Ailment
4 java # #
#
# # # ! #
# #
wizard.pandorasBox wizard.pandorasBox.artifacts
wizard.pandorasBox.artifacts.Ailment
# # wizard.spells.Baldness
( # ) B3 88B"
4 ! #
( #
wizard.pandorasBox.artifacts.Ailment #
wizard.spells.Baldness '
( # # #
27 >
.
HI ( # # #
# # wizard wizard.pandorasBox
wizard.pandorasBox.artifacts wizard.spells # #
wizard.pandorasBox.artifacts
# # " # 2 8
9
-enablesystemassertions -esa >
-disablesystemassertions -dsa +
Using Assertions
4 #
#
# # #
# 6
assert reactor.controlCoreTemperature();
4 4
4 F #
# 4 #
AssertionError
4
IllegalArgumentException IndexOutOfBoundsException
NullPointerException.
Internal Invariants
H #
3" status else
# 8"
=
4 switch # default
switch case default
# #
switch (trinityMember) {
case Housefather:
...
break;
case THE_SON:
...
break;
case THE_HOLY_GHOST:
...
break;
}
4 default
default:
assert false : trinityMember;
( AssertionError #
A# ! !void case
return # switch
switch (trinityMember) {
case THE_FATHER:
return psalm101;
case THE_SON:
return psalm102;
case THE_HOLY_GHOST:
return psalm103;
default:
assert false: trinityMember;
}
return psalm100; // (3) Compile time error if commented out.
7" # #
!void > # AssertionError assert
default #
default:
- # #
# #
( #
( #
3"
3"
- assert
1 while # #
true # assert
1
#
" # 4
1 !
) J; 72J" !synchronized
# # *
" L
* 1
adjustReactorThroughPut()
#
) ?; 7E8" #
Other Uses
( % % #
'
( %
) <8 773"
Review Questions
$ 4 # # #
@
) # #
# @
) # #
-ae
# -enableassertions
-source 1.4
" -disablesystemassertions
-dea
& # @
) #
# FailedAssertion
AssertionException
" RuntimeException
AssertionError
Error
' @
) #
&
# ,
" ,
+ G # # # #
@
) # #
inv(-50);
# inv(0);
inv(50);
" inv(100);
inv(150);
, #
org.example.ttp.Bottle@
) # #
-ea
# -ea:Bottle
-ea:org.example
" -ea:org...
-enableexceptions:org.example.ttp.Bottle
-ea:org.example.ttp
- # # #
@
) #
assertBounds #
# assert
# assert
AssertionError # "too
high" #
AssertionError @
) # #
# ( toString()
( getErrorMessage()
" ( try!catch
AssertionError@
) #
Object
# Throwable
Exception
" Error
RuntimeError
G # # # @
) # #
com.example.Translator
# java.lang.String
dot.com.Boom
" net.example.LaunchTranslator
java.lang.AssertionError
Chapter Summary
# # '
4L(
try!catch!finally #
# # throw
throws
assert
Programming Exercises
- # 3EE -
for while do-while" -
while
A # (
Control I .
# )
4
/** Get the level of reactor output that is most desirable at this time.
(Units are unspecified.) */
public int getOptimalThroughput() {
// ... implementation unspecified ...
return 0;
}
/** A reactor core that has a throughput that can be either decreased or
increased. */
class Reactor {
/** Get the current throughput of the reactor. (Units are
unspecified.) */
public int getThroughput() {
// ... implementation unspecified ...
return 0;
}
return false;
}
/** This exception class should be used to report that the reactor status is
critical. */
class ReactorCritical extends Exception {}
/** A controller that will manage the power plant and make sure that the
reactor runs with optimal throughput. */
class Control {
PowerPlant thePlant;
public Control(PowerPlant p) {
thePlant = p;
}
}
}