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

## Questions and Exercises: Control Flow

[PENDING: This could use more questions and some exercises.]

### Questions

> 1. Recall the `WhileDemo` and `DoWhileDemo` programs.

>    >     public class WhileDemo {
>    >         public static void main(String[] args) {

>    >             String copyFromMe = "Copy this string until you encounter the letter 'g'.";
>    >             StringBuffer copyToMe = new StringBuffer();

>    >             int i = 0;
>    >             char c = copyFromMe.charAt(i);

>    >             while (c != 'g') {
>    >                 copyToMe.append(c);
>    >                 c = copyFromMe.charAt(++i);
>    >             }
>    >             System.out.println(copyToMe);
>    >         }
>    >     }

>    >     public class DoWhileDemo {
>    >         public static void main(String[] args) {

>    >             String copyFromMe = "Copy this string until you encounter the letter 'g'.";
>    >             StringBuffer copyToMe = new StringBuffer();

>    >             int i = 0;
>    >             char c = copyFromMe.charAt(i);

>    >             do {
>    >                 copyToMe.append(c);
>    >                 c = copyFromMe.charAt(++i);
>    >             } while (c != 'g');
>    >             System.out.println(copyToMe);
>    >         }
>    >     }

>    - What would the output be from each program if you change the value of the string `copyFromMe` to `"golly gee. this is fun."`?
>    - Would the output from the two programs be the same? Defend your answer.

> 2. Here's the `Sort` program again:

>    >     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();
>    >         }
>    >     }

>    - Identify all of the control flow statements in the program.
> Check your answers.

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