2(i)
Rewrite the following code using single if statement.
if(code=='g')
System.out.println("GREEN");
else if(code=='G')
System.out.println("GREEN");Show SolutionHide Solution↓
The code can be rewritten using a single if statement as follows:
if(code == 'g' || code == 'G')
System.out.println("GREEN");
Explanation:
- The logical OR operator (
||) is used to check ifcodeis either'g'or'G'. - If either condition is true, the statement
System.out.println("GREEN");will execute. This simplifies the multipleif-elseblocks into a singleifstatement.