Unary operators performs operations with single operand
Lets go through different types of Unary operations with java coding example below:
Increment
It increments the values of an integer. There are two types of Increment
- Pre-Increment
- Post-Increment
Pre- Increment
When you place ++ before the variable name like ++ x it instantly increments and assigns the value is called pre-increment.
The below example y=++x where as x= 5 instantly increments the value to 6 and assigns to y as a result y =6
package com.test.basics;
public class TestPreIncrement {
public static void main(String[] args) {
int x = 5;
int y;
y = ++x;
System.out.println("It instantly increments and assigns value to Y is " + y);
}
}
Post-Increment
When you place ++ after the variable name like x++ its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement is called post-increment
The below example y=x++ where as x= 5 increments the value to 6 but value gets updated before the execution of the next statement as a result y =5
package com.test.basics;
public class TestPostIncrement {
public static void main(String[] args) {
int x = 5;
int y;
y = x++;
System.out.println("X value is "+x);
System.out.println("It increments but incremned value gets updated to Y in the next execution is " + y);
}
}
Decrement
It decrements the values of an integer. There are two types of Decrement
- Pre-decrement
- Post-decrement
Pre-decrement
When you place – – before the variable name like – – x it instantly decrements and assigns the value is called pre-increment.
The below example y=- -x where as x= 5 instantly decrements the value to 4 and assigns to y as a result y =4
package com.test.basics;
public class TestPreDecrement {
public static void main(String[] args) {
int x = 5;
int y;
y = --x;
System.out.println("It instantly decrements and assigns value to Y is " + y);
}
}
Post-Decrement
When you place – – after the variable name like x- – its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement is called post-decrement
The below example y=x- – where as x= 5 decrements the value to 4 but value gets updated before the execution of the next statement as a result y =4
package com.test.basics;
public class TestPostDecrement {
public static void main(String[] args) {
int x = 5;
int y;
y = x--;
System.out.println("X value is "+x);
System.out.println("It decrements but decremented value gets updated to Y in the next execution so y value is " + y);
}
}