- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differentiate between the prefix and postfix forms of the ++ operator in java?
Java provides two operators namely ++ and --, to increment and decrement values by 1 respectively.
There are two variants of these operators −
Pre-increment/decrement − This form, increments/decrements the value first, and then performs the specified operation.
Example
In the following example, the initial value of the variable i is 5. We are printing the incremented value of it using the pre increment operator.
Since we are using the pre increment operator, the value of i is incremented then printed.
public class ForLoopExample { public static void main(String args[]) { int i = 5; System.out.println(++i); System.out.println(i); } }
Output
6
Post-increment/decrement − This form, performs the specified operation first, and then increments/decrements the value.
Example
In the following example, the initial value of the variable i is 5. We are printing the incremented value of it using the post increment operator and, we are printing the i value again.
Since we are using the post increment operator, the value of i is printed and then incremented.
public class ForLoopExample { public static void main(String args[]) { int i = 5; System.out.println(i++); System.out.println(i); } }
Output
5 6
Example
public class ForLoopExample { public static void main(String args[]) { int i = 5; System.out.println(i--); System.out.println(i); int j =5; System.out.println(--j); } }
Output
5 4 4