Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean example return unexpected answer

Tags:

java

boolean

I was going through java test given on indiabix and there a boolean question went something like -

public class If2 
{
    static boolean b1, b2;
    public static void main(String [] args) 
    {
        int x = 0;
        if ( !b1 ) /* Line 7 */
        {
            if ( !b2 ) /* Line 9 */
            {
                b1 = true;
                x++;
                if ( 5 > 6 ) 
                {
                    x++;
                }
                if ( !b1 ) /* Line 17 */
                    x = x + 10;
                else if ( b2 = true ) /* Line 19 */
                    x = x + 100;
                else if ( b1 | b2 ) /* Line 21 */
                    x = x + 1000;
            }
        }
        System.out.println(x);
    }
}

Now the explnation says - As instance variables, b1 and b2 are initialized to false. The if tests on lines 7 and 9 are successful so b1 is set to true and x is incremented. The next if test to succeed is on line 19 (note that the code is not testing to see if b2 is true, it is setting b2 to be true). Since line 19 was successful, subsequent else-if's (line 21) will be skipped. Thus the answer comes to 101 and not 111. But why would the if ( !b1 ) on Line 17 be ignored. Is it that the if ( !b1 ) on Line 7 is only considered true and later appearance of if ( !b1 ) on Line 17 is ignored. My understanding says answer should be 111 and not 101.

like image 346
Shaikh Sakib Avatar asked Jan 23 '26 20:01

Shaikh Sakib


2 Answers

In line 17 b1 is already true, since it was set to true on line 11. Therefore if ( !b1 ) evaluates to false.

Therefore only else if ( b2 = true ) is evaluated to true (and also assigns true to b2), and adds 100 to x.

x was already incremented once before that (line 12), so it ends up with the value 101.

Note that 111 would have been an impossible output even if if ( !b1 ) evaluated to true, since in that case else if ( b2 = true ) wouldn't be evaluated and x would end up with the value 11.

like image 107
Eran Avatar answered Jan 26 '26 10:01

Eran


It is very easy to understand. at line no.11 b1 is set to true.and after x is increment by 1. so x=1. Then at line no.17 if condition getting false !b1=>!true, so add not perform.

Then line no.19 ,condition getting true and add 100 to x i.e x=x+100. so result is 101.

like image 21
Mostch Romi Avatar answered Jan 26 '26 08:01

Mostch Romi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!