Java Programming - Flow Control - Discussion
Discussion Forum : Flow Control - Finding the output (Q.No. 1)
1.
What will be the output of the program?
int i = 1, j = -1;
switch (i)
{
case 0, 1: j = 1; /* Line 4 */
case 2: j = 2;
default: j = 0;
}
System.out.println("j = " + j);
Answer: Option
Explanation:
Multi-constant case labels supported from Java 14, No compilation error and output will be j=0.
Discussion:
9 comments Page 1 of 1.
Dev Singh said:
1 decade ago
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. :).
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. :).
(1)
Chad Baker said:
1 decade ago
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.
(1)
Irfan said:
1 decade ago
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;
}
switch (i)
{
case 0:
case 1: j = 1;
case 2: j = 2;
default: j = 0;
}
(1)
Ranjen said:
9 years ago
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 */
Then, case 0, 1: j = 1; /* Line 4 */
(1)
Binod said:
1 decade ago
I am not getting it. Please make me understood. How the loop goes.
(1)
Joel Varghese said:
4 years ago
Multi-constant case labels supported from Java 14 onwards only.
NUKE said:
2 years ago
For JDK 17.0.1.
No compilation errors:
Correct answer: j = 0.
No compilation errors:
Correct answer: j = 0.
(3)
RAJIV said:
9 years ago
Error in line 1: int i = l, j = -1;
Elena said:
8 years ago
Agree @Chad Baker.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers