Java Lecture 1
Java Lecture 1
if statements
Execute an action if the s$ecified condition is true
:an )e re$resented )* a decision s*m)ol (diamond# in a
@8L activit* diagram
Transition arro's out of a decision s*m)ol have guard
conditions
6or+flo' follo's the transition arro' 'hose guard
condition is true
"0
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 503 2 if singe*seection statement /ML activity diagram0
"1
1992-2007 Pearson Education, Inc. All rights reserved.
ifelse Dou(e*,eection ,tatement
ifelse statement
Executes one action if the s$ecified condition is true or a
different action if the s$ecified condition is false
:onditional 3$erator ( ? : #
Java1s onl* ternar* o$erator (ta+es three o$erands#
? : and its three o$erands form a conditional ex$ression
Entire conditional ex$ression evaluates to the second
o$erand if the first o$erand is true
Entire conditional ex$ression evaluates to the third o$erand
if the first o$erand is false
"2
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 504 2 if@ese dou(e*seection statement /ML activity diagram0
"3
1992-2007 Pearson Education, Inc. All rights reserved.
ifelse Dou(e*,eection ,tatement
-Cont0.
Nested ifelse statements
ifelse statements can )e $ut inside other ifelse
statements
/angling5else $ro)lem
elses are al'a*s associated 'ith the immediatel*
$receding if unless other'ise s$ecified )* )races { }
<loc+s
<races { } associate statements into )loc+s
<loc+s can re$lace individual statements as an if )od*
"4
1992-2007 Pearson Education, Inc. All rights reserved.
ifelse Dou(e*,eection ,tatement
-Cont0.
Logic errors
=atal logic errors cause a $rogram to fail and terminate
$rematurel*
Nonfatal logic errors cause a $rogram to $roduce incorrect
results
Em$t* statements
7e$resented )* $lacing a semicolon ( ; # 'here a statement
'ould normall* )e
:an )e used as an if )od*
"
1992-2007 Pearson Education, Inc. All rights reserved.
Aood Programming Practice 505
9l'a*s using )races in an if...else (or
other# statement hel$s $revent their
accidental omission, es$eciall* 'hen
adding statements to the if5$art or the
else5$art at a later time( To avoid omitting
one or )oth of the )races, some
$rogrammers t*$e the )eginning and
ending )races of )loc+s )efore t*$ing the
individual statements 'ithin the )races(
"!
1992-2007 Pearson Education, Inc. All rights reserved.
'epetition ,tatement
6
?hile statement
7e$eats an action 'hile its loo$5continuation condition
remains true
@ses a merge s*m)ol in its @8L activit* diagram
8erges t'o or more 'or+flo's
7e$resented )* a diamond (li+e decision s*m)ols# )ut has%
8ulti$le incoming transition arro's,
3nl* one outgoing transition arro' and
No guard conditions on an* transition arro's
"7
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 505 2 ?hile repetition statement /ML activity diagram0
""
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: Counter*
Controed 'epetition
:ounter5controlled re$etition
@se a counter varia)le to count the num)er of times a loo$
is iterated
;nteger division
The fractional $art of an integer division calculation is
truncated (thro'n a'a*#
"9
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 506 2 Pseudocode agorit"m t"at uses counter*controed repetition to sove t"e
cass*average pro(em0
1 Set total to zero
2 Set grade counter to one
3
4 While grade counter i le than or e!ual to ten
" Prompt the uer to enter the ne#t grade
$ %nput the ne#t grade
& Add the grade into the total
' Add one to the grade counter
(
1) Set the cla a*erage to the total di*ided b+ ten
11 Print the cla a*erage
90
1992-2007 Pearson Education, Inc. All rights reserved.
@rade2oo#.Aava
91
1992-2007 Pearson Education, Inc. All rights reserved.
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture134ava 5radeBoo2
Enter #rade: 12
Enter #rade: )
Enter #rade: 12
Enter #rade: 12
Enter #rade: %
Enter #rade: '
Enter #rade: (
Enter #rade: )
Enter #rade: 9
Enter #rade: (
.ota" o6 a"" 10 #rades is )1
*"ass avera#e is )
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture13
92
1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming %rror 506
9ssuming that integer division rounds
(rather than truncates# can lead to
incorrect results( =or exam$le, L N I,
'hich *ields (L5 in conventional
arithmetic, truncates to in integer
arithmetic, rather than rounding to "(
93
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: ,entine*
Controed 'epetition
Sentinel5controlled re$etition
9lso +no'n as indefinite re$etition
@se a sentinel value (also +no'n as a signal, dumm* or flag
value#
9 sentinel value cannot also )e a valid in$ut value
94
1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming %rror 50>
:hoosing a sentinel value that is also a
legitimate data value is a logic error(
9
1992-2007 Pearson Education, Inc. All rights reserved.
%rror*Prevention Tip 503
6hen $erforming division )* an
ex$ression 'hose value could )e Bero,
ex$licitl* test for this $ossi)ilit* and
handle it a$$ro$riatel* in *our $rogram
(e(g(, )* $rinting an error message#
rather than allo' the error to occur
9!
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 508 2 Cass*average pro(em pseudocode agorit"m !it" sentine*controed repetition0
1 %nitialize total to zero
2 %nitialize counter to zero
3
4 Prompt the uer to enter the ,irt grade
" %nput the ,irt grade -poibl+ the entinel.
$
& While the uer ha not +et entered the entinel
' Add thi grade into the running total
( Add one to the grade counter
1) Prompt the uer to enter the ne#t grade
11 %nput the ne#t grade -poibl+ the entinel.
12
13 %, the counter i not e!ual to zero
14 Set the a*erage to the total di*ided b+ the counter
1" Print the a*erage
1$ ele
1& Print /0o grade 1ere entered2
97
1992-2007 Pearson Education, Inc. All rights reserved.
9"
1992-2007 Pearson Education, Inc. All rights reserved.
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture134ava 5radeBoo27$i"e
Enter #rade or -1 to 8uit: %&
Enter #rade or -1 to 8uit: 1(
Enter #rade or -1 to 8uit: '
Enter #rade or -1 to 8uit: -1
.ota" o6 a"" 10 #rades is ''
*"ass avera#e is 1)%%
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture13
99
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: ,entine*
Controed 'epetition -Cont0.
@nar* cast o$erator
:reates a tem$orar* co$* of its o$erand 'ith a different
data t*$e
exam$le% (doule! 'ill create a tem$orar* floating5$oint
co$* of its o$erand
Ex$licit conversion
-romotion
:onverting a value (e(g( int# to another data t*$e (e(g(
doule# to $erform a calculation
;m$licit conversion
100
1992-2007 Pearson Education, Inc. All rights reserved.
Formuating #gorit"ms: ?ested Contro
,tatements
:ontrol statements can )e nested 'ithin one
another
-lace one control statement inside the )od* of the other
101
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5011 2 Pseudocode for examination*resuts pro(em0
1 %nitialize pae to zero
2 %nitialize ,ailure to zero
3 %nitialize tudent counter to one
4
5 While tudent counter i le than or e!ual to 1)
6 Prompt the uer to enter the ne#t e#am reult
7 %nput the ne#t e#am reult
8
9 %, the tudent paed
10 Add one to pae
11 3le
12 Add one to ,ailure
13
14 Add one to tudent counter
15
16 Print the number o, pae
17 Print the number o, ,ailure
18
19 %, more than eight tudent paed
20 Print /4aie tuition2
102
1992-2007 Pearson Education, Inc. All rights reserved.
103
1992-2007 Pearson Education, Inc. All rights reserved.
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture134ava !na"ysis
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 2
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Enter resu"t 91 : +ass, 2 : 6ai";: 1
Passed: 9
<ai"ed: 1
=ard>or2in# c"ass
*:01ocuments and /ettin#s0Omer01es2to+0Java *ourse0Lecture13
104
1992-2007 Pearson Education, Inc. All rights reserved.
Compound #ssignment Operators
:om$ound assignment o$erators
9n assignment statement of the form%
*ariable " *ariable operator e#preion;
'here operator is #, -, $, / or % can )e 'ritten as%
*ariable operator" e#preion;
exam$le% c " c # &; can )e 'ritten as c #" &;
This statement adds & to the value in varia)le c and stores
the result in varia)le c
10
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5015 2 #rit"metic compound assignment operators0
#ssignment
operator
,ampe
expression
%xpanation #ssigns
Aume5 int c D 9= D <= e D ;= f D C= g D 12+
FD c FD 4 0 D c F 4 1G to c
-D -D ; D - ; 1 to
.D e .D < e D e . < 2G to e
/D f /D 9 f D f / 9 2 to f
BD g BD H g D g B H 9 to g
10!
1992-2007 Pearson Education, Inc. All rights reserved.
Increment and Decrement Operators
@nar* increment and decrement o$erators
@nar* increment o$erator (### adds one to its o$erand
@nar* decrement o$erator (--# su)tracts one from its
o$erand
-refix increment (and decrement# o$erator
:hanges the value of its o$erand, then uses the ne' value of
the o$erand in the ex$ression in 'hich the o$eration a$$ears
-ostfix increment (and decrement# o$erator
@ses the current value of its o$erand in the ex$ression in
'hich the o$eration a$$ears, then changes the value of the
o$erand
107
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5016 2 Increment and decrement operators0
Operator Caed
,ampe
expression
%xpanation
FF
$refix
increment
FFa
;ncrement a )* 1, then use the ne' value of a in the
ex$ression in 'hich a resides(
FF
$ostfix
increment
aFF
@se the current value of a in the ex$ression in 'hich a resides,
then increment a )* 1(
--
$refix
decrement
--b
/ecrement b )* 1, then use the ne' value of b in the
ex$ression in 'hich b resides(
--
$ostfix
decrement
b--
@se the current value of b in the ex$ression in 'hich b resides,
then decrement b )* 1(
10"
1992-2007 Pearson Education, Inc. All rights reserved.
Outine
Incre%ent.Aa
va
1 // Fig. ;.1C: /ncrement.java
2 // )refix increment an postfix increment operators.
3
4 public class /ncrement
{
! public static voi main" #tring args$% &
7 {
" int c+
9
10 // emonstrate postfix increment operator
11 c D <+ // assign < to c
12 #'stem.out.println" c &+ // print <
13 #'stem.out.println" cFF &+ // print < then postincrement
14 #'stem.out.println" c &+ // print C
1
1! #'stem.out.println"&+ // s8ip a line
17
1" // emonstrate prefix increment operator
19 c D <+ // assign < to c
20 #'stem.out.println" c &+ // print <
21 #'stem.out.println" FFc &+ // preincrement then print C
22 #'stem.out.println" c &+ // print C
23
24 , // en main
2
2! , // en class /ncrement
<
<
C
<
C
C
Postincre%enting the c varia'le
Preincre%enting the c varia'le
109
1992-2007 Pearson Education, Inc. All rights reserved.
Fig0 5017 2 Precedence and associativity of t"e operators discussed so far0
Operators #ssociativity Type
FF -- right to left unar* $ostfix
FF -- F - " t+pe & right to left unar* $refix
. / B left to right 8ulti$licative
F - left to right 9dditive
K KD J JD left to right 7elational
DD *D left to right EFualit*
N: right to left :onditional
D FD -D .D /D BD right to left assignment
110
1992-2007 Pearson Education, Inc. All rights reserved.
Primitive Types
Java is a strongl* t*$ed language
9ll varia)les have a t*$e
-rimitive t*$es in Java are $orta)le across all
$latforms that su$$ort Java
111
1992-2007 Pearson Education, Inc. All rights reserved.
Porta(iity Tip 501
@nli+e : and :MM, the $rimitive t*$es in
Java are $orta)le across all com$uter
$latforms that su$$ort Java( Than+s to this
and JavaDs man* other $orta)ilit* features,
a $rogrammer can 'rite a $rogram once
and )e certain that it 'ill execute on an*
com$uter $latform that su$$orts Java( This
ca$a)ilit* is sometimes referred to as WO4A
(6rite 3nce, 7un 9n*'here#(