The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search

Trail: Learning the Java Language
Lesson: The Nuts and Bolts of the Java Language

## Answers to Questions and Exercises: Control Flow

### Answers to Questions

> 1. Two questions about `WhileDemo` and `DoWhileDemo`.

>    Question: What would the output be from `WhileDemo` and `DoWhileDemo` if you change the value of the string `copyFromMe` to `"golly gee. this is fun"`?
>    Answer: `WhileDemo` displays nothing. `DoWhileDemo` displays `golly`.

>    Question: Would the output be different? Defend your answer.
>    Answer: The output is different. The expression `c != 'g'` is evaluated at the top of the loop in `WhileDemo`. Because the first character of the string is a 'g' the statements within the loop are never executed. In `DoWhileDemo` the expression is evaluated at the bottom of the loop after the first 'g' is appended to the string buffer. Thus the expression tests the second character in the string, which is an 'o'. The loop continues until the second 'g' in the string.

> 2. Question: Identify the control flow statements in the `Sort` program.
>    Answer:

>    >     public class Sort {
>    >         public static void main(String[] args) {
>    >             int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
>    >                                   2000, 8, 622, 127 };

>    >             for (int i = arrayOfInts.length; --i >= 0; ) {
>    >                 for (int j = 0; j < i; j++) {
>    >                     if (arrayOfInts[j] > arrayOfInts[j+1]) {
>    >                         int temp = arrayOfInts[j];
>    >                         arrayOfInts[j] = arrayOfInts[j+1];
>    >                         arrayOfInts[j+1] = temp;
>    >                     }
>    >                 }
>    >             }

>    >             for (int i = 0; i < arrayOfInts.length; i++) {
>    >                 System.out.print(arrayOfInts[i] + " ");
>    >             }
>    >             System.out.println();
>    >         }
>    >     }

| Start of Tutorial > Start of Trail > Start of Lesson | Search