merlin2011
merlin2011

Reputation: 75585

Is there an equivalent of x++ that can be used in an expression for incrementing by values greater than 1?

Apologies for the slightly confusing title.

It is well known that

    int x = 4;
    System.out.println(x++); // prints 4
    x = 4;
    System.out.println(++x); //prints 5

By experimentation, I found that

    int x = 4;
    System.out.println(x+=4); //prints 8

Is there an analog of the above that will increment x but print 4 instead?

Upvotes: 2

Views: 110

Answers (3)

royalhunt
royalhunt

Reputation: 41

++x is pre increment and x++ is post increment

//pre increment
int x = 3;
System.out.println(++x); //prints 4
System.out.println(x); //prints 4

//post increment
int y = 7;
System.out.println(y++); //prints 7
System.out.println(y); // this will print 8 now because of the postincrement

so I think the answer to your question would be the postincrementing of the variable.

Upvotes: 0

Kim Honoridez
Kim Honoridez

Reputation: 997

Try this :

int x = 4;
System.out.println((x+=4)-4); //prints 4

or

int x = 4;
System.out.println((x+=4)-x); //prints 4

however, there's no shortcut operands for that scenario you are referring to. :)

Upvotes: 1

SLaks
SLaks

Reputation: 887857

Like other assignment operators, shorthand assignment returns the final value.
This allows you to write

x = y = z += 4;

There is no post-shorthand operator that returns the original value.

Upvotes: 1

Related Questions