Incrementing and Decrementing Operators

     

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.

graphics/fridge_icon.jpg

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 } } 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net