Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment operator in java

Tags:

java

increment

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?

like image 992
Jack Pettersson Avatar asked Oct 27 '25 03:10

Jack Pettersson


2 Answers

++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:

  1. x = ++x; is redundant as ++x; by itself already accomplishes the same thing.
  2. ++1 makes no sense as you can't change the value of 1 - it is a constant.
like image 113
sepp2k Avatar answered Oct 28 '25 17:10

sepp2k


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.

like image 21
Greg Hewgill Avatar answered Oct 28 '25 17:10

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!