The Nuts and Bolts of the Java Language |
The character-counting program uses awhile
statement to loop over all the characters of the input source and count them.Generally speaking, aclass Count { public static void main(String[] args) throws java.io.IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has " + count + " chars."); } }while
statement performs some action while a certain condition remains true. The general syntax of thewhile
statement is:That is, while expression is true, do statement. In the character-counting application, while thewhile (expression) statementSystem.in.read
method returns a value that is not -1, the program incrementscount
.statement can be one statement, as shown in the character-counting example, or it can be a statement block. A statement block is a series of legal Java statements contained within curly brackets ('{' and '}'). For example, suppose that in addition to incrementing
count
within thewhile
loop you also wanted to print the count each time a character was read. You could write this instead:By convention, the opening curly bracket '{' is at the end of the same line as the. . . while (System.in.read() != -1) { count++; System.out.println("Read a character. Count = " + count); } . . .while
statement and the closing curly bracket begins a new line indented to line up with thewhile
as shown.Statements such as the
while
statement are control flow statements which determine the order in which other statements are executed. Besideswhile
the Java language supports several other control flow statements, including:
Statement Keyword decision making if-else
,switch-case
loop for
,while
,do-while
exception try-catch-finally
,throw
miscellaneous break
,continue
,label:
,return
Note: Although
goto
is a reserved word, currently the Java language does not support thegoto
statement. Use Branching Statements instead.The if-else Statement
Java'sif
-else
statement provides your programs with the ability to selectively execute other statements based on some criteria. For example, suppose that your program printed debugging information based on the value of some boolean variable namedDEBUG
. IfDEBUG
were set totrue
, then your program would print debugging information such as the value of some variable likex
. Otherwise, your program would proceed normally. A segment of code to implement this might look like this:This is the simplest version of the. . . if (DEBUG) System.out.println("DEBUG: x = " + x); . . .if
statement: the statement governed by theif
is executed if some condition is true. Generally, the simple form ofif
can be written like this:So, what if you wanted to perform a different set of statements if the expression is false? Well, you can use theif (expression) statementelse
statement for that. Consider another example. Suppose that your program needs to perform different actions depending on whether the user clicks on the OK button or the Cancel button in an alert window. Your program could do this using anif
statement:This particular use of the. . . // response is either OK or CANCEL depending // on the button that the user pressed . . . if (response == OK) { . . . // code to perform OK action . . . } else { . . . // code to perform Cancel action . . . }else
statement is the catch-all form. Theelse
block is executed if theif
part is false. There is another form of theelse
statement,else if
which executes a statement based on another expression. For example, suppose that you wrote a program that assigned grades based on the value of a test score, an A for a score of 90% or above, a B for a score of 80% or above and so on. You could use anif
statement with a series of companionelse if
statements, and anelse
to write this code:Anint testscore; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; }if
statement can have any number of companionelse if
statements, but only oneelse
. You may have noticed that some values oftestscore
could satisfy more than one of the expressions in the compoundif
statement. For instance, a score of 76 would evaluate totrue
for two of the expressions in theif
statement:testscore >= 70
andtestscore >= 60
. However, as the runtime system processes a compoundif
statement such as this one, once a condition is satisfied (76 >= 70), the appropriate statements are executed (grade = 'C';
), and control passes out of theif
statement without evaluating the remaining conditions.The switch Statement
Use theswitch
statement to conditionally perform statements based on some expression. For example, suppose that your program contained an integer namedmonth
whose value indicated the month in some date. Suppose also that you wanted to display the name of the month based on its integer equivalent. You could use Java'sswitch
statement to perform this feat:Theint month; . . . switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; }switch
statement evaluates its expression, in this case, the value ofmonth
, and executes the appropriatecase
statement. Of course, you could implement this as anif
statement:Deciding whether to use anint month; . . . if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); . . . // you get the idea . . .if
statement or aswitch
statement is a judgment call. You can decide which to use based on readability and other factors. Eachcase
statement must be unique and the value provided to eachcase
statement must be of the same data type as the data type returned by the expression provided to theswitch
statement.Another point of interest in the
switch
statement are thebreak
statements after eachcase
. Thebreak
statements cause control to break out of theswitch
and continue with the first statement following theswitch
. Thebreak
statements are necessary becausecase
statements fall through. That is, without an explicitbreak
control will flow sequentially through subsequentcase
statements. In the previous example, you don't want control to flow from onecase
to the next, so you have to put inbreak
statements. However, there are certain scenarios when you do want control to proceed sequentially throughcase
statements. Like in the following Java code that computes the number of days in a month according to the old rhyme that starts "Thirty days hath September...":Finally, you can use theint month; int numDays; . . . switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; }default
statement at the end of theswitch
to handle all values that aren't explicitly handled by one of thecase
statements.int month; . . . switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Hey, that's not a valid month!"); break; }Loop Statements
You were introduced to Java'swhile
statement above. Java has two other looping constructs that you can use in your programs: thefor
loop and thedo-while
loop.Use the
for
loop when you know the constraints of the loop (its initialization instruction, termination criteria, and increment instruction). For instance,for
loops are often used to iterate over the elements in an array, or the characters in a string.You know when writing the program that you want to start at the beginning of the array, stop at the end, and hit every element. Thus the// a is an array of some kind . . . int i; int length = a.length; for (i = 0; i < length; i++) { . . . // do something to the i th element of a . . . }for
statement is a good choice. The general form of thefor
statement can be expressed like this:initialization is a statement that initializes the loop--its executed once at the beginning of the loop. termination is an expression that determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates tofor (initialization; termination; increment) statementsfalse
, thefor
loop terminates. Finally, increment is an expression that gets invoked for each iteration through the loop. Any (or all) of these components can be empty statements (a single semi-colon by itself).Java provides another loop, the
do-while
loop, which is similar to thewhile
loop you met earlier except that the expression is evaluated at the bottom of the loop:Thedo { statements } while (booleanExpression);do-while
statement is a less commonly used loop construct in programming but does have its uses. For example, thedo-while
is convenient to use when the statements within the loop must be executed at least once. For example, when reading information from a file, you know that you will always have to read at least one character:int c; InputStream in; . . . do { c = in.read(); . . . } while (c != -1);Exception Handling Statements
When an error occurs within a Java method, the method can throw an exception to indicate to its caller that an error occurred and the type of error that occured. The calling method can use thetry
,catch
, andfinally
statements to catch and handle the exception. See Handling Errors Using Exceptions for information about throwing and handling exceptions.Branching Statements
You saw thebreak
statement in action within theswitch
statement earlier. As noted there,break
causes the flow of control to jump to the statement immediately following the current statement.There is another form of
break
that causes flow of control to jump to a labeled statement. You label a statement by placing a legal Java identifier (the label) followed by a colon (:) before the statement:To jump to the statement labeledbreakToHere: someJavaStatementbreakToHere
use this form of thebreak
statement.Labeled breaks are an alternative to thebreak breakToHere;goto
statement, which is not supported by the Java language.Use the
continue
statement within loops to jump from the current statement back to the top of the loop or to a labeled statement. Consider this implementation of theString
class'sindexOf
method which uses the form ofcontinue
that continues to a labeled statement:public int indexOf(String str, int fromIndex) { char[] v1 = value; char[] v2 = str.value; int max = offset + (count - str.count); test: for (int i = offset + ((fromIndex < 0) ? 0 : fromIndex); i <= max ; i++) { int n = str.count; int j = i; int k = str.offset; while (n-- != 0) { if (v1[j++] != v2[k++]) { continue test; } } return i - offset; } return -1; }
Note: Thecontinue
statement can only be called from within a loop.
The last of Java's branching statements the
return
statement. You usereturn
to exit from the current method and jump back to the statement within the calling method that follows the original method call. There are two forms ofreturn
: one that returns a value and one that doesn't. To return a value, simply put the value (or an expression that calculates the value after thereturn
keyword:The value returned byreturn ++count;return
must match the type of method's declared return value.When a method is declared
void
use the form ofreturn
that doesn't return a value:return;
The Nuts and Bolts of the Java Language