Just started learning java, so sorry asking such an arbitrary and silly thing... But i can't wrap my head around the increment operators in java.
Why does this work:
int a = 5;
int a = ++a;
System.out.println(a);
>>6
When this doesn't:
int a = ++5;
System.out.println(a);
>>Compilation error: Found value - Required variable.
Shouldn't this operator work like any other arithmetic operator? Why does this one in particular need a variable? I mean a = 5+1; works, so why doesn't a = ++5?
Is there any way to use ++ directly with values?
++x is not a shortcut for x + 1, it's a shortcut for x += 1. That is, in addition to evaluating to x+1, it also increments the value of x by one. This means two things:
x = ++x; is redundant as ++x; by itself already accomplishes the same thing.++1 makes no sense as you can't change the value of 1 - it is a constant.The answer is that ++x changes the value of x, as well as providing an expression result. You can't change the value of 5, if you were to try to use ++5.
If you want a value that is "one more than x", and you don't need to change the value actually stored in x, then the usual way to do this is of course x + 1.
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