2018年3月17日 星期六

Logical Operators exclusive-OR (^) and Boolean invert (!)

The last two logical operators on the exam are
  • ^ exclusive-OR (XOR)
  • ! Boolean invert

The ^ (exclusive-OR) operator evaluates only boolean values. The ^ operator is related to the non-short-circuit operators we just reviewed, in that it always evaluates both the left and right operands in an expression. For an exclusive-OR (^) expression to be true, EXACTLY one operand must be true—for example,

System.out.printIn ("xor " + ((2<3) ^ (4>3)));

produces the output: xor false

The preceding expression evaluates to false because BOTH operand one (2 < 3) and operand two (4 > 3) evaluate to true.

The ! (boolean invert) operator returns the opposite of a boolean's current value:

if (!(7 == 5)) { system.out.println ("not equal"); }

can be read "if it's not true that 7 == 5," and the statement produces this output: not equal

Here's another example using booleans:

boolean t = true;
boolean f = false;
System.out.println ("! " + (t & !f) + " " + f);

produces the output: ! true false

In the preceding example, notice that the & test succeeded (printing true), and that the value of the boolean variable f did not change, so it printed false.

Given:

1. public class Spock{
2.     public static void main(String[] args){
3.         Long tail = 2000L;
4.         Long distance = 1999L;
5.         Long story = 1000L;
6.         if((tail>distance) ^ ((story*2)==tail))
7.             System.out.print("1");
8.         if((distance+1 != tail) ^ ((story*2)==distance))
9.             System.out.print("2");
10.     }
11. }

What is the result?

A. 1
B. 2
C. 12
D. Compilation fails.
E. No output is produced.
F. An exception is thrown at runtime.

沒有留言:

張貼留言