Unary Operator Post and Pre Operations
Understanding unary increment with post operation and pre operation example.
Learning Objectives
- Learning to use unary post and pre operations using increment operator example.
Source Code
|
Run Output
Code Understanding
int a=10, b=10; //two integer variables are initialised
System.out.println(“a++ directly done while printing = “+ a++);
Here the output would be 10 only as effect of increment will happen only after instruction runs.
System.out.println(“Value of a in next statement = “+ a);
Here we get 11 as the post operation of a++ has happened in previous statement.
System.out.println(“++b directly done while printing = “+ ++b);
Here it will print 11 as ++b will increment first and then printing will happen
System.out.println(“Value of b in next statement = “+ b);
Since here we are just printing b which has already been incremented earlier so 11 will print again.
Notes
- unary operator has just one operand and the value at the same memory location is incremented or decremented without using a second location. So it is supposed to be an efficient process. For example a++ will be more efficient as compared to a=a+1
Common Errors
- Care must be taken while using multiple unary operators within the same expressions as effect of first sub-expression can be seen on other part. For. e.g.
int a=10; int b=a++ – a++;
will yield -1 as effect of first a++ will be seen on next a++. This would be b=10-11.
Suggested Filename(s): UnaryPostPre.java
sunmitra| Created: 2-Mar-2018 | Updated: 2-Mar-2018|