Java Reference
In-Depth Information
Java syntax: if-statement
if ( boolean-expression )
Java syntax: if-else statement
if ( boolean-expression )
Example : if (x < 0) {
x= -x;
then-part and else-part : each is a statement
Then-part: any statement
Example : if (x < y) {
y= y-x;
} else {
x= x - y ;
Execution : Evaluate the
boolean-expression . If it is true ,
execute the then-part .
Execution : Evaluate the boolean-expression . If true , exe-
cute the then-part ; otherwise, execute the else-part .
The if-statement
There are situations in which you would do something depending on
whether some condition is true. For example, if it is cold, you would put your
coat on, but not if it is warm.
In a Java program, a conditional statement is used for this purpose. As an
example, the statement below tests whether x<0 , and if so, it executes the
assignment x= -x; . But if x≥0 , the assignment is not executed.
Style Note
13.2, 13.2.1:
indenting if-
if (x < 0) x= -x;
An if-statement has this form:
if ( condition ) then-part
where the condition is a boolean expression and the then-part is a statement.
To execute an if-statement, evaluate the condition; if it is true , execute the
then -part. If the boolean expression is false , execution of the if-statement is
The block
Suppose we want a statement that adds 2 to both x and y if x is larger than
y . To do this, we write the then-part of the if-statement as a block : a sequence of
statements enclosed in braces { and } . Here is the Java code for it:
// Add 2 to both x and y if x>y
if (x > y) {
x= x + 2;
y= y + 2;
The braces { and } are used to aggregate the sequence of statements into a
Search WWH ::

Custom Search