Learn AP Comp Sci

Problem of the Day

Thursday, January 22, 2026


Problem:

Assume that d and e are int variables that have each been given initial values d = -1 and e = 2. What value will be printed when the following code is executed?

int f = 5;
if (d > 0)
if (e > 0)
f = f + 1;
else
f = f - 1;
System.out.println(f);
  1. 4
  2. 5
  3. 6
  4. none of these

Show solution:

The correct answer is b. The code has been arranged such that the if and else statements aren't visually aligned the way that Java interprets these instructions, and it's possible to misinterpret the logic of the statements.

A more clear way to arrange this same code would be

int f = 5;
if (d > 0)
if (e > 0)
f = f + 1;
else
f = f - 1;
System.out.println(f);

where the else statement, logically connected to the nearest if statement, is lined up beneath it.

To make it even more clear, use curly braces to clearly (and visually) identify the logic:

int f = 5;
if (d > 0)
{
if (e > 0)
{
f = f + 1;
}
else
{
f = f - 1;
}
}
System.out.println(f);