23. Precedence of NOT


Answer:

No. In this defective fragment, the NOT (the !) applies directly to cost.

Precedence of NOT

The NOT operator has high precedence, so it is done before arithmetic and relational operators unless you use parentheses. Examine the following:

!cost < 50 
-----
illegal: can't use ! on an arithmetic variable

Since ! has high precedence, the above says to apply it to cost. This won't work because cost is an integer and NOT applies only to boolean values.


Question 24:

You need new shoes. But all you can afford is a pair of shoes that costs less than fifty dollars.

Look at these fragments of code. Does each do the same thing?


    if ( cost < 50 ) System.out.println("Acceptable shoes"); else System.out.println("Reject these shoes");

    if ( !(cost < 50) ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes");

    if ( cost >= 50 ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes");

    if ( !(cost >= 50) ) System.out.println("Acceptable shoes"); else System.out.println("Reject these shoes");

Mentally try a few costs with each fragment to see if they are equivalent.