Java applications evaluate expressions in the context of statements, which are used for tasks such as declaring a variable, making a decision, or iterating over statements. A statement can be expressed as a simple or a compound statement:
- A simple statement is a single standalone instruction for performing a task; it must be terminated with a semicolon character (
;
). - A compound statement is a sequence of simple and other compound statements located between open- and close-brace characters (
{
and}
), which delimit the compound statement's boundaries. Compound statements can be empty, will appear wherever simple statements appear, and are alternatively known as blocks. A compound statement is not terminated with a semicolon.
In this tutorial, you'll learn how to use statements in your Java programs. You can use statements such as if
, if-else
, switch
, for
, and while
to declare variables and specify expressions, make decisions, iterate (or loop) over statements, break and continue iteration, and more. I'll leave some of the more exotic statements--such as statements for returning values from called methods and for throwing exceptions--for future Java 101 tutorials.
Variable declarations and assignments
I've previously introduced Java variables and explained that they must be declared before being used. Because a variable declaration is a standalone island of code, it's effectively a statement--a simple statement, to be exact. All of these are variable declaration statements:
int age = 25;
float interest_rate;
char[] text = { 'J', 'a', 'v', 'a' };
String name;
A variable declaration minimally consists of a type name, optionally followed by a sequence of square-bracket pairs, followed by a name, optionally followed by a sequence of square-bracket pairs, and terminated with a semicolon. A variable may also be explicitly initialized during its declaration.
Now consider the assignment statement, which is closely related to the variable declaration statement. An assignment statement assigns a value (possibly a reference to an array or a reference to an object) to a variable. Here are some examples:
age = 30;
interest_rate = 4.0F;
age += 10;
text[1] = 'A';
text[2] = 'V';
text[3] = 'A';
name = "John Doe";
An assignment statement is an example of an expression statement, which is an expression that may be used as a statement if it is followed with a semicolon. The following expressions also qualify as expression statements:
- Preincrement (e.g.,
++x;
) - Predecrement (e.g.,
--y;
) - Postincrement (e.g.,
x++;
) - Postdecrement (e.g.,
y--;
) - Method call (e.g.,
System.out.println("Hello");
) - Object creation (e.g.,
new String("ABC");
)
Variable declarations with jshell
You can use jshell
to experiment with variable declarations and expression statements. Here are some examples to get you started (see "Learn Java from the ground up" for an introduction to the Java Shell):
jshell> int age = 25
age ==> 25
jshell> float interest_rate
interest_rate ==> 0.0
jshell> char[] text = { 'J', 'a', 'v', 'a' }
text ==> char[4] { 'J', 'a', 'v', 'a' }
jshell> String name
name ==> null
jshell> age = 30
age ==> 30
jshell> interest_rate = 4.0F
interest_rate ==> 4.0
jshell> age += 10
$7 ==> 40
jshell> text[1] = 'A'
$8 ==> 'A'
jshell> text[2] = 'V'
$9 ==> 'V'
jshell> text[3] = 'A'
$10 ==> 'A'
jshell> name = "John Doe"
name ==> "John Doe"
jshell> text
text ==> char[4] { 'J', 'A', 'V', 'A' }
jshell> age++
$13 ==> 40
jshell> age
age ==> 41
Notice that age++
doesn't appear to have accomplished anything. Here, you see that 40
has been assigned to the scratch variable $13
. However, the postincrement operator performs the increment after returning the current value. (Actually, it stores the current value somewhere, performs the increment, and then returns the stored value.) Entering age proves that age
contains 41, the result of the postincrement operation.
The Java Shell provides various commands and features that simplify working with snippets. For example, the /list
command shows all snippets that have been entered in the current session:
jshell> /list
1 : int age = 25;
2 : float interest_rate;
3 : char[] text = { 'J', 'a', 'v', 'a' };
4 : String name;
5 : age = 30
6 : interest_rate = 4.0F
7 : age += 10
8 : text[1] = 'A'
9 : text[2] = 'V'
10 : text[3] = 'A'
11 : name = "John Doe"
12 : text
13 : age++
14 : age
The number in the left column uniquely identifies a snippet. You can use this number to re-execute a snippet, list the snippet, drop (delete) a snippet, and so on:
jshell> /12
text
text ==> char[4] { 'J', 'A', 'V', 'A' }
jshell> /list 13
13 : age++
jshell> /drop 7
| dropped variable $7
jshell> /list
1 : int age = 25;
2 : float interest_rate;
3 : char[] text = { 'J', 'a', 'v', 'a' };
4 : String name;
5 : age = 30
6 : interest_rate = 4.0F
8 : text[1] = 'A'
9 : text[2] = 'V'
10 : text[3] = 'A'
11 : name = "John Doe"
12 : text
13 : age++
14 : age
15 : text
Here we've entered /12 to re-execute snippet #12, which outputs the contents of text
. We then entered /list 13 to list snippet #13, which increments age
. Next, we entered /drop 7 to delete snippet #7 (no more age += 10
snippet). Finally, we entered /list to re-list all snippets. Notice that snippet #7 has been removed, and a snippet #15 has been added thanks to the /12
command.
Making decisions: if, if-else, and switch
Decision statements let applications choose between multiple paths of execution. For example, if a salesperson sells more than 500 items this month, give the salesperson a bonus. Also, if a student's grade on an algebra test is greater than 85 percent, congratulate the student for doing well; otherwise, recommend that the student study harder for the next test.
Java supports the if
, if-else
, and switch
decision statements. Additionally, a new switch
expressions feature has been added to Java 12.
The if statement
The simplest of Java's decision statements is the if
statement, which evaluates a Boolean expression and executes another statement when this expression evaluates to true. The if
statement has the following syntax:
if (Boolean expression)
statement
The if
statement starts with reserved word if
and continues with a parenthesized Boolean expression, which is followed by the statement to execute when the Boolean expression evaluates to true.
The following example demonstrates the if
statement. When the age
variable contains a value of 55 or greater, if
executes System.out.println(...);
to output the message:
if (age >= 55)
System.out.println("You are or were eligible for early retirement.");
Many people prefer to wrap any simple statement that follows the if
statement in braces, effectively converting it to an equivalent compound statement:
if (age >= 55)
{
System.out.println("You are or were eligible for early retirement.");
}
Although the braces clarify what is being executed by the if
statement, I believe that the indentation provides this clarity, and that the braces are unnecessary.
Experimenting with if statements
Let's try out this example usingjshell
. Restart jshell
and then introduce an age
variable (of type int
) that's initialized to 55
:
jshell> int age = 55
Next, enter the first example if
statement (without the curly braces surrounding its body):
jshell> if (age >= 55)
...> System.out.println("You are or were eligible for early retirement.");
You are or were eligible for early retirement.
jshell>
Notice that the jshell>
prompt changes to the ...>
continuation prompt when you enter a multiline snippet. Pressing Enter after the last snippet line causes jshell
to immediately execute the snippet.
Execute /list to list all snippets. I observe that the if
statement snippet has been assigned 2
in my session. Executing /2 causes jshell
to list and then execute this snippet, and the same message is output.
Now, suppose you assign 25
to age
and then re-execute /2 (or the equivalent snippet number in your session). This time, you should not observe the message in the output.
The if-else statement
The if-else
statement evaluates a Boolean expression and executes a statement. The statement executed depends on whether the expression evaluates to true or false. Here's the syntax for the if-else
statement:
if (Boolean expression)
statement1
else
statement2
The if-else
statement is similar to the if
statement, but it includes the reserved word else
, followed by a statement to execute when the Boolean expression is false.
The following example demonstrates an if-else
statement that tells someone who is less than 55 years old how many years are left until early retirement:
if (age >= 55)
System.out.println("You are or were eligible for early retirement.");
else
System.out.println("You have " + (55 - age) + " years to go until early retirement.");
Chaining if-else statements
Java lets you chain multiple if-else
statements together for situations where you need to choose one of multiple statements to execute:
if (Boolean expression1)
statement1
else
if (Boolean expression2)
statement2
else
...
else
statementN
Chaining works by executing a subsequent if-else
statement whenever the current if
statement's Boolean expression evaluates to false. Consider a demonstration:
if (temperature < 0.0)
System.out.println("freezing");
else
if (temperature > 100.0)
System.out.println("boiling");
else
System.out.println("normal");
The first if-else
statement determines if temperature
's value is negative. If so, it executes System.out.println("freezing");
. If not, it executes a second if-else
statement.
The second if-else
statement determines if temperature
's value is greater than 100. If so, it executes System.out.println("boiling");
. Otherwise, it executes System.out.println("normal");
.
The dangling-else problem
When if
and if-else
are used together, and the source code isn't properly indented, it can be difficult to determine which if
associates with the else
. You can see the problem in the code below:
int x = 0;
int y = 2;
if (x > 0)
if (y > 0)
System.out.println("x > 0 and y > 0");
else
System.out.println("x <= 0");
You would probably expect to see x <= 0
as the output from this code, but it will never happen; instead, nothing will output. The problem is that the else
matches up to its nearest if
, which is if (y > 0)
. Reformatting the code makes it clearer what is happening:
int x = 0;
int y = 2;
if (x > 0)
if (y > 0)
System.out.println("x > 0 and y > 0");
else
System.out.println("x <= 0");
Here it's clearer than an if (y > 0) ... else ...
if-else
statement follows the if (x > 0)
statement. To match the intent of the previous example, you need to introduce brace characters around if (y > 0)
and its subsequent statement. Essentially, a block will follow if (x > 0)
:
int x = 0;
int y = 2;
if (x > 0)
{
if (y > 0)
System.out.println("x > 0 and y > 0");
}
else
System.out.println("x <= 0");
Because x > 0
evaluates to false, System.out.println("x <= 0");
executes. The else
reserved word clearly matches up to if (x > 0)
.
The switch statement
When you need to choose between several execution paths, the switch
statement offers a more efficient alternative to chaining. Have a look at the switch
statement:
switch (selector expression)
{
case value1: statement1 [break;]
case value2: statement2 [break;]
...
case valueN: statementN [break;]
[default: statement]
}
The switch
statement begins with reserved word switch
and continues with a selector expression that selects one of the subsequent cases or the default case to execute. The selector expression evaluates to an integer, a character, or a string.
Each case identifies a statement to execute. The case begins with the reserved word case
and a value that labels the case. Following a colon (:
) character is the statement to execute. The statement can be optionally followed by break;
, to transfer execution to the first statement after switch
. If none of the case labels matches the selector expression's value, the optional default case, which begins with reserved word default
, will execute.
Below is a switch
statement used to determine if an integer value is even or odd (by using the remainder operator). It then outputs an appropriate message via the case whose label matches the remainder:
int i = 27;
switch (i % 2)
{
case 0: System.out.println("even");
break;
case 1: System.out.println("odd");
}