Computer Applications
Predict the output of the following Java program code snippet:
int a=1,b=2,c=3;
switch(p)
{
case 1: a++;
case 2: ++b;
break;
case 3: c--;
}
System.out.println(a + ","
+ b + "," +c);
Answer
(i) p = 1
2,3,3
Working
When p
is 1, case 1
is matched. a++
increments value of a
to 2. As there is no break
statement, fall through to case 2
happens. ++b
increments b
to 3. break
statement in case 2
transfers program control to println
statement and we get the output as 2,3,3.
(ii) p = 3
1,2,2
Working
When p
is 3, case 3
is matched. c--
decrements c
to 2. Program control moves to the println
statement and we get the output as 1,2,2.
Related Questions
State whether the following statement is True or False :
The break statement may not be used in a switch statement.
Predict the output of the following Java program code snippet:
int m=3,n=5,p=4; if(m==n && n!=p) { System.out.println(m*n); System.out.println(n%p); } if((m!=n) || (n==p)) { System.out.println(m+n); System.out.println(m-n); }
switch case construct into if-else-if :
switch (n) { case 1: s=a+b; System.out.println("Sum="+s); break; case 2: d=a-b; System.out.println("Difference="+d); break: case 3: p=a*b; System.out.println("Product="+p); break; default: System.out.println("Wrong Choice!"); }
if-else-if construct into switch case:
if(var==1) System.out.println("Distinction"); else if(var==2) System.out.println("First Division"); else if(var==3) System.out.println("Second Division"); else System.out.println("invalid");