<< |
Java Quizzes Green = Easy, Blue = Normal, Red = Hard Q01 Q02 Q03 Q04 Q05 Q06 Q07 Q08 Q09 Q10 Q11 Q12 Q13 Q14 Q15 Q16 Q17 Q18 Q19 Q20 Q21 Q22 Q23 Q24 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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!

SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

## Suggested Articles

## Books by Sar Maroof |

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