130 likes | 143 Views
Relational Operator and Operations. There are six binary relational operators in Java. They are used to form conditional expressions. They are used with primitive numeric and the character types only. Relational Operators & Operations. Relational expression.
E N D
Relational Operator and Operations • There are six binary relational operators in Java. • They are used to form conditional expressions. • They are used with primitive numeric and the character types only.
Relational expression • Relational expression is a combination of two primitive types separated by a relational operator. • The result from evaluating the expression is one of the boolean values,trueorfalse. • The general form of simple conditional statements is: • Left_Operand Relational_Operator Right_Operand Example: • 10 > 15 • ‘a’ != ‘A’
Evaluating Relational Expressions • When evaluating relational expressions, you must: • First resolve all arithmetic expressions to get the primitive values. • Then compare the primitive values as specified by the relational operator Example: Use the following declaration to evaluate the relational expressions int x = 10, y = 20; double z = 5.0; Evaluate the following relational expressions. • x / y < z • x%y - 10 >= x - y/x - z
Evaluate Relational Expression: x / y < z int x = 10, y = 20; double z = 5.0; x / y < z 0 true
Evaluate Relational Expression: x%y - 10 >= x - y/x - z int x = 10, y = 20; double z = 5.0; x % y - 10>= x - y / x - z 10 2 0 8 3.0 false
Evaluate Relational Expression: x%y – (10 >= x ) - y/x - z int x = 10, y = 20; double z = 5.0; X % y – ( 10 >= x ) - y/x - z
Evaluate Relational Expression: x%y – (10 >= x ) - y/x - z int x = 10, y = 20; double z = 5.0; x % y - ( 10 >= x ) - y / x - z 10 true ????
Evaluating Relational Expressions • The value from a relational expression can be assigned to a Boolean variable. The format is: boolean id = relational_expression. For example : int x = 120; double y = 20; boolean flag = 2 * x > y + 2; • Note: • The relational expression must be evaluated first. • The resulting value is assigned to the Boolean variable flag. • In this case the value true is assigned to the variable flag.
Logical Operator and Operations • Java has three logical operators: • logical-AND ( && ) – Determines the validity of two relational expressions • logical-OR ( || ) - Determines the validity of one or both two relational expressions • logical-NOT ( ! ) – Negates the result of a boolean value • This means that the relational expressions must first be evaluated, before logical operators can be applied.
Evaluate Logical Expression: x + y > z && x – y < z int x = 10, y = 20; double z = 5.0; x + y > z && x – y < z 30 -10 truetrue true
Evaluate Logical Expression int x = 10, y = 20; double z = 5.0; x - y > z || x – y < z -10 -10 falsetrue true
Evaluate Logical Expression: !(x + y > z && x – y < z) int x = 10, y = 20; double z = 5.0; !(x + y > z && x – y < z) 30 -10 truetrue true false