Computer Applications
Rewrite the following code using single if statement.
if(code=='g')
System.out.println("GREEN");
else if(code=='G')
System.out.println("GREEN");
Answer
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 ifcode
is either'g'
or'G'
. - If either condition is true, the statement
System.out.println("GREEN");
will execute. This simplifies the multipleif-else
blocks into a singleif
statement.
Related Questions
Consider the following program segment in which the statements are jumbled, choose the correct order of statements to swap two variables using the third variable.
void swap(int a, int b) { a = b; → (1) b = t; → (2) int t = 0; → (3) t = a; → (4) }
- (1) (2) (3) (4)
- (3) (4) (1) (2)
- (1) (3) (4) (2)
- (2) (1) (4) (3)
Assertion (A): An argument is a value that is passed to a method when it is called.
Reason (R): Variables which are declared in a method prototype to receive values are called actual parameters
- Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)
- Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct explanation of Assertion(A)
- Assertion (A) is true and Reason (R) is false
- Assertion (A) is false and Reason (R) is true
Evaluate the given expression when the value of a=2 and b=3
b*=a++ - ++b + ++a; System.out.println("a= "+a); System.out.println("b= "+b);
A 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"); }