Statements
Actions are defined by a list of statements that are instructions to be executed in some sequence. A statement can include one or more expressions.
Variable declarations
Declaration statements declare variables and constants, specifying their data type, name, and initial value. Some examples are given in the following:.
int a = 42;
a
of type int
and assigns it the value 42
.
String text = "Hello";
The declaration statement above declares a variable named text
of type
String
and assigns it the value "Hello"
.
A variable data type may also be some object type.
Person person = Person.Person();
The declaration statement above declares a variable named person
of type
Parson
and assigns the variable to a new object of type Person
;
Expression statements
x = 14;
foo.callToAMethod();
Statement block
x = 15;
{
int y = 13;
foo.someMethodCall();
}
if (condition) thenStatement;
else elseStatement;
Control statements
If-else
if (condition) {
// Statements
} else {
// Statements
}
While loop
while (condition) {
// Statements
}
Do-while loop
do {
// Statements
} while (condition)
do
.
After each execution of the statement block, the condition is evaluated.
If it evaluates to true
, then the statement block is executed again.
For loop
There are three different versions of the for loop.
// Creating control variables:
for (int i = expr, j = expr; condition; i++, j--) {
// Statements
}
// Initializing existing control variables
for (i = expr, j = expr; condition; i++, j--) {
// Statements
}
// For-iteration
for (int val : IntCollection) {
// Statements
}
Switch
switch (expression) {
case CONSTANT_OR_ENUM_VAL: /* statements */ break;
default: /* statements */ break;
}
break;
statement.
The statements of the default
case are executed if the evaluated expression
value does not match any other case.
Break
The break;
statement is not only available in switch
statements, but also in loops in which they terminate the loop early.