Statements

Coding conventions Java Programming
Statements
Conditional blocks
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 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:

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

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:

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

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 statementEdit

The simplest statement is the variable declaration:

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

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 statementsEdit

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:

Example Code section 3.3: Multiple assignment statements.
  1. int a = 10;
    
  2. int b = 20;
    
  3. 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:

Example Code section 3.4: Multiple assignment statements on the same line.
  1. int a = 10; int b = 20; int c = 30;
    

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.

Example Code section 3.5: Multiple assignment statements with expressions.
  1. int firstNumber = 10;
    
  2. int secondNumber = 20;
    
  3. int result = firstNumber + secondNumber;
    

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.

AssertionEdit

An assertion checks if a condition is true:

Example Code section 3.6: A return statement.
  1.     public int getAge() {
    
  2.         assert age == 24;
    
  3.     }
    

Each assert statement is ended by a semi-colon (;).

Program Control FlowEdit

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 BlocksEdit

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.

Example Code section 3.7: A statement block.
  1. {
    
  2.     int a = 10;
    
  3.     int b = 20;
    
  4.     int result = a + b;
    
  5. }
    

Branching StatementsEdit

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 StatementsEdit

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.

Computer code Code listing 3.8: UnconditionalBranching.java
  1. public class UnconditionalBranching {
    
  2.     public static void main(String[] args) {
    
  3.         System.out.println("Inside main method! Invoking aMethod!");
    
  4.         aMethod();
    
  5.         System.out.println("Back in main method!");
    
  6.     }
    
  7.  
    
  8.     public static void aMethod() {
    
  9.         System.out.println("Inside aMethod!");
    
  10.     }
    
  11. }
    

Running the above code would provide us with this screen of information.

Computer code 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 statementEdit

A return statement exit from a block so it is often the last statement of a method:

Example Code section 3.9: A return statement.
  1.     public int getAge() {
    
  2.         int age = 24;
    
  3.         return age;
    
  4.     }
    

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 StatementsEdit

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 StatementsEdit

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:

Example Code section 3.10: An if statement.
  1. if (i > 0) {
    
  2.    System.out.println("value stored in i is greater than zero");
    
  3. } else {
    
  4.    System.out.println("value stored is not greater than zero");
    
  5. }
    

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:

Example Code section 3.11: An if/else if/else statement.
  1. if (i > 0) {
    
  2.    System.out.println("value stored in i is greater than zero");
    
  3. } else if (i < 0) {
    
  4.    System.out.println("value stored in i is less than zero");
    
  5. } else {
    
  6.    System.out.println("value stored is equal to 0");
    
  7. }
    

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 statementsEdit

The if ... else statement is used to conditionally execute one of two blocks of statements, depending on the result of a boolean condition.

Example:

Example Code section 3.12: An if/else statement.
  1. if (list == null) {
    
  2.   // This block of statements executes if the condition is true.
    
  3. } else {
    
  4.   // This block of statements executes if the condition is false.
    
  5. }
    

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.

Example Code section 3.13: Value swap.
  1. int x = f();
    
  2. int y = y();
    
  3. if (x < y) {
    
  4.   int z = x;
    
  5.   x = y;
    
  6.   y = z;
    
  7. }
    

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:

Example Code section 3.14: Multiple branching.
  1. if (x == 2)
    
  2.   x = 4;
    
  3. else if (x == 3)
    
  4.   x = 6;
    
  5. else
    
  6.   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 statementsEdit

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.

Example Code section 3.15: A switch.
  1. int n = 2, x;
    
  2. switch (n) {
    
  3.   case 1: x = 2;
    
  4.     break;
    
  5.   case 2: x = 4;
    
  6.     break;
    
  7.   case 3: x = 6;
    
  8.     break;
    
  9.   case 4: x = 8;
    
  10.     break;
    
  11. }
    
  12. 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 StatementsEdit

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 loopEdit

Main page: Java Programming/Keywords/while

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 loopEdit

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 loopEdit

Main page: Java Programming/Keywords/for

The for loop is a specialized while loop whose syntax is designed for easy iteration through a sequence of numbers Example:

Example Code section 3.16: A for loop.
  1. for (int i = 0; i < 100; i++) {
    
  2.   System.out.println(i + "\t" + i * i);
    
  3. }
    

If you compile and run the statement above, the program will print the numbers 0 to 99 and their squares

Computer code Output for code listing 3.16
 0      0
 1      1
 2      4
 3      9
 ...
 99     9801

The same statement in a while loop:

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

The foreach loopEdit

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.

Example Code section 3.18: A foreach loop.
  1. String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    
  2.  
    
  3. for (String day : days) {
    
  4.   System.out.println(day);
    
  5. }
    

The output of this program would be:

Computer code 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 statementsEdit

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:

Example Code section 3.19: Using a label.
  1. String s = "A test string for the switch!\nLine two of test string...";
    
  2. outer: for (int i = 0; i < s.length(); i++) {
    
  3.   switch (s.charAt(i)) {
    
  4.     case '\n': break outer;
    
  5.     case ' ': break;
    
  6.     default: System.out.print(s.charAt(i));
    
  7.   }
    
  8. }
    

Compiling and running this statement will produce

Computer code Output for code listing 3.19
 Ateststringfortheswitch!

Throw statementEdit

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:

Example Code section 3.20: A return statement.
  1.     public int getAge() {
    
  2.         throw new NullPointerException();
    
  3.     }
    

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/catchEdit

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

Example Code section 3.21: try/catch block.
  1. try {
    
  2.   // Some code
    
  3. } catch (Exception e) {
    
  4.   // Optional exception handling
    
  5. } finally {
    
  6.   // This code is executed no matter what
    
  7. }
    
Test your knowledge

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

Computer code Code listing 3.2: AProgram.java
  1. public class AProgram {
    
  2.  
    
  3.     private int age = 24;
    
  4.  
    
  5.     public static void main(String[] args) {
    
  6.         int daysInAYear = 365;int ageInDay = 100000;
    
  7.         int localAge = ageInDay / daysInAYear;
    
  8.     }
    
  9.  
    
  10.     public int getAge() {
    
  11.         return age;
    
  12.     }
    
  13. }
    
Answer

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


Language Fundamentals Java Programming
Statements
Conditional blocks
Last modified on 6 August 2013, at 09:07