Quiz: Java Operators

To View Tricks: Login Required

Number of Questions: 20

Question: 16 -

What will be the output of the program?

class Bitwise 
{
    public static void main(String [] args) 
    {
        int x = 11 & 9;
        int y = x ^ 3;
        System.out.println( y | 12 );
    }
}

Options:
  1. 14

  2. 0

  3. 7

  4. 8

  5. Answer:

    14

    Solution:

    The & operator produces a 1 bit when both bits are 1. The result of the & operation is 9. The ^ operator produces a 1 bit when exactly one bit is 1; the result of this operation is 10. The | operator produces a 1 bit when at least one bit is 1; the result of this operation is 14.


Question: 17 -

What will be the output of the program?

public class Test 
{ 
    public static void leftshift(int i, int j) 
    {
        i <<= j; 
    } 
    public static void main(String args[]) 
    {
        int i = 4, j = 2; 
        leftshift(i, j); 
        System.out.println(i); 
    } 
}

Options:
  1. 4

  2. 2

  3. 10

  4. 8

  5. Answer:

    4

    Solution:

    Java only ever passes arguments to a method by value (i.e. a copy of the variable) and never by reference. Therefore the value of the variable i remains unchanged in the main method.

    If you are clever you will spot that 16 is 4 multiplied by 2 twice, (4 * 2 * 2) = 16. If you had 16 left shifted by three bits then 16 * 2 * 2 * 2 = 128. If you had 128 right shifted by 2 bits then 128 / 2 / 2 = 32. Keeping these points in mind, you don't have to go converting to binary to do the left and right bit shifts.


Question: 18 -

Which is the Logical operator in Java that works with a Single Operand?

Options:
  1. Logical AND

  2. Logical OR

  3. Logical NOT

  4. Logical Exclusive OR

  5. Answer:

    Logical NOT

    Solution not available.

Question: 19 -

What are the two possible Logical Operator types?

Options:
  1. Bitwise Logical

  2. A and B

  3. Arithmetic Logical

  4. Boolean Logical

  5. Answer:

    A and B

    Solution not available.

Question: 20 -

What will be the output of the program?

class Test 
{
    public static void main(String [] args) 
    {
        int x= 0;
        int y= 0;
        for (int z = 0; z < 5; z++) 
        {
            if (( ++x > 2 ) || (++y > 2)) 
            {
                x++;
            }
        }
    System.out.println(x + " " + y);
    }
}

Options:
  1. 5 3

  2. 8 2

  3. 8 3

  4. 8 5

  5. Answer:

    8 2

    Solution:

    The first two iterations of the for loop both x and y are incremented. On the third iteration x is incremented, and for the first time becomes greater than 2. The short circuit or operator || keeps y from ever being incremented again and x is incremented twice on each of the last three iterations.