Java Programming - Flow Control - Discussion

Discussion :: 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);
    }
}

[A]. 41
[B]. 42
[C]. 50
[D]. 51

Answer: Option D

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.


Ankur Varshney said: (Dec 29, 2010)  
if ( hand > 50 );
This statement is not legal .so according to me this is error

Sonu said: (Nov 12, 2011)  
How line 7 can be true with one '&' operator? Can somebody explain this.

Sangeetha said: (Feb 14, 2012)  
By default is boolean instance variable are initialized to false?

Sonam said: (Sep 3, 2012)  
The 'if' statement on line 7 will return true hence hand will be incremented by 1,so its value will be 43.Then,if statement on line 9 won't be executed because that condition will be false so 'else if' will execute so value of hand will be 43+7+1=51.
So,answer will be 51.

Cloud Nine said: (Jul 6, 2013)  
@Sonu, That is the unary AND(^) operator.

A B (A^B)
0 0 0
0 1 0
1 0 0
1 1 1

Where, 0=false, 1=true.

Sravan said: (May 20, 2014)  
In line 9 as it is a legal statement why it would go for else if?

Kaushik Mitra said: (Jun 16, 2014)  
@Sravan, it is because flow goes to 'else if' part if the condition in 'if' statement is not satisfied.

Bhosale Suman said: (Nov 20, 2014)  
!b return true.

50&&!b return 1 = true.

If (42> 50&&!b) return false.

How line 7 can be true?

Ranga said: (Jun 24, 2015)  
What is the correct answer?

Srinivas said: (Feb 19, 2017)  
!b true because in place of
if (42>50&&!b) return true.

It means !b before ! default is False that's why that is true?

Shrey Jain said: (Aug 10, 2017)  
Boolean b how can you say Boolean variable b is ture?
And condition work.

I think the answer should we 41.

Ruhan said: (Sep 23, 2021)  
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.

Ruhan said: (Sep 23, 2021)  
@All.

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

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.