Quizzes Assignments Puzzles Easy exercises Required knowledge |

< |
Java Quizzes Green = Easy, Blue = Normal, Red = Hard Select 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 By title |
> |
---|

Here we have a combination of a while loop and a conditional statement.

### Java quiz 18: A while loop and conditional statements

Level: Normal

What is written to the standard output as the result of executing the following code?

public class MyClass { static boolean isActive; public static void main(String[] args) { int x = 7; int y = 1; while(!isActive) { if(x < 17) { x += 3; y += 2; if(x + y > 17) { isActive = true; } } } System.out.print(x - y); } }

###### Author: Sar Maroof

### Answer explanation

- The boolean variable isActive is not initialized. Therefore its value is false by default.
- As long as the variable isActive is false, the body of the while loop is executed.
- The statement x += 3; increments the value of x by 3. The statement y += 2; increments the value of y by 2. Therefore x = 7 + 3 = 10 and y = 1 + 2 = 3.
- The statement if(x + y > 17) returns false, because x + y = 10 + 3 = 13 and that is not greater than 17.
- For the next execution of the loop. x = 10 + 3 = 13, y = 3 + 2 = 5.So, x + y = 13 + 5 = 18 and that is greater than 17.
- For the next execution of the loop. x = 13 + 3 = 16, y = 3 + 2 = 5. x + y = 13 + 5 = 18 and that is greater than 17. Therefore the loop is executed and the staement System.out.print(x – y); writes x – y = 13 – 5 = 8 to the standard output.

The correct answer is: f.

## Suggested Articles

Subscribe to Sar Maroof's RSS feeds! Mail this page to a friend! Bookmark this page! |