0

I think the following code should print 26 but it's printing 62 instead.

public class gjh
{
 public static void main(String[] args)
   {
        int x = 2; 
        x += ++x * ++x * ++x;
        System.out.println(x);
    }

}

So how is this possible?

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by hszforu
2

++x is 3, then the next ++x is 4 then the last one is 5, so you have 345 ie 60.
Now x+= adds that 60 to the initial value of x (2) to give a result of 62.

Votes + Comments
nice maths :)
0

oops!! that was my mistake.Initially i excuted the following program whose output should be 26.

public class gjh
{
 public static void main(String[] args)
   {
        int x = 2; 
        x +=x++ * x++ * x++;
        System.out.println(x);
    }
}

I changed the pre increment operators to post increment, and that should then output 62 as expected.

Well thanks for answering.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.