Saturday 1 February 2014

Arithmetic Operators: ++, --

++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1

Pre increment
    Syntax:
    ++variable
      pre increment operator increments the variable value by 1 immediately.
  
Example
class PreIncrement{
 public static void main(String args[]){
  int var = 10;
  System.out.println(++var);
 }
}

Output
11

Post increment
    Syntax:
        variable++

    post increment operator increments the variable value by 1 after executing the current statement.


class PostIncrement{
 public static void main(String args[]){
  int var = 10;
  
  System.out.println(var++);
  System.out.println(var);
 }
}
Output

10
11

Pre Decrement
    Syntax:
        --variable

    pre decrement operator decrements the variable value by 1 immediately.
    Example
     
class PreDecrement{
 public static void main(String args[]){
  int var = 10;
  System.out.println(--var);
 }
}
Output

9

Post Decrement
    Syntax:
        variable--

post decrement operator decrements the variable value by 1 after executing the current statement.

class PostIncrement{
 public static void main(String args[]){
  int var = 10;
  System.out.println(var--);
  System.out.println(var);
 }
}

Output
10
9


Some more Examples
Class ArithmeticEx{
 public static void main(String args[]){
  int var = 10;
  
  int result = var++ + var++ ;
  System.out.println("value of variable is " + var);
  System.out.println("Result is " +result);
  
  result = var++ + ++var;
  System.out.println("value of variable is " + var);
  System.out.println("Result is " +result);

  result = var++ + var--;
  System.out.println("value of variable is " + var);
  System.out.println("Result is " +result);

  result = --var + var--;
  System.out.println("value of variable is " + var);
  System.out.println("Result is " +result);
 }
}
Output
value of variable is 12
Result is 21
value of variable is 14
Result is 26
value of variable is 14
Result is 29
value of variable is 12
Result is 26

Arithmetic Operators                                                 Conditional Operators                                                 Home

No comments:

Post a Comment