Java : Unary Operators


The Unary Arithmetic Operators are used to increasing or decreasing the value of an operand by adding 1 to the variable, whereas the decrement operator decreases a value.

These two operators have two forms: Postfix and  Prefix to increment or decrement in appropriate variables. These two operators can be placed before or after variables. It’s called a prefix is placed before variable and called as postfix if placed after the variable.

Syntax:


//Postfix
val=a++; //Store the  value of "a" in val then increments.
val=a--; //Store the  value of "a" in val then decrements.

//Prefix
val=++a; //First increment in value of "a" then store in val.
val=--a; //First decrement in value of "a" then store in val.

See Also :

Unary Operator Example


public class UnaryOperatorTest {
public static void main(String[] args) {
int r = 8;
System.out.println("r=: " + r++);
System.out.println("r=: " + r);

int x = 7;
System.out.println("x=: " + x--);
System.out.println("x=: " + x);

int y = 9;
System.out.println("y=: " + ++y);

int p = 5;
System.out.println("p=: " + --p);
}
}

Output


r=: 8
r=: 9

x=:7
x=:6

y=:10

p=:4
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s