Java Programming - Flow Control - Discussion

Discussion :: Flow Control - Finding the output (Q.No.1)

1. 

What will be the output of the program?

int i = l, j = -1; 
switch (i) 
{
    case 0, 1: j = 1; /* Line 4 */
    case 2: j = 2; 
    default: j = 0; 
} 
System.out.println("j = " + j); 

[A]. j = -1
[B]. j = 0
[C]. j = 1
[D]. Compilation fails.

Answer: Option D

Explanation:

The case statement takes only a single argument. The case statement on line 4 is given two arguments so the compiler complains.


Binod said: (Jun 22, 2011)  
I am not getting it. Please make me understood. How the loop goes.

Irfan said: (Jul 28, 2011)  
The above statement is correct if you write it this way.

switch (i)
{
case 0:
case 1: j = 1;
case 2: j = 2;
default: j = 0;
}

Dev Singh said: (Jun 21, 2013)  
Comma "," operator not allowed in case condition. Even it's ok in C programming.

Below is valid in C but not in Java :

int i = 2;
int j = 3;
int k = i+1, j;

printf(k); // it'll execute 3.

Because comma operator precedence is right. But if you enclose with brace like,

int k = (i+1), j;
printf(k); //it'll execute 3.

But above operation only with C not Java. :).

Chad Baker said: (Nov 27, 2013)  
Also, the original question sets the int i, to a letter (L), not a number. That causes a compilation error regardless of what's going on with the switch statement.

Rajiv said: (Aug 29, 2016)  
Error in line 1: int i = l, j = -1;

Ranjen said: (Oct 1, 2016)  
I believe it is correct and applicable from Java 8 onwards. So there is no wrong in this code for Java.

Then, case 0, 1: j = 1; /* Line 4 */

Elena said: (Mar 16, 2017)  
Agree @Chad Baker.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.