Reputation: 1939
What does each expression evaluate to? Assume x is 2 before each one.
int num = x++ * 3;
So this would be equivalent to (2)*3 or num=6 and x is now 3.
num *= x;
num =2*2 or 4
(x < 2) && (x > 1)
Becomes FALSE, because (2<2)=false and (2>1)=true so it's false.
(++x < 2) || (x < 1)
(3<2)
is false and then ((2+1)<1)
is also false, so it's false?
One question is in this case, is the preincrement applied to the variable before the break? Should the second x value be 3 or 2?
I also have the same question for postincrement. Let's say I have num=x++ *x++
where initial x=2. So is this 2*2 or 2*3?
Upvotes: 1
Views: 347
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
Reputation: 2181
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.a *= b
?num
when you're at the second statement?(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
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
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
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