Code Fragment.

Q2. Given the following code fragment

        int ch=20;

        System.out.println(++ch);

        System.out.println(ch);

i.) What output does the above fragment produce?

ii.) What is the effect of replacing ++ch with ch+1?

Ans.

i.) 21

21

ii.) ++ch not only replaces itself with ch+1 i.e., 21 but also increments the value of ch i.e., after ++ch the value of ch is 21. Whereas ch+1 will only print the incremented value i.e., 20+1=21; it will not increment the value of ch. Therefore , after replacing ++ch with ch+1, the output of the program will be:

21

20

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: