DEV Community

Increment ++ and Decrement -- Operator explained in simple way

In this article, you will learn about the increment operator ++ and the decrement operator -- .

In programming (Java, C, C++, JavaScript etc.), the increment operator ++ decrement operator -- are used.

Increment operator (++) or Decrement operator (--) --> This operators increase the value of variable by 1 or decrease the variable by 1.
For eg

int a = 5; a++; //output will be 6 int b = 5; a--; //output will be 4 
Enter fullscreen mode Exit fullscreen mode

These operators are further divided into
1) Prefix increment/decrement (++a/--a)
2) Postfix increment/decrement (a++/a--)

1) Prefix increment/decrement operator --> The ++ and -- are placed before number, first evaluate the value and then performs the work.
For eg

int a = 5; System.out.println(++a); // here the new value is evaluated that is + so value will be 6 and output will be 6 System.out.println(a); // output will be 6 because there is no further work to perform. 
Enter fullscreen mode Exit fullscreen mode

2) Postfix increment/decrement (a++/a--) --> In this work is perform first, and then evaluate the value.
for eg

int a = 5; System.out.println(a++); // Here work is perform what work? the work is to print the value of a that is 5, after that the value will be evaluated to 6 i.e is a + 1 = 6; 5 + 1 = 6; 
Enter fullscreen mode Exit fullscreen mode

When you print value of a for second time then output will show 6;

int a = 5; System.out.println(a++); //output will be 5 System.out.println(a); // after incrementation of a the value will be 6 and it will printed as a output. 
Enter fullscreen mode Exit fullscreen mode

Let's take another example to understand in java programming language

class Operator { public static void main(String[] args) { int a = 5, System.out.println(a++); // 5 will be output System.out.println(++a); // 7 will be output System.out.println(a); // 7 as it is System.out.println(--a); // 6 because of subtraction System.out.println(a--); // 6 will be output System.out.println(++a); // 6 will be output } } 
Enter fullscreen mode Exit fullscreen mode

1 In System.out.println(a++); // 5 will be output here first 5 will be printed and then ++ of 5 will happen so now new value of a will be 6.

2 In System.out.println(++a); the value of a will be 7 because of addition ++a it is because addition is performed, after that 7 will be output.

3 In System.out.println(a); // 7 as it is value from previous.

4 In System.out.println(--a); the value will be 6 because -- of 7-1=6 i.e. value is 6

5 In System.out.println(a--); // 6 will be output because first print value of a and then do subtraction i.e. 6-1=5. When new print command for value a will be printed then 5 will be displayed.

6 In System.out.println(++a); // 6 will be output because ++a i.e. first do addition of _5+1=6 _and print value of a which is 6.

Top comments (0)