Interesting facts about Increment and Decrement operators in Java


There are many interesting facts with respect to increment and decrement operators in Java. We will discuss a few of them with examples −

  • The increment and decrement operators can’t be used with the ‘final’ variables. This is due to the fact that variables associated with ‘final’ keyword can’t be changed −

Example

 Live Demo

public class Demo{
   public static void main(String[] args){
      final int my_val = 34;
      int my_val_2 = ++my_val;
      System.out.println("The value is :");
      System.out.println(my_val_2);
   }
}

Output

/Demo.java:6: error: cannot assign a value to final variable my_val
int my_val_2 = ++my_val;
         ^
1 error
  • Nesting the ‘++’ and ‘- -‘ operator isn’t possible or rather not allowed.

Example

 Live Demo

public class Demo{
   public static void main(String[] args){
      int my_val_1 = 99;
      int my_val_2 = ++(++my_val_1);
      System.out.println("The value is ");
      System.out.println(my_val_2);
   }
}

Output

/Demo.java:6: error: unexpected type
int my_val_2 = ++(++my_val_1);
          ^
required: variable
found: value
1 error

Updated on: 04-Jul-2020

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements