Tutorial:BeanShell/6 Conditions

From HandWiki


Conditionals are where a section of code is only run if certain conditions are met. The most common conditional is the 'if' statement.

The relational operators you've learned so far:

<, <=, >, >=, !=, ==

are sufficient when you only need to check one condition. However what if a particular action is to be taken only if several conditions are true? You can use a sequence of if statements to test the conditions, as follows:

<jc lang="bsh"> x=2; y=1; if (x == 2) {

 if (y != 2) {
    print("Both conditions are true.");
  }

} </jc>

This, however, is hard to write and harder to read. It only gets worse as you add more conditions. Fortunately, Java provides an easy way to handle multiple conditions: the logic operators. There are three logic operators, &&, || and !.

&& is logical and. && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance

boolean b;
b = 3 > 2 && 5 < 7; //  b is true
b = 2 > 3 && 5 < 7; //  b is now false
is logical or. combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. For instance
boolean b;
b = 3 > 2 || 5 < 7; // b is true
b = 2 > 3 || 5 < 7; // b is still true
b = 2 > 3 || 5 > 7; // now b is false

The last logic operator is ! which means not. It reverses the value of a boolean expression. Thus if b is true !b is false. If b is false !b is true.

boolean b;
b = !(3 > 2);  // b is false
b = !(2 > 3);  //  b is true

These operators allow you to test multiple conditions more easily. For instance the previous example can now be written as

<jc lang="bsh"> x=2; y=1; if (x == 2 && y != 2) {

 print("Both conditions are true.");

} </jc>