Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Logical operators and expressions

The class String | Useful examples | Defining attributes of objects | Defining operations on objects (methods) | Defining methods of object creation (constructors) | Static members | Packages and imports | Scope of an identifier. Local variables. Access control. | Structure of a program. Running an application. | A brief survey of control statements. |


Читайте также:
  1. A claim should be well organized with information in a logical order.
  2. A contrastive analysis of English and Ukrainian morphological stylistic means
  3. A) Biological Sciences
  4. Absence of the articles in set expressions
  5. According to their morphological composition adjectives can be subdivided intosimple, derived andcompound.
  6. Additional Words and Expressions
  7. Anatomy, histology and physiology of the normal skin. Histomorphological changes in the skin.

Logical operators are used to create compound conditions:

Assume we want to check whether the following condition holds: a value n lies in the interval [1, 10], i.e. n is greater than or equal 1 and, at the same time, less than or equal 10.
As we already know the notation if (1 <= n <= 10) is incorrect (because relational operators are applied to numeric types only and the expression 1 <= n is of boolean type).
We must apply the conditional-and operator here to check whether the two conditions hold.

n >= 1 and n <= 10.

In Java it is noted as:

n >= 1 && n <= 10

and used as the control expression of the if statement:

if (n >= 1 && n <= 10)...;


Similarly we might want to check whether a value n lies outside the interval [1, 10]. To fulfill such a condition n has to be less than 1 or greater than 10.
To note this in Java the conditional-or operator is applied:

if (n < 1 || n > 10)..

The third logical operator - logical complement - is used to negate expressions.
For example, if we want to take some action in case a variable txt does not represent the string "Abc" we write:

if (! txt.equals("Abc"))...;

Arguments to logical operators must be expressions of boolean type. The result of such an expression is of boolean type too. Its value is true or false according to the following table:

Conditional logical operators
a b a && b a || b !a
true true true true false
false true false true true
true false false true  
false false false false  

 

The operator && has the value true only if both its arguments have the value true, and false otherwise.
The operator || has the value true if at least one of its arguments is true, and is false if both its arguments are false.

 


Logical operators have lower precedence than relational operators and equality operators. Thus we can write (without parentheses):

if (a == 1 && b > 3) c = a + b;

to calculate c when a is equal 1 and b > 3.


Note: the unary complement operator has higher precedence than other logical operators. Therefore parentheses should be applied to ensure the proper order of evaluation of subexpressions.


For example, if we want to take some action in case the following condition does not hold:
the variable txt does not hold the string "Abc" and - at the same time - the variable years has the value greater than 1,
we cannot write:

if (! txt.equals("Abc") && years > 1)...

as this has the meaning of simultaneous fulfilment of the two conditions:
- the string txt is not "Abc"
- years is greater than 1
(of course it is not what we wanted).

We must write instead:

if (!(txt.equals("Abc") && years > 1))...

Additional parentheses modify the order of evaluation of subexpressions and thus we achieve the desired effect.

The discussed operators are called conditional logical operators because they are evaluated from-left-to-right and the evaluation stops when the value of the whole expression is known (lazy evaluation).
This means that not all subexpressions are evaluated if some part of the whole expression determines the result. For example, in the following expression:

a && (b > 0 || c == 1)

if a is false then the expression in the parentheses will not be evaluated, as the value of the whole expression does not depend on its value (if a == false then the whole expression must be false).

In Java there are unconditional logical operators (called boolean logical operators):

The boolean logical operators: & and | have the same properties as the conditional operators:&& and || with the following exception: both operands are evaluated unconditionally.

The exclusive OR operator (^) acts as follows:

 

The boolean logical operators are applied to arguments of boolean type only.
Unfortunately, the same symbols (&, |, ^, ~) denote bitwise operators which are applied to integer numbers (they enable operations on bits).

 

9.4. Making decisions: the if and if-else statements.

As we know, the if statement has the following form:

 

if (exp) ins

where:

Execution: the instruction ins is executed if and only if the value of the expression exp is true.

 


The if-else statement has the form:

 

if (exp) ins1
else ins2

where:

Execution: the instruction ins1 is executed if and only if the value of the expression exp is true. If the value of the expression exp is false then the instruction ins2 is executed.

 

The following examples demonstrate the difference between the if and the if-else statements:

if (a == b) c = d;
c = e;
System.out.println(a + " " + b + " " + c + " " + d);

and

if (a == b) c = d;
else c = e;
System.out.println(a + " " + b + " " + c + " " + d);

The instruction c = d in the first piece of code is to be executed only if the value of the variable a is equal to b. However, independently of this condition, just after the execution of the if statement, the value of the variable e will be stored in the variable c (thus the if statement is not necessary here). Then the values of variables are printed at the command prompt.
In the second piece of code the value of the variable c depends on whether a == b or not (exactly one of the assignments will be executed: c = d or c = e).

Of course the instructions ins1 and ins2 from the definition may be the if (or if-else) statements allowing nesting of conditions:

char op;double a, b, r;...if (op == '+') r = a + b;else if (op == '-') r = a - b; else if (op == '*') r = a*b; else if (op == '/') r = a/b; else System.out.println("Incorrect operation code");

Here arises the question: which else corresponds to which if? The rule is simple: to the given else corresponds the first if that precedes it in the same block and is not already matched. Of course indentation of code does not influence matching of if-else pairs.

Here are some common mistakes made when dealing with the if and if-else statements:

A. Improper matching of if and else in case of the nested if-else statements.

B. The semicolon put after the closing parenthesis of the condition:

if (a > b);
System.out.println("a > b"); // will execute independently of a>b!

C. Lost the closing brace ending a block:

if (a > b) {
c = a + b;
d = e + f;
else c = d + f;

 



Дата добавления: 2015-11-16; просмотров: 51 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Comparison operators and expressions| Multivariant selections done with the switch statement.

mybiblioteka.su - 2015-2024 год. (0.008 сек.)