Increment and Decrement
Swipe to show menu
Now that you know how basic operators work, you can look at two very simple but very useful operators in Java — increment and decrement. These are used when we want to change a value by exactly 1.
++— increment (increase by 1);--— decrement (decrease by 1).
They are often used in counters, loops, and tracking changes in values.
Increment Operator ++
The increment operator increases a value by 1:
int coffeeCupsSold = 35;
coffeeCupsSold++; // 36
coffeeCupsSold++; // 37
coffeeCupsSold++; // 38
Decrement Operator --
The decrement operator decreases a value by 1:
int coffeeCupsSold = 35;
coffeeCupsSold--; // 34
coffeeCupsSold--; // 33
Example
Main.java
1234567891011121314151617package com.example; public class Main { public static void main(String[] args) { int coffeeCupsSold = 35; coffeeCupsSold++; // 36 coffeeCupsSold++; // 37 coffeeCupsSold++; // 38 coffeeCupsSold--; // 37 coffeeCupsSold--; // 36 System.out.println(coffeeCupsSold); } }
The example starts with coffeeCupsSold set to 35, then apply ++ three times to reach 38, and then -- twice to bring it back down to 36. The final println prints 36 as the result.
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 6
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 2. Chapter 6