increment & decrement operators in java
previous NextIn Java, the increment and decrement operators are used to increase or decrease the value of a variable by 1. These operators are often used in loops and other situations where you need to modify a variable's value in a controlled manner.
- Increment & decrement operators can apply only for variables but not for constant values. otherwise, we will get a compile-time error
- We can't perform nesting of increment or decrement operator, otherwise, we will get compile time error
- For the final variables, we can't apply increment or decrement operators, otherwise, we will get compile-time error
- We can apply increment or decrement operators even for primitive data types except for boolean.
- ++variable: Increments the value of the variable by 1 and returns the updated value.
- --variable: Decrements the value of the variable by 1 and returns the updated value.
- variable++: Returns the current value of the variable, then increments it by 1.
- variable--: Returns the current value of the variable, then decrements it by 1.
Increment Operators
There are two types of increment operators available.
- pre-increment
- post-increment
Pre Increment Operator in Java
In the pre-increment operator, the variable is first incremented by 1 and then assigned to another variable.
Example
class PreIncrementProgram{
public static void main(String [] args){
int x = 5;
System.out.println(++x);//x=6
int y = ++x;//x=7
System.out.println(y);//7
}
}
Output :
6 7
Post Increment Operator in Java
In the post-increment operator, the variable is first used and assigned to another variable and then it will increase by 1.
Example
class PostIncrementProgram{
public static void main(String [] args){
int x = 5;
System.out.println(x++);//print 5 and increse by one now x=6
int y = x++;//x=7,y==6
System.out.println(x);//7
System.out.println(y);//6
}
}
Output :
5 7 6
Decrement Operator in java
there are two types of decrement operator available in java.
- pre decrement in java
- post decrement in java
Pre Decrement Operator in java
In pre-decrement operator, the variable is first decremented by 1 and then assigned to another variable.
Example
class PreDecrementProgram{
public static void main(String [] args){
int x = 5;
System.out.println(--x);//x=4
int y = --x;//x=3
System.out.println(y);//3
}
}
Output :
4 3
Post decrement Operator in java
In post-decrement operator, the variable is first used and assigned to another variable and then it will decrease by 1.
Example
class PostDecrementProgram{
public static void main(String [] args){
int x = 5;
System.out.println(x--);//print 5 and decrese by one now x=4
int y = x--;//x=3,y==4
System.out.println(x);//3
System.out.println(y);//4
}
}
Output :
5 3 4
