Interesting facts about Increment and Decrement operators in Java
Increment operator is used to incrementing a value by 1. There are two varieties of increment operator:
- Post-Increment: Value is first used for computing the result and then incremented.
- Pre-Increment: Value is incremented first and then the result is computed.
Decrement operator is used for decrementing the value by 1. There are two varieties of decrement operators.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- Post-decrement: Value is first used for computing the result and then decremented.
- Pre-decrement: Value is decremented first and then the result is computed.
Now let us do Interesting facts about Increment and Decrement operators:
- Can only be applied to variables only
- Nesting of both operators is not allowed
- They are not operated over final variables
- Increment and Decrement Operators can not be applied to boolean.
Let us discuss these 4 facts as listed above and do implement them as follows:
Fact 1: Can be applied to variables only
We can apply ++ and — operator only for variables but not for the constant values. If we are trying to apply ++ and — operator on the constant value then we will get a compile-time error which we will be seeing in example 1B after below example as follows:
Fact 2: Nesting of both ++ and — operators are not allowed
Fact 3: Final variables can’t apply increment and decrement operator
The increment and decrement operators can not be applied to final variables because of the simple reason that their value can not be changed.
Fact 4: Increment and Decrement Operators can not be applied to boolean
We can apply ++ and — operators for all primitive data types except Boolean type as it only has true and false which even sounds impractical.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.