Increment and Decrement Operators

Short Answer:
Increment (++) increases a value by 1 and Decrement (--) decreases a value by 1.

Detailed Explanation:
Java provides two types of increment and decrement operators:

  • Pre-Increment / Pre-Decrement
  • Post-Increment / Post-Decrement

The difference depends on when the value is updated.


1. Pre-Increment (++a)

Short: Value increases first, then used.

int a = 5;
int b = ++a;   // a becomes 6, then assigned to b

Result: a = 6, b = 6


2. Post-Increment (a++)

Short: Value used first, then increased.

int a = 5;
int b = a++;   // b = 5, then a becomes 6

Result: a = 6, b = 5


3. Pre-Decrement (--a)

int a = 5;
int b = --a;   // a becomes 4, then assigned

4. Post-Decrement (a--)

int a = 5;
int b = a--;   // b = 5, then a becomes 4

Key Difference Table

Operator Operation Order Example Result
++a Increment first a=6, b=6
a++ Use first, then increment a=6, b=5
--a Decrement first a=4, b=4
a-- Use first, then decrement a=4, b=5

Important Interview Points

  • Works only with variables (not constants).
  • Commonly used in loops.
  • Be careful while using inside expressions.
  • Pre and Post behave differently in complex statements.

Tricky Interview Example

int a = 5;
int result = a++ + ++a;
System.out.println(result);

Step-by-step: a++ → 5 (a becomes 6) ++a → 7 Result = 5 + 7 = 12

0 comments

Leave a comment