Statements
Navigate Language Fundamentals topic: ) |
Now, that we have the Java platform on our systems and have run the first program successfully, we are geared towards understanding how programs are actually made. As we have already discussed. A program is a set of instructions, which are simple tasks provided to a computer. These instructions are called statements in Java. Statements can be anything from a single line of code to a complex mathematical equation. Consider the following line:
![]() |
Code section 3.1: A simple assignment statement.
|
This line is a simple instruction that tells the system to initialize a variable and set its value as 24. Within that simple definition, we talked about initialization of a variable and setting its value. If the above statement was the only one in the program, it would look similar to this:
![]() |
Code listing 3.1: A statement in a simple class.
|
In the same style as C++, Java places its statements within a class declaration and, in the class declaration, the statements are usually placed in the method declaration, as above.
Variable declaration statement [edit]
The simplest statement is the variable declaration:
![]() |
Code section 3.2: A simple declaration statement.
|
It defines a variable that can be used by the further statement. The first token is the data type of the variable. The second token is the name of the variable. Then each declaration statement is ended by a semi-colon (;
).
Assignment statements [edit]
Up until now, we've assumed the creation of variables as a single statement. In essence, we assign a value to those variables, and that's just what it is called. When you assign a value to a variable in a statement, that statement is called an assignment statement. Did you notice one more thing? The semicolon (;). It's at the end of each statement. A clear indicator that a line of code is a statement is its termination with an ending semicolon. If one was to write multiple statements, it is usually done on each separate line ending with a semicolon. Consider the example below:
![]() |
Code section 3.3: Multiple assignment statements.
|
You do not necessarily have to use a new line to write each statement. Just like English, you can begin writing the next statement where you ended the first one as depicted below:
![]() |
Code section 3.4: Multiple assignment statements on the same line.
|
However, the only problem with writing such code is, it's very difficult to read it back. It doesn't look that intimidating at first, but once you've got a significant amount of code, it's usually better to organize it in a way that makes sense. It would look more complex and incomprehensible written as it is in Listing 1.6.
Now that we have looked into the anatomy of a simple assignment statement, we can look back at what we've achieved. We know that...
- A statement is a unit of code in programming.
- If we are assigning a variable a value, the statement is called an assignment statement.
- An assignment statement include three parts: a data type, variable name (also called an identifier) and the value of a variable. We will look more into the nature of identifiers and values in the section titled Variables later.
Now, before we move on to the next topic, you need to try and understand what the code below does.
![]() |
Code section 3.5: Multiple assignment statements with expressions.
|
The first two statements are pretty much similar to those in Section 3.3 but with different variable names. The third however is a bit interesting. We've already talked of variables as being similar to gift boxes. Think of your computer's memory as a shelf where you put all those boxes. Whenever you need a box (or variable), you call its identifier (that's the name of the variable). So calling the variable identifier firstNumber
gives you the number 10
, calling secondNumber
would give you 20
hence when you add the two up, the answer should be 30
. That's what the value of the last variable result
would be. The part of the third statement where you add the numbers, i.e., firstNumber + secondNumber
is called an expression and the expression is what decides what the value is to be. If it's just a plain value, nothing fancy, then it's called a literal.
With the information you have just attained, you can actually write a decent Java program that can sum up values. To learn more, continue reading.
Assertion [edit]
An assertion checks if a condition is true:
![]() |
Code section 3.6: A return statement.
|
Each assert
statement is ended by a semi-colon (;
).
Program Control Flow [edit]
Statements are evaluated in the order as they occur. The execution of flow begins at the top most statement and proceed downwards till the last statement is encountered. A statement can be substituted by a statement block. There are special statements that can redirect the execution flow based on a condition, those statements are called branching statements, described in detail in a later section.
Statement Blocks [edit]
A bunch of statements can be placed in braces to be executed as a single block. Such a block of statement can be named or be provided a condition for execution. Below is how you'd place a series of statements in a block.
![]() |
Code section 3.7: A statement block.
|
Branching Statements [edit]
Program flow can be affected using function/method calls, loops and iterations. Of various types of branching constructs, we can easily pick out two generic branching methods.
- Unconditional Branching
- Conditional Branching
Unconditional Branching Statements [edit]
If you'd closely look at a method, you'll see that a method is a named statement block that is executed by calling that particular name. An unconditional branch is created either by invoking the method or by calling break
, continue
, return
or throw
, all of which are described in below.
When a name of a method is encountered in a flow, it stops execution in the current method and branches to the newly called method. After returning a value from the called method, execution picks up at the original method on the line below the method call.
![]() |
Code listing 3.8: UnconditionalBranching.java
|
Running the above code would provide us with this screen of information.
![]() |
Output for code listing 3.8
Inside main method! Invoking aMethod! Inside aMethod! Back in main method! |
The program flow begins in the main
method. Just as aMethod
is invoked, the flow travels to the called method. At this very point, the flow branches to the other method. Once the method is completed, the flow is returned to the point it left off and resumes at the next statement after the call to the method.
Return statement [edit]
A return
statement exit from a block so it is often the last statement of a method:
![]() |
Code section 3.9: A return statement.
|
A return statement can return the content of a variable or nothing. Beware not to write statements after a return statement which would not be executed! Each return
statement is ended by a semi-colon (;
).
Conditional Branching Statements [edit]
Conditional branching is attained with the help of the if...else
and switch
statements. A conditional branch occurs only if a certain condition expression evaluates to true.
Conditional Statements [edit]
Also referred to as if
statements, these allow a program to perform a test and then take action based on the result of that test.
The form of the if
statement:
if
(condition) { do statements here if condition is true }else
{ do statements here if condition is false }
The condition is a boolean expression which can be either true
or false
. The actions performed will depend on the value of the condition.
Example:
![]() |
Code section 3.10: An if statement.
|
If statements can also be made more complex using the else if combination:
if
(condition 1) { do statements here if condition 1 is true }else
if
(condition 2) { do statements here if condition 1 is false and condition 2 is true }else
{ do statements here if neither condition 1 nor condition 2 is true }
Example:
![]() |
Code section 3.11: An if/else if/else statement.
|
If there is only one statement to be executed after the condition, as in the above example, it is possible to omit the curly braces, however Oracle's Java Code Conventions explicitly state that the braces should always be used.
There is no looping involved in an if statement so once the condition has been evaluated the program will continue with the next instruction after the statement.
If...else statements [edit]
The if
... else
statement is used to conditionally execute one of two blocks of statements, depending on the result of a boolean condition.
Example:
![]() |
Code section 3.12: An if/else statement.
|
Oracle's Java Code Conventions recommend that the braces should always be used.
An if
statement has two forms:
if
(boolean-condition)
statement1
and
if
(boolean-condition) statement1else
statement2
Use the second form if you have different statements to execute if the boolean-condition is true or if it is false. Use the first if you only wish to execute statement1 if the condition is true and you do not wish to execute alternate statements if the condition is false.
The code section 3.13 calls two int
methods, f()
and y()
, stores the results, then uses an if
statement to test if x
is less than y and if it is, the statement1 body will swap the values. The end result is x always contains the larger result and y always contains the smaller result.
![]() |
Code section 3.13: Value swap.
|
if
...else
statements also allow for the use of another statement, else
if
. This statement is used to provide another if
statement to the conditional that can only be executed if the others are not true. For example:
![]() |
Code section 3.14: Multiple branching.
|
The else
if
statement is useful in this case because if one of the conditionals is true, the other must be false. Keep in mind that if one is true, the other will not execute. For example, if the statement at line 2 contained in the first conditional were changed to x = 3;
, the second conditional, the else
if
, would still not execute. However, when dealing with primitive types in conditional statements, it is more desirable to use switch statements
rather than multiple else
if
statements.
Switch statements [edit]
The switch
conditional statement is basically a shorthand version of writing many if
...else
statements. The syntax for switch
statements is as follows:
switch
(<variable>) {
case <result>: <statements>; break;
case <result>: <statements>; break;
default: <statements>; break;
}
This means that if the variable included equals one of the case results, the statements following that case, until the word break
will run. The default
case executes if none of the others are true. Note: the only types that can be analysed through switch
statements are char
, byte
, short
, or int
primitive types. This means that String
variables can not by analyzed through switch
statements.
![]() |
Code section 3.15: A switch.
|
In this example, since the integer variable n
is equal to 2, case 2
will execute, make x
equal to 4. Thus, 4 is returned by the method.
Iteration Statements [edit]
Iteration Statements are statements that are used to iterate a block of statements. Such statements are often referred to as loops. Java offers four kinds of iterative statements.
- The
while
loop - The
do...while
loop - The
for
loop - The
foreach
loop
The while loop [edit]
The while
loop iterates a block of code while the condition it specifies is true
.
The syntax for the loop is:
while
(condition) {
statement;
}
Here the condition is an expression. An expression as discussed earlier is any statement that returns a value. While
condition statements evaluate to a boolean value, that is, either true
or false
. As long as the condition is true
, the loop will iterate the block of code over and over and again. Once the condition evaluates to false
, the loop exits to the next statement outside the loop.
The do...while loop [edit]
The do-while loop is functionally similar to the while loop, except the condition is evaluated AFTER the statement executes
do
{ statement; }while
(condition);
The for loop [edit]
The for loop is a specialized while loop whose syntax is designed for easy iteration through a sequence of numbers Example:
![]() |
Code section 3.16: A for loop.
|
If you compile and run the statement above, the program will print the numbers 0 to 99 and their squares
![]() |
Output for code listing 3.16
0 0 1 1 2 4 3 9 ... 99 9801 |
The same statement in a while loop:
![]() |
Code section 3.17: An alternative version.
|
The foreach loop [edit]
The foreach statement allows you to iterate through all the items in a collection, examining each item in turn while still preserving its type. The syntax for the foreach statement is:
for
(type item : collection) statement;
For an example, we'll take an array of String
s denoting days in a week and traverse through the collection, examining one item at a time.
![]() |
Code section 3.18: A foreach loop.
|
The output of this program would be:
![]() |
Output for code listing 3.18
Monday Tuesday Wednesday Thursday Friday Saturday Sunday |
Notice that the loop automatically exits after the last item in the collection has been examined in the statement block.
Although the enhanced for loop can make code much clearer, it can't be used in some common situations.
- Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
- Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
- Only single element. Use only for single element access, eg, not to compare successive elements.
- Only forward. It's possible to iterate only forward by single steps.
- At least Java 5. Don't use it if you need compatibility with versions before Java 5.
The continue and break statements [edit]
At times, you would like to re-iterate a loop without executing the remaining statement within the loop. The
statement causes the loop to re-iterate and start over from the top most statement inside the loop.continue
Where there is an ability to re-iterate the loop, there is an ability to exit the loop when required. At any given moment, if you'd like to exit a loop and end all further work within the loop, the
ought to be used.break
The
and continue
statements can be used with a label like follows:break
![]() |
Code section 3.19: Using a label.
|
Compiling and running this statement will produce
![]() |
Output for code listing 3.19
Ateststringfortheswitch! |
Throw statement [edit]
A throw
statement exit from a method and so on and so on or it is caught by a try
/catch
block. It does not return a variable but an exception:
![]() |
Code section 3.20: A return statement.
|
Beware not to write statements after a throw
statement which would not be executed too! Each throw
statement is ended by a semi-colon (;
).
try/catch [edit]
A try
/catch
must at least contain the try
block and the catch
block:
![]() |
Code section 3.21: try/catch block.
|
Question 3.1: How many statements are there in this class?
![]() |
Code listing 3.2: AProgram.java
|
5
One statement at line 3, two statements at line 6, one statement at line 7 and one statement at line 11.