Chapter 2 - Java for Beginners Course

Unary Operators

Operators that require a single operand are called Unary Operators, in contrast for example to the arithmetic operators that require two. Note that some of these operators also assign a new value to the operand.

Plus and minus unary operators

The plus unary operator is seldom used and indicates that a value is positive. Note that a positive value doesn’t need the plus operator, so the statement below is equivalent to int result1 = 1:

int result1 = +1;
// result1 is 1
System.out.println("result1 = " + result1);

Output:

result1 = 1

The minus unary operator is used to negate an expression, as in, it will return the negative value of a positive expression, or viceversa. For example:

int result2 = -result1;
// result2 is -1
System.out.println("result2 = " + result2);

Output:

result2 = -1

Increment/decrement operators

A double plus operator can be used to increment the value of a variable by 1, for example a++, and a double minus operator can be used to decrement the value of a variable by 1, for example a--.

These 2 operators can be used as a prefix or postfix operator, as in, both a++ or ++a will have the same effect on the variable a.

The following examples show the difference between the prefix and postfix versions:

Example 1: Prefix version

// prefix increment operator
int value1 = 0;
int result3 = ++value1;
// result3 is 1 and value1 is also 1
System.out.println("result3 = " + result3);
System.out.println("value1 = " + value1);

Output:

result3 = 1
value1 = 1

When using the prefix version, the incremented value of the variable is returned, hence in this case, result3 has a value of 1.

Example 2: Postfix version

// postfix increment operator
int value2 = 0;
int result4 = value2++;
// result4 is 0 and value2 is 1
System.out.println("result4 = " + result4);
System.out.println("value2 = " + value2);

Output:

result4 = 0
value2 = 1

When using the postfix version, the original value of the operand is returned, as in, before the increment happens, hence in this case, result4 has a value of 0.

The same applies to the prefix/postfix versions of the decrement operator.

Logical complement operator

This operator, represented by an exclamation mark (!), inverts the value of a boolean variable.

For example:

// logical complement operator
boolean value3 = true;
boolean result5 = !value3;
System.out.println("value3 = " + value3);
System.out.println("result5 = " + result5);

Output:

value3 = true
result5 = false

Note that the original operand isn’t updated, this means that value3 keeps its original value.