Java.lang Class

Q1: What will be the output of the program?
public class ExamQuestion7 
{  
    static int j; 
    static void methodA(int i)
    {
        boolean b; 
        do
        { 
            b = i<10 | methodB(4); /* Line 9 */
            b = i<10 || methodB(8);  /* Line 10 */
        }while (!b); 
    } 
    static boolean methodB(int i)
    {
        j += i; 
        return true; 
    } 
    public static void main(String[] args)
    {
        methodA(0); 
        System.out.println( 'j = ' + j ); 
    } 
}

A j = 0

B j = 4

C j = 8

D The code will run with no output

ANS:A - j = 0

The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed. However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called. The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4.



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.