Menu
Topics Index
...
`

Arrange the lines of the code


If you need explanation Read this topic

If you need Answer Take test on this topic

Arrange the lines of the code
How should be the lines M, N, O and P ordered such that x is 11, y is 16 and z is 25 at the end of the program.
class CompoundAssignments
{
    public static void main(String arg[])
    {
        int x = 5;
        int y = 2;
        int z = 3;

        x += 6; // LINE M
        y *= 8; // LINE N
        z += y * x; // LINE O
        z %= 7; // LINE P
    }
}

A. M, N, O, P
B. P, O, N, M
C. N, O, P, M
D. M, P, O, N
Topic: Arithmetic Compound Assignment Operators In Java

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.

Answer is D
IF the sequense of execution is as below,we will see the mentioned output

At the end of step 1 : Line M: x=11;y=2;z=3
At the end of Step 2 : Line P: x=11,y=3,z=3%7=3;
At the end of step 3 : Line O: x=11,y=3,z=z+(y*x)=3+(2*11)=25;
At the end of Step 4 : Line N: x=11y=2*8=16,z=25;

Posted by Shashanka Mogaliraju    2014-11-21 09:12:16


Ans is D...here we use the CompoundAssignment Operator which will increase the speed...and using this we can perform both arithmetic and assignment at a time..

we have these operators for +,-,*,/,% etc...
age+=3 is faster than the age=age+3
if we have lengthy variable names than this will usefull
here we create the 3 integer local variables named with x,y,z and assigned with the 5,2,3...for local variables JVM not going to provide any default values...if we use without initilization than Compilier will raise an error...

Coming to the program we need to arrange the lines in the Order Like M,P,O,N
Than the Code will be

x+=6;
z%=7;
z+=y*x;
y*=8;

if we extract it than it will look like this
x=x+6;
z=z%7;
z=z+y*x;
y=y*8;

After Executing the Line M:
x=x+6 means x=5+6;
x=11;y=2;z=3
After Executing the Line P:
z=3%7;
x=11,y=2,z=3
After Executing the Line O:
z=z+y*x;
x=11,y=3
here we have 2 Operators +,* According to the priority * will get evaluated
than z=z+y*x;
z=3+22;
z=25;
After Executing the Line N:
y=y*8;
y=8*2;
y=16
After this
x=11 and y=16 and z=25

Posted by Uday Kumar    2014-11-21 13:25:49


d

Posted by Shubham Bansal    2014-11-21 18:20:50


d

Posted by Sumeena Thatai Kalra    2014-11-22 14:30:54


This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Sai Ram,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Shashanka Mogaliraju. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-11-23 02:09:34


© meritcampus 2019

All Rights Reserved.

Open In App