Chris
Chris

Reputation: 1939

Postincrement and preincrement in Java expressions

What does each expression evaluate to? Assume x is 2 before each one.

Upvotes: 1

Views: 347

Answers (5)

Jerome
Jerome

Reputation: 4572

int num = x++ * 3; => OK: x = 3, num = 6
num *= x; => what's the initial value of num ? if num = 2, then you are also OK.
(x < 2) && (x > 1) is false when x = 2, OK
(++x < 2) || (x < 1) is false when x = 2, OK as well

I remember I had a look at the openJDK, especially the Lower class in javac source and ++x is translated into x += 1 therefore you can see it as:
((x += 1)) < 2) which is (whithout type casting): ((x = (x + 1)) < 2). The second test will have the newer x value i.e 3 because java evaluates the conditions from left to right.

Upvotes: 1

Pradeep Gollakota
Pradeep Gollakota

Reputation: 2181

  1. "Assume x is 2 before each one." Is that a given assumption or is it an assumption you're making? I don't believe that you can make that assumption. I believe that you have evaluate all of these statements in sequence.
  2. What is the expanded form of a *= b?
  3. What is the initial value of num when you're at the second statement?
  4. On your last statement you did correctly (assuming your initial conditions are correct) compute (2+1) < 1 because x has been incremented.

Keep track of the values of x and num after each statement and I think you'll get to the right answer.

Good luck!

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47729

num *= x;
num =2*2 or 4

I don't know where you got that.

num *= x; is equivalent to num = num * x;. If num was 6 (from the previous statement) then it would now be 12 (assuming x is still 2).

Upvotes: 0

Orn Kristjansson
Orn Kristjansson

Reputation: 3485

Yes those are some very basic concepts, do yourself a favour. Download unittest framework something like jUnit would do. Then you can run all these tests quickly with a few asserts that will show you exactly what is going on. Another way to do it without much overhead is just to print it out on the console.

int num = x++ * 3;
System.out.println( "num=" + num );  // num=6

Upvotes: 0

fbernardo
fbernardo

Reputation: 10104

It's incremented before the "break" yes. Basically it's the first thing java does (parenthesis are still the first ones actually). So in (++x < 2) || (++x < 3) the 2nd ++x happens after the first one if it isn't true.

Upvotes: 1

Related Questions