BeanShellTutorial:6 Conditions

From jWork.ORG
Revision as of 19:22, 27 December 2016 by Jworkorg (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Limitted access. Reguest membership or login to this link first if you are already a member
Contents

Conditions

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:


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

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


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