Java program using Increment and Decrement Operators
Increment ++ and Decrement -- Operator as Prefix and Postfix in java
Increment and
decrement operators are unary operators that add or subtract one, to or from
their operand (an operand is the part of a
computer instruction that specifies data that is to be operating on or
manipulated and, by extension, the data itself.) respectively.
In different programming language(Java, C, C++, Vala, PHP, etc…) the increment
operator (++) increases, the decrement
operator (--) decreases the value of the variable(operand) by 1.
let us suppose, num= 10
using increment operator,
num++; //Increase value by 1 and the value of num
becomes 11
++num; //Increase value by 1 and the value of num
becomes 11
using decrement operator,
num--; //Decrease value by 1 and the value of
num becomes 9
--num; //Decrease value by 1 and the value of
num becomes 9
It is quite simple till now, But Here is the
the main difference which matters a lot when the Operators are used as prefix and
postfix.
Working mechanism of prefix and postfix operators
- If you use the prefix operator like --num then It decrements the value num by 1 at first and then returns its value.
- If you use the postfix operator like num-- then It returns its initial value at first and then decrements the value of num by 1.
Demonstration of the prefix and postfix form of the Increment (++) and Decrement (--) operators
Example of the prefix Increment(++) Operator and postfix Increment(++)public class Increment
{
public static void main(String []args)
{
int num=10; //value assign
//Initially,num = 10. It is increased to 11 then, it is displayed.
System.out.println("The increased value using prefix = "+ ++num); //output
//11 is displayed then, num is increased to 12.
System.out.println("The increased value using postfix = "+num++); //output
}
}
Example of the prefix decrement (--) Operator and postfix decrement (--)
{
public static void main(String []args)
{
int num=10;//value assign
//Initially,num = 10. It is decreased to 9 then, it is displayed.
System.out.println("The decreased value using prefix = "+ --num);//output
//9 is displayed then, num is decreased to 8.
System.out.println("The decreased value using postfix = "+num--);//output
}
}
- Output of the prefix Increment(++) Operator and postfix Increment(++)
The increased value using prefix = 11
The increased value using postfix = 11
- Output of the prefix decrement (--) Operator and postfix decrement (--)
The decreased value using prefix = 9
The decreased value using postfix = 9
Comments
Post a Comment