What are the restrictions on increment and decrement operators in java?

Java 8Object Oriented ProgrammingProgramming

The increment operator increments the value of the operand by 1 and the decrement operator decrements the value of the operand by 1. We use these operators to increment or, decrement the values of the loop after executing the statements on a value.

Example

 Live Demo

public class ForLoopExample {
   public static void main(String args[]) {
      //Printing the numbers 1 to 10
      for(int i = 1; i<=10; i++) {
         System.out.print(" "+i);
      }
      System.out.println(" ");
      //Printing the numbers 10 to 1
      for(int i = 10; i>=1; i--) {
         System.out.print(" "+i);
      }
   }
}

Output

1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1

Restrictions on increment and decrement operators

  • You cannot use increment and decrement operators with constants, if you do so, it generates a compile time error.

Example

public class ForLoopExample {
   public static void main(String args[]) {
      int num = 20;
      System.out.println(num++);
      System.out.println(20--);
   }
}

Output

ForLoopExample.java:5: error: unexpected type
      System.out.println(20--);
                        ^
   required: variable
   found: value
1 error
  • You cannot nest two increment or decrement operators in Java, if you do so, it generates a compile time error −

Example

public class ForLoopExample {
   public static void main(String args[]) {
      int num = 20;
      System.out.println(--(num++));
   }
}

Output

ForLoopExample.java:4: error: unexpected type
      System.out.println(--(num++));
                               ^
required: variable
found: value
1 error
  • Once you declare a variable final you cannot modify its value. Since increment or, decrement operators changes the values of the operands. Usage of these operators with a final variable is not allowed.

Example

public class ForLoopExample {
   public static void main(String args[]) {
      final int num = 20;
      System.out.println(num++);
   }
}

Output

ForLoopExample.java:4: error: cannot assign a value to final variable num
   System.out.println(num++);
                      ^
1 error
  • Usage of increment and decrement operators with boolean variables is not allowed. If you still, try to increment or decrement a boolean value a compile time error is generated.

Example

public class ForLoopExample {
   public static void main(String args[]) {
      boolean bool = true;
      System.out.println(bool++);
   }
}

Output

ForLoopExample.java:4: error: bad operand type boolean for unary operator '++'
      System.out.println(bool++);
                            ^
1 error
raja
Published on 08-Jul-2019 16:20:10
Advertisements