Booleans in Control Flow Statements

   

As you have already seen, Java is very strict when it comes to use of the boolean type. This strong typing also holds true in the restrictions placed on expressions that are allowed in the conditional clause of a control statement. These expressions are limited to variables (or literals) of the primitive type boolean and expressions that evaluate to a boolean result. Examples are shown in the following code fragments :

 boolean testVal = false; int intVal = 1; ... if (testVal) { }  else { } if (intVal != 1) { }  else { } ... while (testVal) { } while (intVal == 0) { } ... do { }  while (testVal) do { }  while (intVal == 0) for (int j=0; testVal; j++) { } for (int j=0; intVal < 5; j++) { } 

Here, the conditionals used by the various control statements are demonstrated with both a boolean variable and a Boolean expression built from a comparison of the integer intVal with an integer constant. Naturally, much more complicated Boolean expressions could be used in the same way.

A key point to make here is that this restriction to Boolean expressions is very much unlike C and C++. These languages allow a variety of data types and expressions to be used to direct control statements. Typical examples are the use of an integer variable or a pointer. Here, a non-zero integer or a non-null pointer is treated the same as a value of true. The following examples demonstrate the differences:

 int myInt = 3; String myString = null; ... // compiler error if (myInt) { }  else { } // can use this instead if (myInt != 0) { }  else { }  ... // compiler error if (myString) { }  else { } // can use this instead if (myString != null) { }  else { } 
   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net