Java Reference
In-Depth Information
if (numMonthlySales > 100)
wage += bonus;
Ifthenumberofmonthlysalesexceeds100, numMonthlySales > 100 evaluates
totrueandthe wage += bonus; assignmentstatementexecutes.Otherwise,thisas-
signment statement does not execute.
If-Else Statement
Theif-elsestatementevaluatesaBooleanexpressionandexecutesoneoftwostatements
dependingonwhetherthisexpressionevaluatestotrueorfalse.Thisstatementhasthe
following syntax:
if ( Boolean expression )
statement1
else
statement2
If-else consists of reserved word if , followed by a Boolean expression in
parentheses,followedbya statement1 toexecutewhen Boolean expression
evaluatestotrue,followedbya statement2 toexecutewhen Boolean expres-
sion evaluates to false.
The following example demonstrates this statement:
if ((n&1) == 1)
System.out.println("odd");
else
System.out.println("even");
Thisexampleassumestheexistenceofan int variablenamed n thathasbeeninitial-
izedtoaninteger.Itthenproceedstodeterminewhethertheintegerisodd(notdivisible
by 2) or even (divisible by 2).
TheBooleanexpressionfirstevaluates n&1 ,whichbitwiseANDs n 'svaluewith 1 .
Itthencomparestheresultto 1 .Iftheyareequal,amessagestatingthat n 'svalueisodd
outputs; otherwise, a message stating that n 's value is even outputs.
Theparenthesesarerequiredbecause == hashigherprecedencethan & .Withoutthese
parentheses,theexpression'sevaluationorderwouldchangetofirstevaluating 1 == 1
andthentryingtobitwiseANDtheBooleanresultwith n 'sintegervalue.Thisorderres-
ultsinacompilererrormessagebecauseofatypemismatch:youcannotbitwiseAND
an integer with a Boolean value.
Search WWH ::




Custom Search