HTML Markup | JavaScript | Java | Home & Links

Tutorial 2 - Control Flow

This tutorial on basic Java control flow assumes some introductory programming experience in another language.

Conditional Statements

Conditions are phrases that can be evaluated to a boolean value such as a comparison operator between two constants, variables or expressions used to test a dynamic situation. Examples are x <= 5 and bool_flag != true.

Conditional statements execute a block or set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in blocks (ie. curly brackets). For example:

if (value>5) {x=7;}

Note: If the block (curly brackets) contains only one statement, the brackets can be omitted. But this is not good programming practice. The curly brackets make the code more consistent and easier to read.

Occasionally some actions for the false outcome of a condition need to be executed as well. The else keyword is used to separate branches.

if (name=="Fred") {x=4;}
  else {x=20;};

Note: When the conditional if statement is used only to make an assignment to one variable, the terse C conditional operator can be used but note that many find it unreadable. A simple example is:

x=(name=="Fred") ? 4 : 20;


For statements allow a set of statements to be repeated or looped through a fixed number of times. The round bracket contains initializer(s) ; conditional test ; incrementer(s). If more than one initializer or incrementer is used they are separated with commas. The test condition is checked prior to executing the block. Incrementing is done after executing the block. To output #1 #2 etc.(or #5 #4 etc.) on separate rows write:

for (int i=1;i<=5;i++) {document.writeln("#"+i);};
for (int i=5;i>=1;i--) {document.writeln("#"+i);};

Note: A special case of the for loop is the infinite loop for (;;){...}. This could be used with appropriate 'breakout' logic where a continuous operation was needed.

Caution: For loops can be written in ways that violate structured programming principles by allowing counter variables to be used outside of the scope of the loop block if they are defined outside the loop. Avoid the looseness of the language by always localizing the loop variable.

The enhanced for statement allows iteration over a full set of items or objects. For example:

int[] squares={0,1,4,9,16,25};
for (int square : squares) {System.out.println(square);}
// is equivalent to
for (int i=0;i<squares.length;i++) {System.out.println(squares[i]);}

While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked prior to executing the block. To output #1 #2 etc. on separate rows, write:

int i=0;
while (i<=5) {
   document.writeln("#"+i); i++;

Do While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked after executing the block. To output #1 #2 etc. on separate rows, write:

int i=1;
do {
   document.writeln("#"+i); i++;
   } while (i<=5);

Nested loops are possible. Be very careful about modifying any indices!.

for (int i=0;i<10;i++) {
  for (int j=i;j7<10;j++) {


Switch (aka case) statements are used to select which statement block is executed depending on a variable's value. default is used for the else situation. The selection variable must be one of: int, char or string datatype.

String selection="2"; switch (selection)
   case "1": System.out.println("You picked 1");break;
   case "2": System.out.println("You picked 2");break;
   default:  System.out.println("Oops!, that was an invalid entry.");

Continue, Break and Return

Continue statements are used in looping statements to force another iteration of the loop before reaching the end of the current one. Most often continue is used as part of a conditional statement that only happens in certain cases.

int x=0;
while (x<10)
   x++; System.out.println(x); continue;
   // you will never get to this point!

Break statements are used in looping and 'switch' statements to force an abrupt termination or exit from the loop or switch. In the following example the loop is never completed. Once again the normal use of break is as part of a conditional statement.

int x=0;
while (x<10)
   x++; System.out.println(x); break;
   // you will never get to this point!

Return statements are used to force a quick exit from a method. They are also used to pass values back from methods.

Command Line Arguments

Java applications interface with system command line arguments through the static void main(String args[]) method. [Note: args[] is a Java coding convention!] The args[] array does not include the interpreter java command or the application's class name and the count starts at 0. Arguments are passed as strings.

string g=args[0]; // standard method of access
int w=Integer.parseInt(args[1]); // if integer is wanted
char s=args[2].charAt(0); // use first char only

Notes: The methods parseInt() and charAt() are referenced in the type wrappers and string class topics. Entering values of the wrong datatype can force run-time errors. A later tutorial on exceptions shows how to catch and recover from these types of errors.

Warning: Double quote marks are consumed by the command line parser and are not passed on to the args[] array!

The number of arguments passed in from the command line can be determined by using the .length property. This is important when testing for required arguments, when there is a variable number of arguments or when there is an unpredictable number of arguments (eg. wildcard file globs * and ?.

A command line argument handling routine is a project that could be incorporated into many applications.

Assignment Problems

For a quick test review of the basics (ie. programming in the small), try some of these short problems.

Project: Metric Converter

This project tests knowledge of syntax without getting too involved in the complexities of object manipulation or a user interface. A toy metric converter should be just about right as it allows three basic stages of application development; IPO, branching, and switch selection.

The First Stage [Input - Process - Output]

The goal of the first stage of this project is to input from the command line a temperature given in degrees Fahrenheit (a geezer's unit), calculate the value in Celsius (the modern way) and then display the answer. This tests the ability to get some input, do a math process and finally display the output. It also gives some practice working with the development environment and doing compilations.

The basic input procedure will be to get the Fahrenheit reading from the command line using the method Integer.parseInt(args[0]) which returns an integer from the first argument on the command line.

The math processing part is really easy. Celsius, a scientist, used water as his gauge so freezing was 0 and boiling was 100. Fahrenheit, an engineer used a more commonly available liquid, alcohol for his range :-). As alcohol freezes at lower temperatures, that is why the 32° difference. Because of the difference in range from freezing to boiling of the two liquids the ratio of size of the units turns out to be 100 to 180 or 5 to 9. This is the basic principle for the formula deg_C=((deg_F-32) * 5)/9. Since division may produce a real number with a decimal value, cast the input number into a double and work with double precision floating point numbers (aka real numbers). Caution: Be sure to rewrite the formula with decimal numbers!

Once the answer is calculated, it can be output by using the method System.out.println(deg_C)

Note: This program must be run from the command line with an integer following the program name. No error checking has been done yet! A brute force check could check args.length before parsing to make sure some data was given. It could even check the data to make sure it was an integer.

Second Stage [Branching]

The second stage is to modify the application so that the conversion can be made in either direction. This will require a logical branch based on some additional input. Assume that the input has to look like 40 F or 10 C

    char units=args[1].charAt(0);
    if (units=='F')
    { /* do F --> C conversion */ }
    { /* do C --> F conversion */ }

Also the command line should be checked to make sure that the number of arguments is correct (which we failed to do in stage one). A simple error message can be printed after checking the count such as:

    if (args.length!=2)
      System.out.println ("Usage: Metric_2 ## F|C");

Third Stage [Switches]

The third stage is to use the units argument to select an appropriate conversion routine (temperature, mass, distance, etc.) and switch to routines accordingly. For this program add routines to convert lbs to kilograms and kg to lbs. This stage maxes out the limits of programming in the small. In later tutorials custom objects will be used to encapsulate data and procedures and GUI objects used to allow for interactive input.

switch (units)
  case 'F': { /* conversion routine */ } ; break;
  case 'C': { /* conversion routine */ } ; break;
  case 'L': { /* conversion routine */ } ; break;
  case 'K': { /* conversion routine */ } ; break;
  default : System.out.println("Oops! I do not understand the units...");

Tutorial Source Code

Obtain source for basic problems, circle, metric, etc. here.

JR's HomePage | Comments [jatutor2.htm:2016 02 15]