wellnwill Marathahalli Bangalore

Increment (++) / Decrement (--) Operator

  • Increment Operator (++) is used to increment value of Variable by 1 (default)
  • Decrement Operator (--) is used to decrement value of Variable by 1 (default)

Types of Increment and Decrement Operator:

  1. Pre Increment / Pre Decrement Operator (1st increment/decrement then work)
  2. Post Increment / Post Decrement Operator (1st work then increment/decrement)
Expressions Initial value of a Value of b Final value of a
b=++a ; 1 2 2
b=a++ ; 1 1 2
b=--a ; 1 0 0
b=a-- ; 1 1 0

Pre Increment/PreDecrement Operator -->

  • “++” or “--” will be written before Variable name.
  • Value will be Incremented or Decremented First and then incremented or Decremented value will be used in expression.
class Test25 
{
   public static void main(String argss[]) 
   {
     int a=20; 
     System.out.println(++a);
   }
}

// O/P ->  21
class Test26 
{
   public static void main(String argss[]) 
   {
     int a=20; 
     System.out.println(--a);
   }
}

// O/P -> 19

Post Increment / Post Decrement -->

  • “++” or “--” will be written after Variable name.
  • Post increment or decrement operator are used to increase or decrease value just after completion of expression evaluation.
class Test27
{
   public static void main(String argss[])
   {
     int a=20; 
     System.out.println(a++);  // 20
     System.out.println(a);   // 21
  }
}
class Test28
{
   public static void main(String argss[])
   {
     int a=20; 
     System.out.println(a--);  // 20
     System.out.println(a);  // 19
   }
}
  • We can apply Increment /Decrement Operators on variables but not for the value/constant.
  • We can apply increment /Decrement Operators for every primitive types except boolean.
class Test29
 {
   public static void main(String argss[])
   {
  int a=20++; 
  System.out.println(a);
  }
}

// O/P - CompileTimeException 
          - unexpexted type, required-variable,found-value.
class Test30
{
   public static void main(String argss[])
   {
     boolean a=true; 
     System.out.println(a++);
   }
}

// O/P - CompileTimeException
          - bad operand type boolean for unary operator "++".
  • Listing of increment /Decrement Operators are not allowed.
  • We can not apply increment /Decrement Operators for final variables
class Test31
{
   public static void main(String argss[])
   {
     int a=20; 
     int x= (a++)++;
     System.out.println(a);
   }
}

// O/P - CompileTimeException
       - unexpexted type, required-variable,found-value.
class Test32
{
   public static void main(String argss[])
   {
     final int a=20; 
     a++;
     System.out.println(a);
   }
}

// O/P - can not assign value to a final variable.

  • In the case of increment /Decrement Operators type casting will be performed automatically.
  • Difference between x++ and x=x+1:

    x++ : internal type casting(type of x)(x+1)) and x=x+1 is a normal expression.

    x++ means x=x+1;

Footer with Map