Conditional operators and control statements
In this section, you learn about the various statements and operators you can use to tell your Java programs how you want them to act based on different input.Relational and conditional operators
The Java language gives you operators and control statements that you can use to make decisions in your code. Most often, a decision in code starts with a Boolean expression (that is, one that evaluates to either true or false). Such expressions use relational operators, which compare one operand or expression to another, and conditional operators.Table 3 lists the relational and conditional operators of the Java language.
Table 3. Relational and conditional operators
| Operator | Usage | Returns true if... | 
|---|---|---|
> | a > b | a
                            is greater than b | 
>= | a >= b | a
                            is greater than or equal to b | 
< | a < b | a
                            is less than b | 
<= | a <= b | a
                            is less than or equal to b | 
== | a == b | a is
                            equal to b | 
!= | a != b | a is
                            not equal to b | 
&& | a &&
                                b | a and b are both true,
                            conditionally evaluates b (if a is false,
                                b is not evaluated)  | 
|| | a || b | a or
                                b is true, conditionally evaluates b (if
                                a is true, b is not evaluated)  | 
! | !a | a is false
                         | 
& | a & b | a
                            and b are both true, always evaluates
                        b | 
| | a | b | a or
                                b is true, always evaluates b | 
^ | a ^ b | a and
                                b are different  | 
 The if statement 
Now that you have a bunch of operators, it's time to use them. This code shows what
                happens when you add some logic to the Person object's
                    getHeight() accessor: 
1 
2 
3 
4 
5 
6 
7 
 | public int getHeight() {  int ret = height;  // If locale of the machine this code is running on is U.S.,  if (Locale.getDefault().equals(Locale.US))    ret /= 2.54;// convert from cm to inches  return ret;} | 
height (in
                centimeters) to inches. This (somewhat contrived) example illustrates the use of the
                    if statement, which evaluates a Boolean expression inside
                parentheses. If that expression evaluates to true, it executes the next statement. In this case, you only need to execute one statement if the
Locale of
                the machine the code is running on is Locale.US. If you need to execute
                more than one statement, you can use curly braces to form a compound
                    statement. A compound statement groups many statements into one —
                and compound statements can also contain other compound statements. Variable scope
Every variable in a Java application has scope, or localized namespace, where you can access it by name within the code. Outside that space the variable is out of scope, and you get a compile error if you try to access it. Scope levels in the Java language are defined by where a variable is declared, as shown in Listing 7.Listing 7. Variable scope
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
 | public class SomeClass {  private String someClassVariable;  public void someMethod(String someParameter) {    String someLocalVariable = "Hello";    if (true) {      String someOtherLocalVariable = "Howdy";    }    someClassVariable = someParameter; // legal    someLocalVariable = someClassVariable; // also legal    someOtherLocalVariable = someLocalVariable;// Variable out of scope!  }  public void someOtherMethod() {    someLocalVariable = "Hello there";// That variable is out of scope!  }} | 
SomeClass, someClassVariable is accessible by all
                instance (that is, nonstatic) methods. Within someMethod,
                    someParameter is visible, but outside of that method it is not, and
                the same is true for someLocalVariable. Within the if
                block, someOtherLocalVariable is declared, and outside of that
                    if block it is out of scope. For this reason, we say that Java has
                    block scope, because blocks (delimited by { and
                    }) define the scope boundaries. Scope has many rules, but Listing 7 shows the most common ones. Take a few minutes to familiarize yourself with them.
 The else statement
Sometimes in a program's control flow, you want to take action only if a particular
                expression fails to evaluate to true. That's when else comes in handy: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
 | public int getHeight() {  int ret;  if (gender.equals("MALE"))    ret = height + 2;  else {    ret = height;  Logger.getLogger("Person").info("Being honest about height...");  }  return ret;} | 
else statement works the same way as if, in that it
                executes only the next statement it runs across. In this case, two statements are
                grouped into a compound statement (notice the curly braces), which the program then
                executes. You can also use
else to perform an additional if check: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
 | if (conditional) {  // Block 1} else if (conditional2) {  // Block 2} else if (conditional3) {  // Block 3} else {  // Block 4} // End | 
conditional evaluates to true, then Block
                    1 is executed and the program jumps to the next statement after the
                final curly brace (which is indicated by // End). If
                        conditional does not evaluate to true, then
                        conditional2 is evaluated. If
                        conditional2 is true, then Block
                    2 is executed, and the program jumps to the next statement after the
                final curly brace. If conditional2 is not true, then the
                program moves on to conditional3, and so on. Only if all three
                conditionals fail is Block 4 executed. The ternary operator
The Java language provides a handy operator for doing simpleif /
                    else statement checks. Its syntax is: 
1 
 | (conditional) ? statementIfTrue : statementIfFalse; | 
conditional evaluates to true, then
                        statementIfTrue is executed; otherwise,
                        statementIfFalse is executed. Compound statements are
                not allowed for either statement. The ternary operator comes in handy when you know that you need to execute one statement as the result of the conditional evaluating to true, and another if it does not. Ternary operators are most often used to initialize a variable (such as a return value), like so:
1 
2 
3 
 | public int getHeight() {  return (gender.equals("MALE")) ? (height + 2) : height;} | 


0 comments:
Post a Comment