Menu
Topics Index
...
`

Operators output


If you need explanation Read this topic

If you need Answer Take test on this topic

Operators output
What will be the output of the following program?
class Operations
{
    int v;

    public static void main(String[] args)
    {
        new Operations().add(5).print().sub(7).print().multiply(3).add(3).print().sub(4).print();
    }

    Operations add(int i) { v+=i; return this; }

    Operations sub(int i) { v=-i; return this; }

    Operations multiply(int j) { v*=j; return this; }

    Operations print() { System.out.println("v = " + v); return this; }
}

A. v = 5
v = -2
v = -3
B. v = 5
v = -2
v = -3
v = -7
C. v = 5
v = -7
v = -18
v = -4
D. Compilation Error
Topic: Java Multiple Methods In One Class

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Here v is implicitly initialized with the default value of 0. Then a chain of method calls executes starting with add(5) which adds 5 to v. Then with sub(7), after applying unary minus (-) operator on the operand i (i.e, with the statement v = -i), the value of v becomes -7. Then with multiply(3), the value of v will become -21 which is added to 3 with add(3) yielding -18. Finally, with sub(4), the value of v becomes -4 (as unary minus produces negative value). So the answer is C.

Posted by Shaileshwar Sharma    2014-04-09 11:29:00


Congratulations Shaileshwar Sharma. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-04-10 03:55:40


© meritcampus 2019

All Rights Reserved.

Open In App