(Note: I came across this somewhat accidentally, so it may not be practical, but I am just very curious)
I wanted to print out a value, which was the sum of two values, after incrementing the second. Something like so:
int first = 10;
int second = 20;
System.out.println(first + ++second);  //31
System.out.println(first);             //10
System.out.println(second);            //21
Maybe not the neatest code, but it worked. But then, I started experimenting.
System.out.println(first +++ second);  //30
System.out.println(first);             //11
System.out.println(second);            //21
That's fine; it means that the first was incremented after being added, and that whitespace can be ignored here. Cool. But then...
System.out.println(first +++++ second);  //"Invalid Argument", doesn't work
While
System.out.println(first ++ + ++ second);  //31
System.out.println(first);             //11
System.out.println(second);            //21
Works fine, but for some reason, is still different than
System.out.println(first + + + ++ second);  //31
System.out.println(first);             //10
System.out.println(second);            //21
And maybe the strangest of all,
System.out.println(first + + + + + + second);  //30
System.out.println(first);             //10
System.out.println(second);            //20
So what's going on here? When is whitespace between operators ignored, and when is it not? Why can I write "+ + + + +", without any issues?
Thanks!
This comes down to operator precedence. The order of operations goes:
foo++, foo--)++foo, --foo,  +expr, ...)+, -)So, let's take a look at each expression:
first + ++second is first + (++second). That's fine.
first +++ second is (first++) + second, which works as you said it does.
first +++++ second is ((first ++)++)+ second), but (first ++) is a value (not a variable) and thus can't be incremented -- that's what the error is trying to tell you.
first ++ + ++ second explicitly tells Java to split things up differently than above: it becomes (first ++) + (++ second), which is fine.
first + + + + + + second becomes first + (+ (+ (+ (+ (+ second))))). The unary + just means "not negated", so +foo == foo. Therefore this expression simplifies to first + second, which is obviously fine.
I don't want to close it as a duplicate since it's a different language but I believe it to be the same reason as layed out here.
It's simply a matter of parsing and these bullets should help you figure it out:
+ bear no extra meaning and only one will be appliedCode: first +++ second
Parsed: first++ + second
Code: first +++++ second
Parsed: There is no binary operator ++ since it will try to make ++ ++ +
Code: first ++ + ++ second
Parsed: first++ + ++second
Code: first + + + ++ second
Parsed: first + ++second
Code: first + + + + + + second
Parsed: first + second
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With