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
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 5A student executes the following program segment and gets an error. Identify the statement which has an error, correct the same to get the output as WIN.
boolean x = true; switch(x) { case 1: System.out.println("WIN"); break; case 2: System.out.println("LOOSE"); }
Write a Java program to print name, purchase amount and final payable amount after discount as per given table:
Purchase Amount Discount upto ₹10000/- 15% ₹10000 to ₹ 20000/- 20% Above ₹20000/- 30% Write a program using switch case to find the volume of a cube, a sphere and a cuboid.
For an incorrect choice, an appropriate error message should be displayed.- Volume of a cube = s * s *s
- Volume of a sphere = (4/3) * π * r * r * r (π = (22/7))
- Volume of a cuboid = l*b*h