Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 4)
4.
What will be the output of the program?
public class SwitchTest 
{  
    public static void main(String[] args) 
    {
        System.out.println("value =" + switchIt(4)); 
    } 
    public static int switchIt(int x) 
    {
        int j = 1;  
        switch (x) 
        { 
            case l: j++; 
            case 2: j++;  
            case 3: j++; 
            case 4: j++; 
            case 5: j++; 
            default: j++; 
            } 
        return j + x;  
    } 
}
value = 2
value = 4
value = 6
value = 8
Answer: Option
Explanation:

Because there are no break statements, once the desired result is found, the program continues though each of the remaining options.

Discussion:
14 comments Page 2 of 2.

Senthil kumar said:   1 decade ago
When you are consider this program

The actual value of "J" is 1 and "X"

Position is 4 so,the 4th position of "J" value is 5 and default Place does not have and break .

So that position also increment so eventually result of program is

4th place value=5
5th place
value=6
default
value=7
j=1 as per intial

So, total = 7+1 = 8.

Aashish said:   1 decade ago
First it satisfies the condition x=4
then it jumps to case 4, and then because of no break statements,
it executes all statements..
So, in case 4 , j becomes 1
in case 5 , j becomes 2
in case dafault , j becomes 3
But there is a post increment operator so it increments the value
of j to 4 after the default case executes..
and then it returns 4+4=8 value...
Hope you understand...

Ishrat said:   1 decade ago
Please someone explain this problem how 8 comes ?

Thg said:   1 decade ago
int x=4

then cm to switch statement x=4 .
case 4 will we executed j++ =2
case 5 j++ =3
return j+x
3+4 =7

the result is 7..
how 8 come


Post your comments here:

Your comments will be displayed after verification.