Statements

Navigate Language Fundamentals topic: v  d  e )


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:

Example Code section 3.1: A simple assignment statement.
int age = 24;

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:

Computer code Code listing 3.1: A statement in a simple class.
public class MyProgram
 {
    public static void main(String[] args) 
    {
        int age = 24;
    }
}

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

edit

The simplest statement is a variable declaration:

  Code section 3.2: A simple declaration statement.
int age;

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

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

  Code section 3.3: Multiple assignment statements.
int a = 10;
int b = 20;
int c = 30;

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.
int a = 10; int b = 20; int c = 30;

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.

  Code section 3.5: Multiple assignment statements with expressions.
int firstNumber = 10;
int secondNumber = 20;
int result = firstNumber + secondNumber;
System.out.println(result);
secondNumber = 30; // This won't change the value of secondNumber. See the note.
System.out.println(result); // Hence, the result will remain same.

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, 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 result its value will not be changed if we assign different values to firstNumber or secondNumber, 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

edit

An assertion checks if a condition is true:

  Code section 3.6: A return statement.
    public int getAge() 
    {
        assert age >= 0;
        return age;
    }

Each assert 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 (java -ea [name of compiled program]).

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

  Code section 3.7: A statement block.
{
    int a = 10;
    int b = 20;
    int result = a + b;
}

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 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 break, continue, return or throw, 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.

  Code listing 3.8: UnconditionalBranching.java
public class UnconditionalBranching {
    public static void main(String[] args) {
        System.out.println("Inside main method! Invoking aMethod!");
        aMethod();
        System.out.println("Back in main method!");
    }

    public static void aMethod() {
        System.out.println("Inside aMethod!");
    }
}
  Output provided with the screen of information running the above code.
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 exits from a block, so it is often the last statement of a method:

  Code section 3.9: A return statement.
    public int getAge() {
        int age = 24;
        return age;
    }

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 (i > 0) {
   System.out.println("value stored in i is greater than zero");
} else {
   System.out.println("value stored is not greater than zero");
}

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 (i > 0) {
   System.out.println("value stored in i is greater than zero");
} else if (i < 0) {
   System.out.println("value stored in i is less than zero");
} else {
   System.out.println("value stored is equal to 0");
}

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.
if (list == null) {
  // This block of statements executes if the condition is true.
} else {
  // This block of statements executes if the condition is false.
}

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)
   statement1
else
   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.
int x = f();
int y = y();
if (x < y) {
  int z = x;
  x = y;
  y = z;
}

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.
if (x == 2)
  x = 4;
else if (x == 3)
  x = 6;
else
  x = -1;

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 Object variables can not by analyzed through switch statements. However, as of the JDK 7 release, you can use a String object in the expression of a switch statement.

  Code section 3.15: A switch.
int n = 2, x;
switch (n) {
  case 1: x = 2;
    break;
  case 2: x = 4;
    break;
  case 3: x = 6;
    break;
  case 4: x = 8;
    break;
}
return x;

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.
for (int i = 0; i < 100; i++) {
  System.out.println(i + "\t" + i * i);
}
  Output for code listing 3.16 if you compile and run the statement above.
 0      0
 1      1
 2      4
 3      9
 ...
 99     9801

The program prints the numbers 0 to 99 and their squares.

The same statement in a while loop:

  Code section 3.17: An alternative version.
int i = 0;
while (i < 100) {
   System.out.println(i + "\t" + i * i);
   i++;
}

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 Strings denoting days in a week and traverse through the collection, examining one item at a time.

  Code section 3.18: A foreach loop.
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

for (String day : days) {
  System.out.println(day);
}
  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 continue 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 break ought to be used.

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

  Code section 3.19: Using a label.
String s = "A test string for the switch!\nLine two of test string...";
outer: for (int i = 0; i < s.length(); i++) {
  switch (s.charAt(i)) {
    case '\n': break outer;
    case ' ': break;
    default: System.out.print(s.charAt(i));
  }
}
  Output for code listing 3.19
 Ateststringfortheswitch!

Throw statement

edit

A throw statement exits 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.
    public int getAge() {
        throw new NullPointerException();
    }

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.
try {
  // Some code
} catch (Exception e) {
  // Optional exception handling
} finally {
  // This code is executed no matter what
}
Test your knowledge

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

  Code listing 3.2: AProgram.java
public class AProgram {

    private int age = 24;

    public static void main(String[] args) {
        int daysInAYear = 365;int ageInDay = 100000;
        int localAge = ageInDay / daysInAYear;
    }

    public int getAge() {
        return age;
    }
}
Answer

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