Computer Applications
Ravi runs the following Java code but encounters an error. Identify the statement causing the issue, correct it, and ensure the output is "Hungry".
char h = 'Y';
if (h == 'y' || 'Y')
System.out.println("Hungry");
else
System.out.println("Not Hungry");
Answer
char h = 'Y';
if (h == 'y' || h == 'Y') {
System.out.println("Hungry");
} else {
System.out.println("Not Hungry");
}
Reason — The problem lies in the condition of the if statement:
if (h == 'y' || 'Y')
The condition 'Y' is invalid because || expects boolean expressions on both sides. 'Y' alone is a char, not a boolean, causing a compilation error.
The statement can be corrected as:
if (h == 'y' || h == 'Y')
Now both sides of || are boolean expressions.
Related Questions
Differentiate between if else if and switch-case statements
The statement that brings the control back to the calling method is:
- break
- System.exit(0)
- continue
- return
Which of the following data type cannot be used with switch case construct?
- int
- char
- String
- double
Rewrite the following code using single if statement.
if(code=='g') System.out.println("GREEN"); else if(code=='G') System.out.println("GREEN");