1
{int num1 = 5; int num2 = 6; int num3; num3 = ++num2 * num1 / num2 + num2; System.out.println(num3);} //12 

The compiler gives the num3 = 12, but how do I get that value? when I try to get that num3 value I got 6(by without using compiler). Both value of num2++ and ++num2 gives the same, but when I use following code it gives a different value. Why I got different values. what are the steps for get those num3 values (without using compiler?)

num3 = num2++ * num1 / num2 + num2; //11 
1
  • Brackets my friend brackets. Remeber BODMAS Commented May 9, 2015 at 2:49

2 Answers 2

1

Both increment operation num++ and ++num will result into num=num+1 there is only difference between the order of assignment and increment operations.

num++(post-increment) -> first num is used and then incremented ++num(pre-increment) -> first num is incremented and then used

You code prints 12 when I tested.

public static void main(String[] args) { int num1 = 5; int num2 = 6; int num3; num3 = ++num2 * num1 / num2 + num2; System.out.println(num3); } 

I will suggest you to make use of brackets as it will increase readability as well.

Sign up to request clarification or add additional context in comments.

1 Comment

first one is 12 and second one is 11 no
0

If you do:

int num2 = 6; System.out.println(num2++); 

It will print 6, and then change num2 to 7. But if you do:

int num2 = 6; System.out.println(++num2); 

It will change num2 to 7 and then print 7. So:

num3 = ++num2 * num1 / num2 + num2; num3 = 7 * 5/ 7 + 7 num3 = 35/7 + 7 num3 = 12 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.