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);
}
}
}
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
}
-=
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);
}
}
}
--
http://www.co5.in/
0 comments:
Post a Comment