Machine-translated by Google. Questions are authored in English.
Top

Discussion

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 1: j++; 
            case 2: j++;  
            case 3: j++; 
            case 4: j++; 
            case 5: j++; 
            default: j++; 
            } 
        return j + x;  
    } 
}

  • A.value = 2
  • B.value = 4
  • C.value = 6
  • D.value = 8

Answer: D

Correct answer: value = 8

Switch labels fall through unless a break intervenes, and here none does. With x = 4 control enters at case 4 and then runs through case 5 and default, so j is incremented three times from 1 to 4. The method returns \( j + x = 4 + 4 = 8 \). Counting only the matching label gives 2 and 6, both of which are offered.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.