In this article, we will learn about java increment and
decrement operators with programming examples.
Java Increment Operator
Java increment operator is one of the arithmetic operators.
Increment operator increments the value inside a variable. Increment operator
is a unary operator, it operates on one operand. It is represented by ++ symbol.
It has two types:
Pre Increment Operator
In this, ++ operator is written before the variable
name.
For example,
int a = 1;
++a;
Now value of a become 2.
Programming Example of Pre Increment Operator
class PreIncrement
{
public static void main(String[] args)
{
int a = 1;
int b = ++a;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}
Output:
a = 2
b = 2
Post Increment Operator
In this, ++ operator is written after the variable
name.
For example,
int a = 1;
a++;
Now value of a become 2.
Programming Example of Post Increment Operator
class PostIncrement
{
public static void main(String[] args)
{
int a = 1;
int b = a++;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}
Output:
a = 2
b = 1
Value of b is 1, because value of a is assigned to b and after assigning, variable a increments.
Java Decrement Operator
Java Decrement operator is one of the arithmetic operator.
Decrement operator Decrements the value inside a variable. Decrement operator
is a unary operator, it operates on one operand. It is represented by -- symbol.
It has two types:
Pre Decrement Operator
In this, -- operator is written before the variable name.
For example,
int a = 2;
--a;
Now value of a become 1.
Programming Example of Pre Decrement Operator
class PreDecrement
{
public static void main(String[] args)
{
int a = 2;
int b = --a;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}
a = 1
b = 1
Post Decrement Operator
In this, -- operator is written after the variable name.
For example,
int a = 2;
a--;
Now value of a become 1.
Programming Example of Post Decrement Operator
class PostDecrement
{
public static void main(String[] args)
{
int a = 2;
int b = a--;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}
a = 1
b = 2
Value of b is 2, because value of a is
assigned to b and after assigning, variable a decrements.
0 comments:
Post a Comment