Friday 15 December 2017

How are java increment statements evaluated in complex expressions

itemprop="text">

What is the output of the following
code:



int x = 2; 
x +=
x++ * x++ * x++;
System.out.println(x);



I understand that
++variableName is pre-increment operator and the value of
variableName is incremented before it is used in the expression
whereas variableName++ increments its value after the
expression is executed. What I want to know is - how does this logic apply
here?



itemprop="text">
class="normal">Answer



Its easier
to see the what is going on with x = 1 instead of 2. The output for
x=1 is 7.



The key to
the understanding of this is in JLS href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7.2"
rel="nofollow noreferrer">15.7.2 which states that the every operand is
fully evaluated before any part of the operation is
performed.




The
Java programming language guarantees that every operand of an operator (except the
conditional operators &&, ||, and ? :) appears to be fully evaluated before any
part of the operation itself is
performed.




Thus,
x++ (each of 3 times, left to right with appropriate precedence which isn't an issue
here) is evaluated, then the operation * is evaluated and assigned to the original
value.




x = 1 + (1 * 2 *
3)


If x starts out
with 2, you get:



x = 2 + (2 * 3 *
4)


Unlike in C, this
is well defined in Java and will behave the same on each invocation in any
runtime.




Associated
ideone if anyone wants to run it for themselves: rel="nofollow noreferrer">https://ideone.com/Y2qcJ6


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...