Principles of Programming: Java Level 1 by Jonathan Frank

Principles of Programming: Java Level 1 by Jonathan Frank

Author:Jonathan Frank
Language: eng
Format: azw3, epub
ISBN: 9781514430378
Publisher: Xlibris US
Published: 2016-01-16T16:00:00+00:00


true

false

true

true

true

true

The Boolean expression, A OR B, has two input values: the values of Boolean expressions A and B. A OR B only yields false if BOTH A AND B are false. Otherwise, it yields true.

Checking to see whether a user’s input matches at least one of several choices is a common use of the logical OR operator. The program checks whether the user’s integer is evenly divisible by two or three, or whether it is divisible by neither. If X is evenly divisible by Y, then when X is divided by Y, the remainder is zero. Also, remember from Lesson 5: an expression, such as i % 2, which yields a result of type int, can be used anywhere that a literal value or the value of a variable, of type int, can be used. The Boolean expression, i % 2 == 0 || i % 3 == 0, gets evaluated.

Let’s try this with the integer, 8. Substitute 8 for i, in the Boolean expression, to make 8 % 2 == 0 || 8 % 3 == 0. The result of 8 mod 2 is equal to 0, so 8 % 2 == 0 yields true. In order for A || B || … to yield false, ALL of its input values must be false. If ANY of them are true, the expression will yield true. Therefore, there is no need to evaluate 8 % 3 == 0 here. The logical OR operator uses lazy evaluation, just like logical AND. If the user enters the number 8, the message, 8 is divisible by 2 or 3., will be printed.

Let’s try this with the integer, 5. Substitute 5 for i, in the Boolean expression, to make 5 % 2 == 0 || 5 % 3 == 0. The result of 5 mod 2 is NOT equal to 0, so 5 % 2 == 0 yields false. The result of 5 mod 3 is NOT equal to 0, so 5 % 3 == 0 also yields false. Substitute false for 5 % 2 == 0 and false for 5 % 3 == 0 to make false || false, which yields false. Since the first Boolean expression, 5 % 2 == 0, yielded false, the second one, 5 % 3 == 0, gets evaluated. This is because it’s still possible for the A || B || … expression to yield false, since a value of true has not been encountered yet (when only 5 % 2 == 0 has been evaluated). If the user enters the number 5, the message, 5 is not divisible by 2 or 3., will be printed.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.