r/AskComputerScience • u/SaltySkeletor18 • Mar 11 '20
We've had quite a bit of debate inside my (Java) class on this problem. The debugger says line 7 is like a = 4 + 3 then it increments it be 1 before it assigns it however by that logic wouldn't the output be "-1"?
3
Mar 11 '20
You should have a look at the Java bytecode for this class. It will shed some light on the order of what is happening. Pseudo bytecode below, just a guess though.
; ++a
inc a
push a
; a++
push a
inc a
; ++a + a++
add
; a =
store a4
u/Mukhasim Mar 11 '20
Here's the output I get from javap.
$ javap -c Addit.class Compiled from "Addit.java" public class Addit { public Addit(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_3 1: istore_1 2: iconst_2 3: istore_2 4: iinc 1, 1 7: iload_1 8: iload_1 9: iinc 1, 1 12: iadd 13: istore_1 14: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 17: iload_1 18: invokevirtual #3 // Method java/io/PrintStream.println:(I)V 21: iinc 1, -1 24: iload_1 25: iload_1 26: iinc 1, -1 29: isub 30: istore_1 31: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 34: iload_1 35: invokevirtual #3 // Method java/io/PrintStream.println:(I)V 38: return }5
Mar 11 '20
Cheers, I've commented a snippet of it below.
; push 3 on the stack 0: iconst_3 ; store 3 into variable 1 (a) 1: istore_1 ; ditto 2 -> b 2: iconst_2 3: istore_2 ; increment variable 1 by 1 4: iinc 1, 1 ; load variable 1 onto the stack 7: iload_1 ; load variable 1 onto the stack 8: iload_1 ; increment variable 1 by 1 9: iinc 1, 1 ; pop the 2 values off the stack, add them, store the result 12: iadd ; take the result off the stack and store it in variable 1 (a) 13: istore_1 ; invoke System.out.println 14: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 17: iload_1 18: invokevirtual #3 // Method java/io/PrintStream.println:(I)V2
2
u/proskillz Mar 12 '20
What do you do that you would need to know how to read java bytecode? Hmm. Maybe I need to up my game on low level java.
3
Mar 12 '20
Program analysis, reverse engineering, security audits, hacking. Most (all?) of the Java decompilers are outdated, many of the RE tools have some subset of useful features but not all. A lot of times it is easier to just look at the bytecode.
I also have a fascination with Jazelle and hope to one day reverse engineer enough of it to present at a conference. The spec is not available. The short of it, is they took Java bytecode (usually interpreted by a program, the JVM) and made it work native on old ARM chips. Like fucking what?! Native Java bytecode???
Anyway, it is a stack based language. Pretty easy to understand and not a very complex instruction set. If you're interested in learning a stack based "low level" language, check out WASM though. It is much more modern and will probably be more profitable in the future. The search "wasm by hand" will bring up a few cool projects.
1
u/WikiTextBot Mar 12 '20
Jazelle
Jazelle DBX (direct bytecode execution) is an extension that allows some ARM processors to execute Java bytecode in hardware as a third execution state alongside the existing ARM and Thumb modes. Jazelle functionality was specified in the ARMv5TEJ architecture and the first processor with Jazelle technology was the ARM926EJ-S. Jazelle is denoted by a "J" appended to the CPU name, except for post-v5 cores where it is required (albeit only in trivial form) for architecture conformance.
Jazelle RCT (Runtime Compilation Target) is a different technology and is based on ThumbEE mode and supports ahead-of-time (AOT) and just-in-time (JIT) compilation with Java and other execution environments.
The most prominent use of Jazelle DBX is by manufacturers of mobile phones to increase the execution speed of Java ME games and applications.
Java bytecode instruction listings
This is a list of the instructions that make up the Java bytecode, an abstract machine language that is ultimately executed by the Java virtual machine. The Java bytecode is generated from languages running on the Java Platform, most notably the Java programming language.
Note that any referenced "value" refers to a 32-bit int as per the Java instruction set.
[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source ] Downvote to remove | v0.28
1
2
Mar 11 '20
Remember that ints are value types and not reference types.
So, the order of what happens here is this:
a is assigned the value of 3.
value-of-a is incremented (prefix unary operation occurs before the value is taken) to 4
value-of-a (4) is added to value-of-a (4, remember that postfix unary operation happens after the value is read) to render 8
the second value-of-a (4) is decremented to 3, but this is lost since the value has already been read
a is assigned the value of 8.
(Step 4 above may actually be optimized out since it has no effect, and it may happen after step 5.)
The order is the same in the second assignment:
value-of-a is decremented to 7
value-of-a (7) is subtracted from value-of-a (7) to render 0.
the second value-of-a (7) is decremented to 6, but this value is lost (see step 4 above)
a is assigned the value of 0.
Finally: never, ever write code like this.
4
4
u/sepp2k Mar 11 '20
Remember that ints are value types and not reference types.
The behavior doesn't change if you replace
intwithInteger(which is a reference type) in OP's code.It also doesn't change if you create your own mutable reference type with methods like
postInc(),preInc()etc.3. value-of-a (4) is added to value-of-a (4, remember that postfix unary operation happens after the value is read) to render 8
4. the second value-of-a (4) is decremented to 3, but this is lost since the value has already been read
The side-effect of
a++is executed before the addition is evaluated, not after.You can see the difference if we make
a++evaluate to 0 and replace the addition with a division (which throws an exception if the right operand is 0):class Bla { public static void main(String[] args) { int a = -1; try { a = ++a / a++; } catch (Exception e) { e.printStackTrace(); } System.out.println(a); } }As you can see the value of
awill be 1 afterwards, meaning the side-effect ofa++was executed before the division (otherwise the exception would have prevented it from executing andawould have been0).2
Mar 11 '20
If this is the behavior of the postfix operator
a++ sets the value of a to 5 and evaluates to 4
then a++ should evaluate to 0 when used in the expression in your code.
I don't have a Java compiler handy, but I entered your class in four different online Java compilers and all of them threw "java.lang.ArithmeticException: / by zero".
I think you're confused about your example here, and you're making a distinction without a difference (i.e., saying the side effect is executed before evaluation and not after, when the end result is exactly the same in each of the cases presented).
3
u/sepp2k Mar 11 '20
then a++ should evaluate to 0 when used in the expression in your code.
Yes,
a++evaluates to 0 either way. What I'm saying is that the value ofaafterwards will be 1.If
awere only incremented after the division, thenawould still be 0 at the end because the division never finishes (it throws an exception).Maybe this doesn't convince you because you think that the increment could just happen after the exception is being thrown (but before it's caught), so let's look at another type of expression instead:
f(x++);. Would you say thatxwill be increased afterfis called or beforefis called? If you think it's increased after the call, the following code should serve as a counter-example:class Bla { static int x = 0; static void f(int arg) { System.out.println("f was called with the argument " + arg + " and the value of x is " + x); } public static void main(String[] args) { f(x++); } }The result can be seen here. As you can see the value of
xcan already be observed to be 1 whilefis running, so the increment must have happened before the method call, not after.0
Mar 11 '20
Maybe this doesn't convince you because
No, it didn't convince me because your previous example didn't work out the way you claimed it would. Particularly this part:
As you can see the value of a will be 1 afterwards, meaning the side-effect of a++ was executed before the division (otherwise the exception would have prevented it from executing and a would have been 0).
The "otherwise" part happened. Furthermore, your example code threw an error exactly as it would have had the a++ increment happened after the evaluation--which is what I was claiming originally.
Your second example is even more specious. at the moment the function is called, x is evaluated as 0, which, in the function body, is assigned to the variable arg. On the SECOND evaluation of x, it's value is 1, which indicates that the increment happened
afterbetween the first and second evaluations. And by "happened" I mean, "has any noticeable effect on the code".3
u/sepp2k Mar 11 '20
The "otherwise" part happened.
No, it didn't. The code prints 1, not 0.
your example code threw an error
Which I said it would. The question was never whether the exception would be thrown. The question was whether
awould be1or0after the exception. And it was1.On the SECOND evaluation of x, it's value is 1, which indicates that the increment happened after between the first and second evaluations
The fact that it happened at all was my point. The exception didn't prevent it from happening, so it must have happened before the exception, and thus before the division.
0
Mar 11 '20 edited Mar 11 '20
Are you really so disingenuous to not understand that my quote was referring to your FIRST example (the one with the try/catch) and not the second one?
Forget it. If you're going to start arguing in bad faith, then this discussion ends.
EDIT: My bad. I overlooked the final print at the end. It does print 1. This doesn't change my understanding that postfix unary operation happens in evaluate-then-increment order (or decrement). What's the difference?
3
u/sepp2k Mar 11 '20
Are you really so disingenuous to not understand that my quote was referring to your FIRST example (the one with the try/catch) and not the second one?
What? No. You were referring to the first example and so was I. What makes you think I was referring to the second one (or that I thought/pretended to think that you were)? The second one doesn't even contain an exception.
1
Mar 11 '20
I apologize. I didn't notice the "1" printed in the output after the first example, and was trying to make sense of everything you wrote in that mistaken context.
The exception didn't prevent it from happening, so it must have happened before the exception, and thus before the division.
So here's my quibble: when you say that the increment happens before the division, to me that entails that the *assignment* of the incremented value back to the variable ALSO happens before the division.
But apparently you're saying that
the incremented value is stored (somewhere?)
the variable is evaluated at its original value,
the division happens with the variable's original value,
and THEN the stored value is assigned to the variable.
It's just simpler for me to think evaluate-then-increment:
the variable is evaluated at its original value, which is stored (somewhere?)
the variable is incremented
the stored value is used in the division
There's nothing in any of your examples (or any example I can think of) to distinguish between these two accounts.
2
u/sepp2k Mar 11 '20
It's just simpler for me to think evaluate-then-increment:
the variable is evaluated at its original value, which is stored (somewhere?)
the variable is incremented
the stored value is used in the division
That's perfectly fine by me. But the way you wrote it in your first post, you had the increment after the addition. I.e. you had the addition in step 3 and the increment in step 4.
1
u/sepp2k Mar 11 '20
This doesn't change my understanding that postfix unary operation happens in evaluate-then-increment order (or decrement). What's the difference?
My objection wasn't that you said that the increment happens after the evaluation of
x++(that's not the way the standard defines it, but you're right that that's a distinction without a difference).My objection was that you said the increment happens after the addition, i.e. after the evaluation of
4 + 4.2
Mar 11 '20
Fair enough. What I meant to indicate was that the value used in the addition was the pre-increment value. I now understand that the way I expressed it suggested consequences I did not intend.
0
u/MirrorLake Mar 11 '20 edited Mar 11 '20
For any some languages, questions like these are resolved by referring to the language's operator precedence. It's a much longer version of "PEMDAS" order of operations that you might have learned in algebra, but the same idea applies.
3
u/sepp2k Mar 11 '20
Not really. Precedence doesn't tell you whether the left operand is evaluated before the right. Neither does associativity - left-to-right associativity does not imply left-to-right evaluation (note that all operators are evaluated left-to-right in Java, even if the associativity is right-to-left).
Precedence also doesn't tell you in what order side-effects happen, nor does it explain the difference in semantic between
++xandx++.So precedence and associativity aren't sufficient in explaining the behavior of OP's code (nor are they particularly helpful as the precedence of
a = ++a + a++is the one part that's pretty obvious).Case in point: In C the involved operators have the same precedence and associativity as in Java, but the behavior is still different (undefined).
1
u/MirrorLake Mar 11 '20
My link has information about associativity as well, though. You can absolutely figure out the correct answer from it. I feel like I got thrown under the bus here.
3
u/sepp2k Mar 11 '20
My link has information about associativity
As I said, associativity is also irrelevant because it does not affect evaluation order. The article you linked also mentions that evaluation order always goes left-to-right, though. I admit I didn't fully read the article when I wrote my earlier reply - I just responded to your claim that "questions like these are resolved by referring to the language's operator precedence".
1
u/MirrorLake Mar 11 '20
It's not an article, it's a page from a Java textbook. It seems the main point of confusion for professionals and students alike is the post-decrement/increment operator does not do what people assume it does in Java. I was more or less trying to remind any students here that every textbook/language standard has a table devoted to helping you navigate these operator questions.
-3
u/SafeForWorkLife Mar 11 '20
So a problem like this is not solvable, unfortunately. General concepts and rules are broken by doing this. Different languages and compilers will interpret and execute this differently. Even different versions of the same compiler might handle this different.
Some people can trace to an answer, but without the answer probably would come up with the wrong one. The problem lies with order of operations across multiple assignments are not really defined anywhere. I am although not a Java expert, but I have come across this problem before.
8
u/sepp2k Mar 11 '20
The problem lies with order of operations across multiple assignments are not really defined anywhere.
The Java spec very much does define it, it's only undefined in other languages like C and C++. All Java compiler versions are guaranteed to produce the same result that OP got - otherwise they're not conforming.
175
u/sepp2k Mar 11 '20 edited Mar 11 '20
Here are the things you need to know:
++aincrementsaand evaluates to the incremented valuea++also incrementsa, but evaluates to the unincremented valueThe operands of an operator are evaluated left-to-right
When a sub-expression is evaluated, all of its side-effects will have taken effect before the evaluation of the outer expression continues
In an assignment expression, the assignment happens after the evaluation of the assigned expression
So on line 7 the following things will happen in the following order:
a = ++a + a++starts being evaluated++a + a++starts being evaluated++asets the value ofato4and evaluates to4a++sets the value ofato5and evaluates to4++a + a++is now4 + 4and evaluates to8a = ++a + a++is nowa = 8and setsato8Then on line 9:
a = --a - a--starts being evaluated--a - a--starts being evaluated--asets the value ofato7and evaluates to7a--sets the value ofato6and evaluates to7--a - a--is now7 - 7and evaluates to0a = --a - a--is nowa = 0and setsato0PS: All of this applies to Java and many other languages, but there are notable languages where the rules are different and the equivalent code would behave different or have no defined behavior at all (in C and C++ it's undefined behavior).