Java if else & switch Practice Questions
- Categories Java, if & switch, if & switch
Below are few questions on Java if else and switch
- Convert the following if-else-if construct into switch case:
if(var == 1)
System.out.println("good");
else if(var == 2)
System.out.println("better");
else if(var == 3)
System.out.println("best");
else
System.out.println("invalid");
Ans
switch(var) { case 1: System.out.println("good"); break; case 2: System.out.println("better"); break; case 3: System.out.println("best"); break; default: System.out.println("invalid"); }
- Find the output in the following code snippet:
int ch=2;
switch(ch) {
case 1: System.out.println("All courses");
Break;
case 2: System.out.println("Simply Coding ");
case 3: System.out.println("Best Study Material");
}
Ans.
Simply Coding
Best Study Material
- Rewrite the following program code using suitable ‘if’ command.
switch(m){
case 0:
x=x+2;
System.out.println(“X=” x);
break;
case 1:
x=x+4;
System.out.println(“X=” x);
break;
case 2:
x=x+6;
System.out.println(“X=” x);
break; }
Ans:
if(m==0){ x= x+2; System.out.println(“X=” +x); } else if(m==1){ x= x+4; System.out.println(“X=” +x); } if(m==2){ x= x+6; System.out.println(“X=” +x); }
- What is wrong in the following program code? Find any 2 errors and explain.
switch (p)
?
case 3:
int x= 12; int y = 35;
int z= x* y;
break;
case 3:
int a = 20;
int b = 76;
break;
int z=x * y;
Ans.
- Just after switch statement the question mark (?) symbol should be replaced by open brace (), this shows the beginning of switch block.
- The constants value for two or more case statements cannot be same so, one should be changed.
- In case 3 the break statement is present before the last statement z= x* y which is wrong and the error message that appears is “unreachable code”.
- Rewrite the following code after corrections.
int a;
if(a=1)
a==100;
else If(a=2)
a=1000;
Ans:
int a; if(a==1) a=100; else if(a==2) a=1000;
- Give the output of the following code fragment when
(i) opn = ‘b’
(ii) opn = ‘x’
switch (opn)
{
case ‘a’:
System.out.println(“Simply Coding”);
break;
case ‘b’:
System.out.println(“Online Tutor”);
case ‘c’:
System.out.println(“Online Courses”);
default:
System.out.println(“Invalid Input”);
}
Ans.
i. Online Tutor
Online Courses
Invalid Input
ii. Invalid Input
You may also like
If-else and switch Programs
22 June, 2021
Conditional Statements in Java
16 June, 2021
Forming Math Expressions
13 June, 2020