Thursday, March 31, 2016

Increment Operators


Hey guys, over the past few posts we learnt about math operations. Now we're gonna learn about Increment Operators.

What are these Increment and Decrement Operators ?

Increment and decrement operators are unary operators that add or subtract one from their operand, respectively. They are commonly implemented in imperative programming languages.

It's very simple. let's go through simple exercises

As usual open Eclipses. Then type....

import java.util.*;
public class main {
public static void main(String []args){

int x = 10;

x = x + 1 ;

System.out.println(x);

}
}

OK. Let's see what happened here...

  1. We declare and initialize x variable to 10
  2. Then we say, x equals to x + 1
Yeah I know you are confused. As we learnt in mathematics classes this is a illegal expression. Because in maths ,
                            x = x + 1
                            x - x = 1
                            0 = 1 ????

            Never can be happened !!!!!!!!!!

But in programming of course it is happening...

That means 'x' variable is changing; you are adding '1'  to the value of  'x' . In this case '10 + 1'

How about ...

  1.  x = x + 2;
  2. x = x - 1;
  3. x = x - 2;


Another Example :-

import java.util.*;
public class main {
public static void main(String []args){

int x = 10;

x = x++ ;

System.out.println(x);

}
}

This also means the 'x = x + 1'. 

No comments:

Post a Comment