# Simple looking but tough

Shailendra Guggali

Ranch Hand

Posts: 86

posted 15 years ago

look at the foll code :

public class TestClass

{

public static void main (String args[ ] )

{

int k = 1;

int i = ++k + k++ + + k ;

System.out.print(i+ " "+ k) ;

}

}

what is the result??

i thought ++k makes it 2 then k++ keeps it at 2 and +k doesn't change its value( just makes it positive). so the result should be 2+2+2 = 6

i = 6; k = 2

But it is wrong!!!

public class TestClass

{

public static void main (String args[ ] )

{

int k = 1;

int i = ++k + k++ + + k ;

System.out.print(i+ " "+ k) ;

}

}

what is the result??

i thought ++k makes it 2 then k++ keeps it at 2 and +k doesn't change its value( just makes it positive). so the result should be 2+2+2 = 6

i = 6; k = 2

But it is wrong!!!

Udayan Naik

Ranch Hand

Posts: 135

posted 15 years ago

Hi Shailendra.The answer will be 7,not 6.If we go over it...

1)Initially k=1;

2)++k will make k=2 since we are using a prefix operator.(as said by you).So currently the value of the expression is 2.

3)Now since there is a postfix operator in k++,the SAME VALUE of k will be used at that point in evaluating the expression.Thus now value is 2+2;

4)NOW k WILL BE INCREMENTED,because of the postfix operator.Thus now k=3;

5)Now to this expression,we are adding +k.Hence now we have value of expression as 2+2+3=7.This is assigned to i,hence i=7;

Remember,at every point the CURRENT VALUE of the variable will be used when evaluating the expression.

I hope i have been clear enough.

1)Initially k=1;

2)++k will make k=2 since we are using a prefix operator.(as said by you).So currently the value of the expression is 2.

3)Now since there is a postfix operator in k++,the SAME VALUE of k will be used at that point in evaluating the expression.Thus now value is 2+2;

4)NOW k WILL BE INCREMENTED,because of the postfix operator.Thus now k=3;

5)Now to this expression,we are adding +k.Hence now we have value of expression as 2+2+3=7.This is assigned to i,hence i=7;

Remember,at every point the CURRENT VALUE of the variable will be used when evaluating the expression.

I hope i have been clear enough.

Udayan Naik<BR>Sun Certified Programmer for the Java 2 Platform

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |