Flylib.com

Books Software

 
 
 

Transfer of Control Statements


Transfer of Control Statements

Transfer of control statements moves the point of execution in your program to another location. They are used to exit from loops and other control structures, to return to the top of a loop, or to return from a method.

break Statements

We encountered the break statement in our discussion of switch statements. A break statement is used to exit the current loop or other flow control structure. The program execution is sent to the next statement following the control structure. By default, a break statement inside a nested loop will exit only the current loop, not the entire loop structure. You can add a label after a break statement to break out of a specified labeled block of code.

Example: Breaking Out of an Outer Loop

In this example, two for loops are used to search a 2-D array of data for a negative value. If a negative value is found, its location is noted and the loop exits. We want to exit both the inner and outer loops if a negative value is found. To do this, we label the outer for loop "outer" and use a labeled break statement. If a simple break statement had been used (without the label) only the inner loop would have been exited. The outer loop would continue normally.

public class BreakDemo
{
  public static void main(String args[]) {
    double data[][] = { {4.1, 3.2, 1.1},
                        {-1.3, 2.4, 6.7},
                        {7.7, 0.3, 9.8} };

    outer: for(int i=0; i<3; ++i) {
      for(int j=0; j<3; ++j) {
        System.out.println("i= " + i + " j= " + j);
        if (data[i][j] < 0.0) {
           System.out.println("negative value at" +
                 " [" + i + "][" + j + "]");
           break outer;
        }
      }
    }
  }
}

Output ”

i=0 j=0
i=0 j=1
i=0 j=2
i=1 j=0
negative value at [1][0]

continue Statements

A continue statement causes program execution to return to the top of the current loop, bypassing any code that may be defined below the continue statement. Similar to the break statement, a continue statement can provide a label to return to the top of a labeled loop. The continue statement is an example of a redundancy within Java. Anything you can do with a continue statement you can also do with an if-else statement. Because of this, you will rarely see or use continue statements.

return Statements

The return statement is used to return from a method. It transfers program control to the executable statement following the method call. The return keyword can be used by itself or it can precede a value that will be returned. More details on return statements are provided in Chapter 9.


Basic Printing and Keyboard I/O

Java has a powerful and sophisticated I/O capability, but sometimes you only want to read keyboard input and/or write things to the console. To facilitate this, Java provides three built-in data streams to handle standard input, output, and error. Standard input defaults to keyboard input. Standard output defaults to printing to the console. Standard error is an unbuffered output stream that writes to the console. In this section we'll focus on the standard input and output streams.

The standard input and output data streams are implemented as public static fields defined in the System class. A discussion on what a static field is can be found in Chapter 8. The names of the fields are System.in and System.out . Let's first discuss the standard output stream.

System.out is an instance of the PrintStream class, one of the Java I/O classes. System.out has two basic printing methods print() and println() . We've already seen the println() method in action in many of the examples in this chapter. The print() and println() methods write a String (a collection of characters ) to the invoking output stream. For instance, the syntax

System.out.println("Hello there everybody");

will display the text "Hello there everybody" on your console. If the value passed to the print() or println() methods is a primitive data type or non- String object the value is converted into a String representation. The difference between the print() and println() methods is that println() adds a newline character to the end of the String whereas print() does not.

Table 6.9. Commonly Used Escape Sequences

E SCAPE SEQUENCE

M EANING

\'

Single quote

\"

Double quote

\\

Backslash

\n

Newline

\t

Tab

Both methods take a String as their argument. You can pass the methods a simple String or a concatenated String made up from two or more pieces. An easy way to concatenate Strings is by using the + operator.

String name = "Jackson";
int age = 7;
System.out.println("Student name: "+name+" Age = "+age);

As we see in the example code snippet, a primitive datatype can also be concatenated to a String . The value of the integer variable is converted to a String representation before it is concatenated to the String .

Because double quotes surround a String literal definition, you might ask yourself how to represent a String that contains a double quote character. Java defines a number of escape sequences that represent special characters. Some of the commonly used escape sequences are shown in Table 6.9.

Now, let's discuss the standard input stream. The standard input stream defaults to keyboard input. The standard input stream is represented by an instance of the InputStream class named System.in . The InputStream class is designed to read byte data (as compared to character data). System.in can read keyboard input by invoking the read() method. This method reads one or more bytes from an input stream.

Reading console data as bytes, then converting the bytes into characters can be tedious . It is more convenient to wrap a character input stream around the standard input stream. The wrapped stream can then read the keyboard input either as individual characters or as a String . An example is shown in the next section. More information on the Java I/O classes can be found in Chapter 25.

Example: Reading Console Input

As we discussed previously, the standard input stream is a byte stream. It reads data as bytes. When reading console input, it is more convenient to read the data as characters. An InputStreamReader is a character input stream. If we wrap an InputStreamReader around the standard input stream, we can read console input as characters.

We also wrap a BufferedReader around the InputStreamReader because a BufferedReader can read an entire line of data at once. An InputStreamReader will read the data character by character. The BufferedReader object calls the readLine() method that waits until the Enter or Return key is clicked. It then returns the characters that were typed in previously as a String.

I/O operations can throw exceptions. Because of this we place the read operation inside a try block. Java exception handling is discussed in detail in Chapter 12. Note also the use of the standard output stream in this example calling both the print() and println() methods.

import java.io.*;

public class StdIODemo
{
  public static void main(String args[]) {
    String name;

    System.out.print("Enter name:  ");

    try {
      BufferedReader reader =
         new BufferedReader(
             new InputStreamReader(System.in));

      name = reader.readLine();
      System.out.println("name was "+name);
     } catch (IOException ioe) {}
  }
}

Output (will vary) ”

name was Lisa