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 onlu 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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s