Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 7)
7.
What will be the output of the program?
public class If1 
{
    static boolean b;
    public static void main(String [] args) 
    {
        short hand = 42;
        if ( hand < 50 && !b ) /* Line 7 */
            hand++;
        if ( hand > 50 );     /* Line 9 */
        else if ( hand > 40 ) 
        {
            hand += 7;
            hand++;    
        }
        else
            --hand;
        System.out.println(hand);
    }
}
41
42
50
51
Answer: Option
Explanation:

In Java, boolean instance variables are initialized to false, so the if test on line 7 is true and hand is incremented. Line 9 is legal syntax, a do nothing statement. The else-if is true so hand has 7 added to it and is then incremented.

Discussion:
13 comments Page 2 of 2.

Shrey jain said:   8 years ago
Boolean b how can you say Boolean variable b is ture?
And condition work.

I think the answer should we 41.

Ruhan said:   4 years ago
@All.

I think the line 9 condition is not satisfied. Am I right?

Ruhan said:   4 years ago
If (hand > 50); this is legal and we won't get any error but as the condition is true and we entered in this statement then why we are going for else if condition, as our first statement is satisfied program, should be executed there itself and answer is 43.


Post your comments here:

Your comments will be displayed after verification.