Learn AP Comp Sci

☰

Problem of the Day

Friday, October 30, 2026


Problem:

Consider the following method.

/**
* Identifies names that begin with A
* @param name a string that *may* be null!
*/
public static void initial(String name)
{
if ( /* missing code */ )
System.out.println("Begins with A");
else
System.out.println("Doesn't begin with an A");
}

Which of the following boolean expressions can be used to replace the /* missing code */ so that the method works as intended?


  1. name.substring(0,1).equals("A") && name != null

  2. name != null && name.substring(0,1).equals("A")
  1. I only
  2. II only
  3. Both I and II
  4. Neither I nor II

Show solution:

The correct answer is b. Given that there's a possibility that name has a null value, we need to check that possibility before checking to see what the initial letter of the name might be.

In an and statement (&&), if the first expression evaluates as false, further evaluation of the expression is "short-circuited"—we already know that the compound statement will be false, so we don't bother with evaluating the rest of it.