Confusion rose because of this post. The author updated his post, and the result became clear.
Conclusion: Java evaluates expressions from left to right
Closed!
As evaluation of expression is done from right to left the following code should store 5 in j:
int i=2;
int j=++i+i++;
System.out.println(j);
But I get 6 as the output, which forces me to re-think the right to left evaluation idea. Kindly explain the theory here.
You get 6 because it's 3 + 3:
the first OP is ++i which increments first (to 3) then that value is used
next OP is +i which adds 3 again
last OP ++ doesn't take part in the addition, but it increments i after using it
Your assumption is false. Here's what the documentation says :
All binary operators except for the assignment operators are evaluated
from left to right
So
++i+i++
is equivalent to
(++i)+(i++)
where ++i is evaluated first.
This gives
3+3
which is 6 (and i has value 4 after this).
int i = 2;
int j = ++i + i++;
is the same as
int i = 2;
// This part is from ++i
i = i + 1;
int left = i; // 3
// This part is from i++
int right = i; // 3
i = i + 1;
int j = left + right; // 3 + 3 = 6
If instead you'd done:
int i = 2;
int j = i++ + ++i;
that would be equivalent to:
int i = 2;
// This part is from i++
int left = i; // 2
i = i + 1;
// This part is from ++i
i = i + 1;
int right = i; // 4
int j = left + right; // 2 + 4 = 6
So the sum is the same, but the terms being summed are different.
The first ++ increments i. The + adds i to itself. i is 3.
Where'd you get the idea that it is right-to-left? It is left-to-right.
What are the rules for evaluation order in Java?
This how it works, since unary operators have more precedance than binary:
int i=2;
int j =(++i)+(i++);
^^^ ^^^
3 +(i++) //The value of i is now 3.
^^^ ^^^
3 + 3 //The value of i is incremented after it is assigned.
When evaluating an expression such as a+b, before you can add 'b' to 'a', you need to know what 'a' is. In this case, a is ++i, which is 3, and b is i++ which is 3. Evaluating right-to-left gives 3 + 3 = 6
In Java and C#, the evaluation of subexpressions will be done left to right:
int j=++i + i++;
contains the following two subexpressions ++i and i++. These subexpressions will be evaluated in this order so this will translate into:
int j= 3 + 3;
As in Java and C#, the ++i will be executed returning 3 but i will be changed to 3 before the second i++. The second will return the current value of i which is 3 now and after i++ the value of i will be 4.
In C++ this would be undefined.
And in real-world, you do not want to type this code (except for code golfing)
Related
This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 3 years ago.
I got these 2 different codes in Java that I can't understand how they produce these specific outputs.
They seemed to work in 2 different logic and I can't figure it out!
int a = 5;
int b = 4;
a -= (b++) + ++a; // For more confusing results replace -= with += and see how the logic changes.
System.out.println(a); // Output: -5
and
int c = 8;
c += ++c;
System.out.println(++c); // Output: 18
How does each situation work and how are they producing these specific outputs?
The major difference here is what post and pre increment are. These determine whether the value is increased before evaluation, or afterward.
Here is how the first case breaks down mathematically:
a = 5 - (4 + 6), which reduces to -5.
Note that a is increased from ++a AKA preincrement before the math is done, however b is calculated as 4. Another thing to note is the a used from the -= uses the original a value, regardless of post or pre increment.
The second equation reduces to this mathematically:
c = 8 + 9 which reduces to 17.
The output prints 18 because your System.out.print(++c) increments it one more time before output due it being preincrement. Note if the print statement used c++, the value would print to 17.
The chart for operator precedence can be found here. Note that assignment has lower precedence than the unary/postfix operators.
It's all about the Operator Precedence in Java. Check that table and figure out which operation takes place first and which last.
It is equivalent to:
int a = 5;
int b = 4;
a -= (b++) + ++a; // => 5 -= (4) + 6
int c = 8;
c += ++c; // => 9 += 9
The main diff is thet:
++a and ++c increments the value and immediately returns it.
b++ returns the value and then increments it.
There is a difference in the order of ++. While both increase the variable, ++a will pass the original value to the operation chain your in middle of; while a++ would pass the new value. So for your first example:
++a --> a is now 6; but the equation is using 5:
a -= (b++) + 5;
b++ --> b is now 5;
a -= 5 + 5;
a -= 10;
? = 5 - 10;
a = a - 5 + 5;
a = 5 - 5 + 5;
a = -10;
(You should have enough to trace the second example).
For a list of operations try this. Some more increment examples are here.
A minimal example is `
int x=3,y=3;
x += ++x;
y+= y++;
at the x x is 7 and y is 6. Precedence alone is not enough to explain the behaviour. Using precedence the second line would be x += (++x), i.e. increment x and return its value, (x is now 4); next we have x+=4 which would return 8.
Instead, it seems better to treat x += w as a short hand for x = x + w, this rewriting happens before evaluation. In our case the rewriting is x = x + ++x interpreted as x = (x + (++x)). So interpreted as
x = ( 3 + (++x))
x = ( 3 + 4 ) x is 4
x = 7 x is 7
A simlar system works to the y equation giving y = 6 at the end.
I am trying to make a program that takes all the combinations of a dice (got that part done) but now I am trying to take all the combinations and put them in an array by there total ( (1,1) = 2, (2,4) = 6 ) and I will eventually implement it into a game. But when trying to organize them I created an infinite loop that does not seem like it should be running infinitely.
for (int dice1 = 1; dice1 < 7; dice1++)
for (int dice2 = 1; dice2 < 7; dice2++)
for (int j = 0; j < 6;)
{
msg = "";
msg = "(" +dice1 + ", " + dice2 + ")";
arrayDice[dice1 - 1][dice2 - 1] = msg;
add = dice1 + dice2 - 2;
arrayAdd[add][j] = msg;
if (add == 10 - j)
j = j + 1;
}
the arrayDice is just the array of all combinations while the arrayAdd is all the added combinations. I really can't find where the problem is coming from.
Third for loop in your program is the one that is running infinitely. In the third loop, you are not incrementing the counter 'j' within the for statement but you increment it within the body of the loop. However, the only place in the body of the third loop where the counter 'j' is increasing is within an if statement - if (add == 10 - j). Since you start this loop with j=0, the expression 10 - 0 = 10 for the first iteration while the variable 'add' is 1 + 1 -2 = 0. So this expression if (add == 10 - j) evaluates to false. So j never gets incremented. The only other variable in this expression is 'add' which doesn't get changed until you come out of the third loop. So in short the expression if (add == 10 - j) never evaluates to true and hence j is never incremented resulting in the third loop running infinitely.
I'm trying to figure out what constitutes an instruction in java code. In class lecture that I attended professor mentioned 7 things that can be constituted as instruction but. I am having trouble making out what.
assignment, access of array, return statement, addition multiplication subtraction,..
Here is a example code she gave out:
int sum = 0;
int i = 0;
while ( i < 3 ) {
sum += A[ i ];
i++;
}
she says there are total of 18 instructions in this java code but I only count 15. Could you guys clarify why this is.
I believe something is missed in the explanation what count as instruction
Taking this schema there would be twenty.
1) int sum = 0; // 1 assignment
2) int i = 0; // 1 assignment
3) while ( i < 3 ) { // 1 comparison
4) sum += A[ i ]; // 1 array access, 1 addition, 1 assignment --> sum = sum + A[i]
5) i++; // 1 addition, 1 assignment --> i = i + 1;
6) }
The lines 3-5 are executed three times.
Can anyone explain me how different spacing affects the unary operator?
int i = 1;
int j = i+ + +i; // this will print j=2
int k = i++ +i; // this will print k=3
int l = i+++i; // this will print l=3
int m = i++++i; // compile time error
.
First, let's separate this into three separate cases which can't interact:
int i = 1;
System.out.println(i+ + +i); // 2
int j = 1;
System.out.println(j++ +j); // 3
int k = 1;
System.out.println(k+++k); // 3
Now let's rewrite them using brackets:
int i = 1;
System.out.println(i + (+(+i)));
int j = 1;
System.out.println((j++) + j);
int k = 1;
System.out.println((k++) + k);
First operation
Here we can't be using the prefix or postfix ++ operators, as we don't have a token of ++ anywhere. Instead, we have a binary + operator and two unary + operators.
Second operation
This one's simple: it's pretty much as it reads, a postfix ++ operator followed by a binary + operator (not the unary + operator that +j might otherwise imply).
Third operation
The final line is parsed as (k++) + k rather than k + (++k). Both will actually give the same answer in this situation, but we can prove which is which by using two different variables instead:
int k1 = 1;
int k2 = 1;
System.out.println(k1+++k2); // Prints 2
System.out.println(k1); // Prints 2
System.out.println(k2); // Prints 1
As you can see, it's k1 that's been incremented rather than k2.
The reason that k+++k is parsed as tokens of k, ++, +, k is due to section 3.2 of the JLS, which includes:
The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would.
Fourth operation (compile failure)
The same "longest possible translation" rule parses i++++i as i, ++ ,++, i which isn't a valid expression (because the result of the ++ operation is a value, not a variable).
+ is an operator, and ++ is an operator, but + + is not - + + is interpreted as two +s, not one ++. So the space forces your code to be interpreted differently.
+ is both a binary operator which adds two numbers and a unary operator which does not change a number (it exists only for consistency with the unary - operator).
If we use add instead of binary +, no-change instead of unary +, and increment instead of ++ then it might be more clear.
int j=i+ + +i becomes int j = i add no-change no-change i;.
int k=i++ +i; becomes int k=i increment add i;.
I suspect int k = i+++i; also becomes int k = i increment add i; but I have not checked this with the language specification.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Freebase query example in python:
I know that I'm dyslexic and I don't have a PhD but I always find Google APIs incomprehensible. I just need an example on the following: Get the '/music/genre' list and then get the subgenres ...
could anyone explain difference between operators in this program
int i=10;j=10;
int n=i++%5;
int k=++j%5;
when i try this program iam getting n=0 ,k=1 and i=11,j=11
and ++a and a++ operator with other operators.
thank you in advance.
i++ means "use the value of i then increment it"
++i means "increment the value of i then use it"
i%5 means "the remainder after dividing i by 5"
i++ and ++i are called increments and both are equivalent to i = i + 1 but differ in when the variable is incremented.
int i = 0;
System.out.println(i++); //This prints 0 then increments i to 1
System.out.println(++i); //This prints 2 because i is
//incremented by 1 and then printed
% is the modulus operator and provides the remainder of a division problem.
6 % 4 = 2 //This is the same as saying 6 divided by 4,
//but prints the remainder which is 2
For you specific problem:
int i=10;
int n=i++%5; //Here you have 10 % 5 which is 0, so n = 0.
//After that i is incremented to 11.
++ is called the increment operator, they increase the variable value by 1.
When used in any expression, ++i will first increment the value of i by one and then use the incremented value in expression.
On other hand when i++ is used in any expression, exp is evaluated with the initial value of i, and after that value of i is incremented by one.
int n=i++%5;
is equivalent to
int n=i%5; // i=10, n = 10%5 = 0;
i = i +1; //i = 10 + 1 = 11
And int k = ++j%5;
is equivalent to
j = j + 1; // j = 10 + 1 = 11
int k = j % 5; // k = 11 % 5 = 1
Hope this will be helpful.