Quick little puzzle-y Java thing - java

Sorry, I couldn't think of a better title.
Anyway, when I compile the following code:
class Example{
public static void main(String[] args) throws Exception {
int x = 3;
x -= 2 + x++ == 4 ? x++ : ++x;
System.out.println("x = " + x);
}
}
I get the answer -2.
Now I would really like to know how it comes to this answer, as I can't find it.
It would be amazing if I could get an answer to this, as this may be on a exam that I'll have somewhat soon.
Note: Of course I wouldn't ever code out something like this myself, this is just an exercise.
Thanks so much if you can help me out!
Edit: answer to fge's answer:
Okay, thanks! but now if I change it up a little and make it like so:
x = 2;
x += 3 + ++x == 6 ? x-- : x--;
System.out.println("x = " + x);
I would think that you would get the following:
++x == 6
is not true, as x is now 3. this means we get x--, making it now 2 again.
then we get 3 + 2 = 5, so the expression can be evaluated to:
x += 5
because x is now 2, we get 2 + 5 = 7.

When you create such code example
int x = 3;
System.out.println(2 + x++ == 4 ? x++ : ++x);
you will see that the output is 5. It is because it is equivalent to
(2 + x++) == 4 ? x++ : ++x
so first Java will evaluate (2+ x++). Since we have x++ value of x will be returned first creating (2+3) and then incremented, so x will be now 4 after it.
Since (2+3) == 4 is false because (5 == 4) we will execute this part ++x, first incrementing x to 5 and then returning it.
Now lets go back to your example
int x = 3;
x -= 2 + x++ == 4 ? x++ : ++x;
You may know that x -= y is in fact x = x - y so it can be written as
x = x - (2 + x++ == 4 ? x++ : ++x);
So, since Java evaluates from left to right it will be
x = 3 - (2 + x++ == 4 ? x++ : ++x);
We know now that (2 + x++ == 4 ? x++ : ++x) is in fact 5 so
x = 3 - 5; // == -2

Related

java expression calculation and operator precedence

i have problem to step by step java expression calculation
System.out.println(++x + x++ * y-- - --y);
I know this precedence:
1. postfix unary
2. prefix unary
3. multiplicative
4. additive
but when i calculate with this precedence the result is below:
// 12 + 11 * 19 - 18
can some one help me
You can understand it from the example given below:
public class Main {
public static void main(String[] args) {
int x = 5, y = 10;
System.out.println(++x + x++ * y-- - --y);// 6 + 6 * 10 - 8 = 58
}
}
Steps in this calculation:
++x = 6
6 + x++ * y-- = 6 + 6 * 10 = 6 + 60 = 66 (after this y will become 9 because of y-- and x will become 7 because of x++ but this increased value of x has never been used in subsequent calculation)
66 - 8 = 58 (before y gets subtracted from 66, it will become 8 because of --y)
Postfix unary is applied after the variable evaluation, opposite to prefix, which is applied before evaluation, your expression can be rewrited:
int x_prefix = x + 1; // ++x
int y_prefix = y - 1; // --y
System.out.println(x_prefix + x * y - y_prefix);
int x = x + 1; // x++
int y = y - 1; // y--
You write operators precedence, it's right but every operator has own behavior, in case of postfix increment, of course has to be evaluate before others, but its behavior is return the current variable and after increment its value.
NOTE: I just rewrited your expression as is, if you use in the same expression the variable postfix incremented, the next access see the variable incremented:
int x = 1;
System.out.println(x++ + x++); // 1 + 2
System.out.println(x) // 3
For completeness:
int x = 1;
System.out.println(++x + ++x); // 2 + 3
System.out.println(x) // 3

Pre and Post Increment and Decrement in Java [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 5 years ago.
Day after tomorrow is my exam for Computers (JAVA) and I have a big problem in the above title. I understood what does post and pre increment and decrement means. But I can no understand what to do when the matter comes to a complex, long statement. One example for such question is below.
class java_1
{
public void main()
{
int x = 4;
x += x++ - --x + x + x--;
}
}
You see what I meant by complex statements. The statement contains only one variable being incremented and decremented again and again, and I get confused over here. Can you please help me clear my confusion. Also, kindly give the answer to the above code.
a += b; is similar to a = a + b. Using this assumption we can rewrite
x += x++ - --x + x + x--;
as
x = x + (x++ - --x + x + x--);
Lets now have x = 4 and evaluate right side (from left to right)
x + (x++ - --x + x + x--)
4 + (x++ - --x + x + x--)
^ //still x = 4
4 + (4 - --x + x + x--)
^ //x++ use current value (4), then increment x to 5
4 + (4 - 4 + x + x--)
^ //--x decremented to 4, then use current value (4)
4 + (4 - 4 + 4 + x--)
^ //still x = 4
4 + (4 - 4 + 4 + 4)
^ //x-- read current value (4), then decrement x to 3
So we are getting
x = 4 + (4 - 4 + 4 + 4);
which means
x = 12;

Java operators, explanation [duplicate]

This question already has an answer here:
How are java increment statements evaluated in complex expressions
(1 answer)
Closed 8 years ago.
I know there are several question about the x++ operation, I know the difference between ++x and x++. But now I have to solve this:
int x = 5;
x += x++ * x++ * x++;
Well I know that this shouldn't be too difficult, but still, I need an explanation how this calculatino is done, step by step, I don't get it by myself..
Your code is equivalent to:
int x = 5;
int originalX = x;
int a = x++;
int b = x++;
int c = x++;
x = originalX + a * b * c;
System.out.println("x = " + x); //215
x += x++ * x++ * x++;
can be written as:
x = x+ x++ * x++ * x++;
how will it be evaluated?
x= 5+(5 * 6 * 7) because you are using postfix. So, the incremented value of x will be visible from the second time it is used.
So, final output = 5+ (5*6*7) == 215
x++ would mean read the value and use it in the place which is referenced and then increment it.
So in your question:-
int x = 5;
x = 5 + 5 * 6 * 7
x += x++ * x++ * x++;
x = 215
int x = 5;
x += x++ * x++ * x++;
First, set some brackets to better see the calculation sequence:
x += ((x++ * x++) * x++);
Then, replace the first occurance of x with it's value, calculate, and continiue replacing with updated values:
5 += ((x++ * x++) * x++);
5 += ((5 * x++) * x++);
5 += ((5 * 6) * x++);
5 += ((5 * 6) * 7);
5 += 210;
and now, it's plain math...
Result should be: 215
And my compile gives me: 215
So I think my explanation is correct. But i'm not 100% sure...

How does the following statement work?

int x = 10;
x += x++;
System.out.println(x);
why the answer of above statement is 20 ?
The operator += is an addition assignment operator. Like Alya said above, x += x++ is equivalent to x = x + x++, which in your case is x = 10 + 10. However, it's a very messy statement and I'll explain why towards the end of this post.
Now, you're probably thinking "Why is it 20 and not 21 (10 + 11) since you have the ++?" and that's valid. There's actually a difference between a post-increment and a pre-increment. x++ is the post-increment and will actually evaluate the value of x first and THEN increment x, while ++x is the pre-increment which will increment x and THEN evaluate the value of x.
For example, x = 10; System.out.println(x++); System.out.println(x); will print 10 and then print 11 because the first print line prints x and THEN performs the ++ calculation, making x 11 which the next line prints. Conversely, x = 10; System.out.println(++x); System.out.println(x); will print 11 on both print statements.
Going back to why I said x += x++; is very messy is because technically the ++ operator isn't performed in this case. x++ is technically the same as x=x+1 and remembering that x+=y is the same as x = x+y) , the line x += x++; is kind of like saying x = x + (x = x + 1); which is kind of weird looking because you do 2 assignment statements in one and won't actually "work how you want it". Back to your example int x = 10; x += x++; if you print x, you will get 20 even though you could look at it as: x is now the value of x + the value of x, then finally + 1 to it. But unfortunately, that's not how it works.
To solve your problem, if you change your code from a post-increment to a pre-increment, then it should work, ie: x+=++x; will print your 11 but I would argue the that's quite unreadable and a bit confusing. x+=x; x++; System.out.println(x); is easier to follow.
x++ will execute first. It returns x and then increments x by 1.
Finally, the += operator will add to x the return value of x++, which was 10.
Thus, x will be 20 and it will overwrite the changes to x by the statement x++.
So first x is initialized to be 10. Then the x++ has higher precedence so that gets carried out first. the "++" is a post-increment in this case (because it is after the variable as opposed to pre-increment which would be ++x). Post-increment means "first use the variable then increment it by one" so in this case it first uses x to be 10 then increments it to 11 after it is used. Then we look at the "+=" which is short hand for "x = x+x++". so we have x = 10+10 which = 20. If you were to carry this out again it would equal x = 20+20 = 40.
In this particular case, the x++ isn't necessary as x is reassigned the value after it is incremented each time.
int x = 10; x += x++;
will equal to x=x+x
where x++ mean use the x value then increament it , so it's value will be 10
so the result will equal 20
if you want to see the change of the x , see this example:
int x = 10;
int y = 10;
y +=x++;
System.out.println(y);
System.out.println(x);
will print :
y=20
x=11////////////according to x++ and without to overwrite it
//
// Shows how increments work.
//
int i = 0;
System.out.println(i);
i++; // Add one
System.out.println(i);
i += 2; // Add two
System.out.println(i);
i += 3; // Add three
System.out.println(i);
++i; // Add one
System.out.println(i);
i += i; // Added itself
System.out.println(i);
//
// Uses increments and assigns.
//
int v = 0;
v = i++; // Increment after value copy
System.out.println(v);
System.out.println(i);
v = ++i; // Increment before value copy
System.out.println(v);
System.out.println(i);
//Output
0 -
1
3
6
7
14
14
15
16
16
x+=x++ first assigns the value to x and then increments (post-increment)
x+=++x first increments then assign the value to x (pre increment)
there are two types of increments/decrements in programming
1. pre-increment/decrement
2. post-increment/decrement
In programming both of these have same operations but differ in there nature as they both used for increment or decrement; they can be written as,
x+=1; (increment by 1)
x-=1; (decrement by 1)
you can use a variable instead in the above cases as well

Increment X Mod N in One Line

I have several small programs that require infinitely looping over the integer set Z sub n. I often write the code in this manor:
int x = 0;
int n = 13; //or some other prime
while(1) {
//do stuff dependent on x
++x;
x %= n;
}
I write code mostly in C/C++ & Java so I was wondering:
Is there a way to increment x mod n in one line rather then two in either language?
Have you considered:
x = (x + 1 == n ? 0: x + 1);
The chances are the x + 1 will optimise to one instruction and at least you are guaranteed to never use division (which a bad optimiser might use when % is involved).
x = (x + 1) % n;
Not terribly surprising.
Another alternative is this
x = ++x % n; // Java
if (++x == n) x = 0;
Using x = (x + 1 == n ? 0 : x + 1); requires two additions: one for the comparison and another when the value of x is set to x + 1.

Categories