Java Garage

     

Incrementing and Decrementing Operators

This is the kind of thing you need to do with some frequency, especially within loops . Java makes incrementing and decrementing a variable by 1 easy with these special operators:

x = 0; x++; //x is 1

You can subtract the same way:

y = 10; y--;

The preceding operators are called post-increment and post-decrement, because they add or subtract 1 after the variable has been evaluated.

FRIDGE

You may only use these operators with variables ”not with literals. That is, you can't do this: 10++; . That's illegal! You can't do this either: String x -= "something";. No funny stuff, now.

You can also use these operators for pre-incrementing and pre-decrementing, which adds or subtracts 1 before the variable has been evaluated. Like this:

--x; ++y;

Here is a class you can compile and run to demonstrate these operators:

OperatorTest.java

public class OperatorTest { public static void main(String[] args) { int x = 10; //evaluate, then increment System.out.println("post decrement: " + x++); //prints 10 System.out.println(x); //x is now 11 //decrement, then evaluate System.out.println("pre decrement : " + x); //prints 10 } }

Категории