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");
Java Conditional Stmts
1 Like
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.
Answered By
1 Like
Related Questions
Using the switch-case statement, write a menu driven program to do the following:
(a) To generate and print Letters from A to Z and their Unicode
Letters Unicode A 65 B 66 . . . . . . Z 90 (b) Display the following pattern using iteration (looping) statement:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Which of the following is true about the
default
label in aswitch
statement?Rewrite the following code using single if statement.
if(code=='g') System.out.println("GREEN"); else if(code=='G') System.out.println("GREEN");
An air-conditioned bus charges fare from the passengers based on the distance travelled as per the tariff given below:
Distance Travelled Fare Up to 10 km Fixed charge ₹80 11 km to 20 km ₹6/km 21 km to 30 km ₹5/km 31 km and above ₹4/km Design a program to input distance travelled by the passenger. Calculate and display the fare to be paid.