Question:

Java code (explain only..)

by  |  earlier

0 LIKES UnLike

Given x = 1, y = 2, what is the output of the following code?

if (x != y)

System.out.print ("Statement 1. ");

else

System.out.print ("Statement 2. ");

System.out.print ("Statement 3. ");

Answers are statements 1 & 3.

Hmm, why is it statement 3? Is it because there is a semi-colon after the statement 2 so it prints out statement 3 as well? I think it should just print out statement 1 since x != y is true...

 Tags:

   Report

2 ANSWERS


  1. The else includes the one statement after it much like the if so statement 3 is not part of the if/else and thus is always printed.


  2. Your code can be re written as

    if (x != y)

    {

    System.out.print ("Statement 1. ");

    }

    else

    {

    System.out.print ("Statement 2. ");

    }

    System.out.print ("Statement 3. ");

    Reason being if AND else both will consider next line within their scope by default.

    So,Third one is independent of IF AND ELSE.

    In any case 3 will be printed along with 1 and 2 depending upon condition provided in IF()

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.