Java Incrementing and Decrementing
Java Incrementing and Decrementing.
Increment (++) and decrement (--) operators in Java programming let you easily add 1 to, or subtract 1 from, a variable.Incrementing and Decrementing operators example:
...
int Counter = 5;
Counter++; // Start with Counter and increment it.
Counter--; // Start with Counter and decrement it.
// You can achieve the same with these two variants
Counter = Counter + 1;
Counter = Counter - 1;
// And You can achieve the same with these two variants
Counter += 1;
Counter -= 1;
...
Types of Increment and Decrement Operator
- Prefixing increment / Prefixing decrement Operator
- Postfixing increment / Postfixing decrement Operator
Postfixing Versus Postfixing:
...
int a = ++x; // prefix increment
int b = x++; // postfix increment
int a = --x; // prefix decrement
int b = x--; // postfix decrement
...
Prefixing says that you performs the increment operation and then returns the value of the increment operation.
Postfixing says that you returns the value before you performs the increment operation.
Prefixing Versus Postfixing program example:
public class PrePostOperator {
public static void main(String[] args) {
int myAge = 39; // initialize two integers
int yourAge = 39;
System.out.print("I am: " + myAge + " years old.\n");
System.out.print("You are: " + yourAge + " years old\n");
myAge++; // postfix increment
++yourAge; // prefix increment
System.out.print("One year passes...\n");
System.out.print("I am: " + myAge + " years old.\n");
System.out.print("You are: " + yourAge + " years old\n");
System.out.print("Another year passes\n");
System.out.print("I am: " + myAge++ + " years old.\n");
System.out.print("You are: " + yourAge + " years old\n");
System.out.print("Let's print it again.\n");
System.out.print("I am: " + myAge + " years old.\n");
System.out.print("You are: " + yourAge + " years old\n");
}
}
The result will bee:
I am: 39 years old.
You are: 39 years old
One year passes...
I am: 40 years old.
You are: 40 years old
Another year passes
I am: 40 years old.
You are: 40 years old
Let's print it again.
I am: 41 years old.
You are: 40 years old
© 2010 by Finnesand Data.
All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the
correctness in the pages or source codes.
The risk of using this web-site pages or any program
codes from this website is entirely at the individual user.