Lesson: Decision and control structures in Java
(Class 8)
Write the output for the following codes:
1. if (5>3)
System.out.println ("5 is greater");
else if (3>5)
System.out.println ("3 is greater");
else
System.out.println ("both are equal");
2. switch (ch)
{
case'a':
System.out.println ("Platform Independent");
break;
case'b':
System.out.println ("Object Oriented");
break;
case'c':
System.out.println ("Robust and Secure");
break;
default:
System.out.println ("wrong input");
}
i) if ch = 'b'
ii) if ch = 'a'
Answers
Answer:
1. 5 is greater
2. i) Object Oriented
ii) Platform Independent
Explanation:
Q1: in an if statement, the condition (expression in brackets) is first tested. If this is condition is True (i.e satisfied), then the else if and else clauses following it are not executed.
In the given question, 5 is undoubtedly greater than 3. This is why the line "5 is greater" is printed. As the condition is true, the subsequent cases are NOT checked as they are ELSE if an ELSE statements.
Extension activity: try to figure out what would happen if you replaced the else if and else with an if statement instead! I promise it'll help solidify your understanding of this concept.
Q2: in a switch case, the expression in brackets is tested against each of the case parameters.
Consider part i) of q2.
ch='b'
First case:
as 'b' is not equal to 'a', this condition is false; the statemetns under the first case ARE NOT executed.
Second case:
as 'b'='b', this condition is true; the statements under the second case ARE executed and we thus get "Object Oriented" as our output!
The case is concluded with a 'break' clause. This clause prevents a 'cascade effect' (i.e the subsequent cases are not tested, the system moves on to the block following switch)
Extension activity: attempt to reason what would happen if you removed all the break clauses in the second example.
I hope you have a better understanding of if-else-if and switch cases now. Do not hesitate to comment down below for further clarifications.
Cheers!
Answer:
A piece of advice for all my friends who are reading this: Life brings us as many joyful moments as it does downfalls, and ...
Top answer · 2 votes
Explanation:yup ur right................ More
0 votes
Answer:ya you are rightExplanation:i need a cute gf More