A statement is essentially any complete sentence that causes
some action to occur. It can encompass multiple operators
and operands, as well as multiple sub-statements.
For example, the statement
int
x = 1;
declares a variable x
and then assigns the value 1 to it.
This statement
x
= 5.3 *(4.1 / Math.cos (0.2*y));
consists of several expressions - multiplication, division, a method
call to a math function - but is still considered a single statement.
Note: A group of statements
enclosed in parentheses - called a code block - acts as
a single statement. The basic if
statement, see below, executes a statement if the test is true,
as in
if
(a < b) statement ;
where statement
is executed if a
is less than b.
However, it could also execute a whole block of code as in
if
(a < b) {
statement 1;
statement 2;
...
}
where all the statements within the parentheses will execute
if a is
less than b.
Note that a semi-colon is not used after the right parenthesis.
Basic Statements
We list below several important kinds of statements. Some of these
are discussed in more detail in the Chapter
2: Java Supplements.
- Declarations
Statements that create identifiers, or variable names, for primitive
type values and object references. Java is a strongly typed
language so every variable must be declared of a particular type.
An initializer in the declaration can assign a value to the variable:
int
x;
int x, y; <- multiple declaration
double y=1.0; <- Declaration &
initializer
double x=5.0, y;
- Conditional
if-else Statement:
if
(i > 10) {
j++:
} else {
j=0;
}
- Repetitive
Loop Statements:
for
loop
for
(i = 0; i < 10; i++) j++;
while
loops
while (i < 5) {
i = a.doSomething ();
}
do/while
loops
do{
i = a.doSomething ();
} while (i < 5)
Enhanced for
loop (added with Java 5.0)
for
(type value : container) statement
where container a Java object, such as an array
(see Chatper 3) that contains other objects.
The statement goes as
read "for each value in container,
do the statement.". We will return
to this statement in Chapter
10.
- Other
Flow statements:
break
statement
& statement labels
while
(i < 5) {
i = a.doSomething ();
if (i < 0)
break; // jump out of the
loop
}
continue
statement
jmp0:
while (b.func()){
for (int i = 0; i < 4;
i++){
if (a.func ())
continue
jmp0; // jump to start of outer loop
}
}
switch
statement
switch (i) {
case 1: b.func
();
case 2: a.func
();
default: c:func
();
}
- Invoking a method (Java
version of a subroutine. Methods discussed later):
Math.sin
(0.3);
|