Tuesday, July 3, 2012

JAVA Basics 7:Java Increment and Decrement Operators


There are 2 Increment or decrement operators ->  ++ and --. These two operators are unique in that they can be written both before the operand they are applied to, called prefix increment/decrement, or after, called postfix increment/decrement.  The meaning is different in each case.
Example
x = 1;
y = ++x;
System.out.println(y);

prints 2, but

x = 1;
y = x++;
System.out.println(y);

prints 1
Source Code
//Count to ten

class UptoTen  {

  public static void main (String args[]) {
    int i;
    for (i=1; i <=10; i++) {  
      System.out.println(i);
    } 
   }

}
When we write i++ we're using shorthand for i = i + 1. When we say i-- we're using shorthand for i = i - 1. Adding and subtracting one from a number are such common operations that these special increment and decrement operators have been added to the language. T
There's another short hand for the general add and assign operation, +=. We would normally write this as i += 15. Thus if we wanted to count from 0 to 20 by two's we'd write:
Source Code
class CountToTwenty  {

  public static void main (String args[]) {
    int i;
    for (i=0; i <=20; i += 2) {  //Note Increment Operator by 2
      System.out.println(i);
    } 
   
 } //main ends here

}
As you might guess there is a corresponding -= operator. If we wanted to count down from twenty to zero by twos we could write: -=
class CountToZero  {

  public static void main (String args[]) {
    int i;
    for (i=20; i >= 0; i -= 2) {  //Note Decrement Operator by 2
      System.out.println(i);
    } 
   }

}

No comments:

Post a Comment