Conditional Statements

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 curly brackets. For example:

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

Note: If the block (ie. curly brackets) contains only one statement, you may leave the brackets off. But this is not good programming practice. The curly brackets make the code more consistent and easier to read.

Occasionally you may want to perform some actions for the false outcome of a condition 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, you can use the terse C conditional operator. A simple example is:

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

Loops

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. The incrementing is completed after executing the block. For example to output #1 #2 #3 etc. on separate rows you could write:

for (int i=1; i<=15; 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) {...;}
// is equivalent to
for (int 1;i<squares.length;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. For example to output #1 #2 #3 etc. on separate rows you could write:

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

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. For example to output #1 #2 #3 etc. on separate rows you could write:

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

The Switch Statement

Switch (or case) statements are used to select which statements are to be executed depending on a variable's value matching a label. default is used for the else situation. Note that the selection variable can only be int or char datatype.

switch (selection)
{
case '1': System.out.println("You typed a 1"); break;
case '2': System.out.println("You typed a 2"); break;
case '3': System.out.println("You typed a 3"); break;
case '4': System.out.println("You typed a 4"); 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. The following is a trivial example. Most often the 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

Command line arguments are accessible through the args[] array (assuming that args is the name used in the class header [NOTE: args[] is a Java coding convention!]). The array does not include the interpreter java command or the class name and the count starts at 0. Each argument is passed as a string but may be converted as in the following:

int w = Integer.parseInt(args[0]);
// or sometimes you want the argument to be a character type
char s = args[1].charAt(0); // uses first letter of argument only

Note: The methods parseInt() and charAt() are referenced in the type wrappers and string class topics.

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 args.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 the file glob expansions (* and ?) in batch operation.

Command line options are arguments with a prefix of - (dash) and is UNIX-centric. They normally precede pathnames in the command line. Options are normally a single character but sometimes are a number or followed by a number. Examples of command line options are:

pr -d *.htm ; print double spacing lines
head -10 *.htm ; show first 10 lines
head -c 10 *.htm ; show first 10 characters

Command line switches are arguments with a prefix of / (slash) and is msDOS-centric. They normally toggle boolean flags but can be found in many variations such as a following argument qualifier or a parsing situation. Depending on programmer, they may have to precede or follow file arguments.Examples are:

find /p fred *.htm ;page pause requested
progname /help ;help or man page requested
format /head=4. *.htm ;include 4 lines of header space
print -lines 45 *.htm ;print first 45 lines of file(s)

Note: I personally prefer switches to options but YMMV! Try to develop a standard argument option|switch handling routine that is as user tolerant as possible regarding switches and filenames. The routine should identify switches by the prefix / and act appropriately. Routines that are accessing filenames from the args[] array should skip switches (as identified with the / prefix).