Java Programming/Statements

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 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:

This line is a simple instruction that tells the system to initialize a variable and set its value as 24. If the above statement was the only one in the program, it would look similar to this:

Java places its statements within a class declaration and, in the class declaration, the statements are usually placed in a method declaration, as above.

Variable declaration statement
The simplest statement is a variable declaration:

It defines a variable that can be used to store values for later use. The first token is the data type of the variable (which type of values this variable can store). The second token is the name of the variable, by which you will be referring to it. Then each declaration statement is ended by a semicolon.

Assignment statements
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 (also called an initialization statement). Did you notice one more thing? It's the semicolon, which is 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 with each statement on a separate line ending with a semicolon. Consider the example below:

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:

However, the only problem with putting multiple statements on one line is, it's very difficult to read it. 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 3.4.

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 includes three parts: a data type, the variable name (also called the identifier) and the value of a variable. We will look more into the nature of identifiers and values in the section Variables later.

Now, before we move on to the next topic, you need to try and understand what the code below does.

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  gives you the number , calling   would give you   hence when you add the two up, the answer should be. That's what the value of the last variable  would be. The part of the third statement where you add the numbers, i.e.,  is called an expression and the expression is what decides what the value is to be. If it's just a plain value, like in the first two statements, then it's called a literal (the value is literally the value, hence the name literal).

Note that after the assignment to  its value will not be changed if we assign different values to   or , like in line 5.

With the information you have just attained, you can actually write a decent Java program that can sum up values.

Assertion
An assertion checks if a condition is true:

Each  statement is ended by a semi-colon. However, assertions are disabled by default, so you must run the program with the -ea argument in order for assertions to be enabled.

Program Control Flow
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
A bunch of statements can be placed in braces to be executed as a single block. Such a block of statements can be named or be provided with a condition for execution. Below is how you'd place a series of statements in a block.

Branching Statements
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
If you look closely 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,  ,   or  , all of which are described below.

When the name of another 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.

The program flow begins in the  method. Just as  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
A  statement exits from a block, so it is often the last statement of a method:

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  statement is ended by a semi-colon.

Conditional Branching Statements
Conditional branching is attained with the help of the  and   statements. A conditional branch occurs only if a certain condition expression evaluates to true.

Conditional Statements
Also referred to as  statements, these allow a program to perform a test and then take action based on the result of that test.

The form of the statement:

(condition) { do statements here if condition is true } {   do statements here if condition is false }

The condition is a boolean expression which can be either or. The actions performed will depend on the value of the condition.

Example:

If statements can also be made more complex using the else if combination:

(condition 1) { do statements here if condition 1 is true }  (condition 2) { do statements here if condition 1 is false and condition 2 is true } {   do statements here if neither condition 1 nor condition 2 is true }

Example:

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
The ... statement is used to conditionally execute one of two blocks of statements, depending on the result of a boolean condition.

Example:

Oracle's Java Code Conventions recommend that the braces should always be used.

An statement has two forms:

(boolean-condition)

and

(boolean-condition)

Use the second form if you have different statements to execute if the is true or if it is false. Use the first if you only wish to execute 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 methods,   and , stores the results, then uses an  statement to test if   is less than y and if it is, the  body will swap the values. The end result is x always contains the larger result and y always contains the smaller result.

... statements also allow for the use of another statement,. This statement is used to provide another statement to the conditional that can only be executed if the others are not true. For example:

The  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, the second conditional, the  , would still not execute. However, when dealing with primitive types in conditional statements, it is more desirable to use  rather than multiple   statements.

Switch statements
The conditional statement is basically a shorthand version of writing many ... statements. The syntax for statements is as follows: {  case : ; break; case : ; break; default: ; break; } This means that if the variable included equals one of the case results, the statements following that case, until the word  will run. The  case executes if none of the others are true. Note: the only types that can be analysed through statements are, , , or  primitive types. This means that variables can not by analyzed through  statements. However, as of the JDK 7 release, you can use a String object in the expression of a switch statement.

In this example, since the integer variable  is equal to 2,   will execute, make   equal to 4. Thus, 4 is returned by the method.

Iteration Statements
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  loop
 * The  loop
 * The  loop
 * The  loop

The while loop
The  loop iterates a block of code while the condition it specifies is.

The syntax for the loop is:

(condition) { statement; }

Here the condition is an expression. An expression as discussed earlier is any statement that returns a value. condition statements evaluate to a boolean value, that is, either  or. As long as the condition is, the loop will iterate the block of code over and over and again. Once the condition evaluates to, the loop exits to the next statement outside the loop.

The do...while loop
The do-while loop is functionally similar to the while loop, except the condition is evaluated AFTER the statement executes {   statement; } (condition);

The for loop
The for loop is a specialized while loop whose syntax is designed for easy iteration through a sequence of numbers. Example: The program prints the numbers 0 to 99 and their squares.

The same statement in a while loop:

The foreach loop
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:

(type item : collection) statement;

For an example, we'll take an array of s denoting days in a week and traverse through the collection, examining one item at a time.

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
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.

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.

The  and   statements can be used with a label like follows:

Throw statement
A  statement exits from a method and so on and so on or it is caught by a  /  block. It does not return a variable but an exception:

Beware not to write statements after a  statement which would not be executed too! Each  statement is ended by a semi-colon.

try/catch
A /  must at least contain the   block and the   block:

Question 3.1: How many statements are there in this class?

5 One statement at line 3, two statements at line 6, one statement at line 7 and one statement at line 11.