Java Reference
In-Depth Information
You can combine the Boolean operators to create a more complex Boolean
expression. For example, try to determine the result of the following code:
int x = 5, y = 6, z = -3;
boolean b = ((x + 3 > y) ^ (z >= y)) && !(x == 5 | ++x == y);
Pay close attention to the parentheses. If you replace the comparisons with
true and false, you get the following logically equivalent statement:
(true ^ false) && !(true | true)
Evaluating the ^ and | expressions gives you:
true && !(true)
This is the same as true and false, which is false; therefore, the variable b in
the code above will be the value false.
Now that you have seen the Boolean operators, I am ready to talk about the
various control structures in Java, all of which involve some type of Boolean
expression.
The if Statement
An if statement consists of a Boolean expression followed by one or more state-
ments. If statements have the following syntax:
if( Boolean_expression )
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression in parentheses is true, the statements within the
curly brackets are executed. If the Boolean expression is false, the statements in
curly brackets are skipped over. In the case of false, the flow of control will
jump to the statement that is immediately beyond the curly brackets.
The IfDemo program that follows demonstrates using if statements. Study
the program and try to determine what the output will be. A sample output is
shown in Figure 3.1.
public class IfDemo
{
public static void main(String [] args)
{
int x = Integer.parseInt(args[0]);
Search WWH ::




Custom Search