logo

CuriousTab

CuriousTab

Discussion


Home Java Programming Flow Control See What Others Are Saying!
  • Question
  • What will be the output of the program?
    for(int i = 0; i < 3; i++) 
    { 
        switch(i) 
        { 
            case 0: break; 
            case 1: System.out.print("one "); 
            case 2: System.out.print("two "); 
            case 3: System.out.print("three "); 
        } 
    } 
    System.out.println("done");
    


  • Options
  • A. done
  • B. one two done
  • C. one two three done
  • D. one two three two three done

  • Correct Answer
  • one two three two three done 

    Explanation
    The variable i will have the values 0, 1 and 2.

    When i is 0, nothing will be printed because of the break in case 0.

    When i is 1, "one two three" will be output because case 1, case 2 and case 3 will be executed (they don't have break statements).

    When i is 2, "two three" will be output because case 2 and case 3 will be executed (again no break statements).

    Finally, when the for loop finishes "done" will be output.


    More questions

    • 1. What will be the output of the program (in jdk1.6 or above)?
      public class BoolTest 
      {
          public static void main(String [] args) 
          {
              Boolean b1 = new Boolean("false");
              boolean b2;
              b2 = b1.booleanValue();
              if (!b2) 
              {
                  b2 = true;
                  System.out.print("x ");
              }
              if (b1 & b2) /* Line 13 */
              {
                  System.out.print("y ");
              }
              System.out.println("z");
          }
      }
      

    • Options
    • A. z
    • B. x z