Technology Programming

Unary Operator

Definition:

Unary operators return the result of an operation on only one operand. There are six defined in the Java language:

+    the unary plus operator makes an expression positive. -    the unary negative operator makes an expression negative. ++   the increment operator increments a value by 1. --   the decrement operator decrements a value by 1. !    the logical complement operator inverts a boolean value. ~    the bitwise complement operator inverts the bits of a binary number.


The increment and decrement operators are special because they can be applied in both prefix (before the operand) and postfix (after the operand) positions. The difference between prefix and postfix is not the end result of the operation but how the expression is evaluated. The prefix expression returns the value after the operation has been performed whereas the postfix expression returns the value before the operation is performed.

Examples:


int prefixValue = 5;//increment prefixValue by one (i.e., 6). ++prefixValue;//the prefix expression is equal to prefixValue//incremented by one (i.e., 7). int seven = ++prefixValueint postfixValue = 10//increment the postfixValue by one (i.e., 11). postfixValue++;//the postfix expression is equal to postfixValue//before it is incremented by one (i.e., 11).int eleven = postfixValue++;//postfixValue has still been incremented by one (i.e., 12). int twelve = postfixValue;

Glossary:

#ABCDEFGHIJKLMNOPQRSTUVWXYZ

Leave a reply