logo

CuriousTab

CuriousTab

Discussion


Home Java Programming Flow Control See What Others Are Saying!
  • Question
  • What will be the output of the program?
    int x = 3; 
    int y = 1; 
    if (x = y) /* Line 3 */
    {
        System.out.println("x =" + x); 
    }
    


  • Options
  • A. x = 1
  • B. x = 3
  • C. Compilation fails.
  • D. The code runs with no output.

  • Correct Answer
  • Compilation fails. 

    Explanation
    Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails.

    More questions

    • 1. What will be the output of the program?
      class Super
      { 
          public int i = 0; 
      
          public Super(String text) /* Line 4 */
          {
              i = 1; 
          } 
      } 
      
      class Sub extends Super
      {
          public Sub(String text)
          {
              i = 2; 
          } 
      
          public static void main(String args[])
          {
              Sub sub = new Sub("Hello"); 
              System.out.println(sub.i); 
          } 
      }
      

    • Options
    • A. 0
    • B. 1
    • C. 2
    • D. Compilation fails.
    • Discuss
    • 2. 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