Given the code fragment:
String valid = “true”;
if (valid) System.out.println (“valid”);
else system.out.println (“not valid”);
What is the result?
A.
Valid
B.
not valid
C.
Compilation fails
D.
An IllegalArgumentException is thrown at run time
Explanation:
In segment ‘if (valid)’ valid must be of type boolean, but it is a string.
This makes the compilation fail.
C.
Compilation fails
Answer is C.
The condition in a java if-statement must evaluate to a boolean true or false value. A String object, like as referred to by valid, cannot be used as an if-statement conditional. Doing so will result in a compile-time Java error: incompatible types: String cannot be converted to boolean.