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?
name.substring(0,1).equals("A") && name != nullname != null && name.substring(0,1).equals("A")
- I only
- II only
- Both I and II
- Neither I nor II
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.