Java From Beginner To Advanced

0% completed

Previous
Next
Unary Operators

Unary operators perform operations on a single operand. They can modify the operand's value or state directly. In Java, unary operators are used to increment or decrement numeric values, change the sign of a number, or invert a boolean value.

Unary Operators

OperatorDescriptionExample
++Increment operator; increases an integer by 1a++ or ++a
--Decrement operator; decreases an integer by 1a-- or --a
+Unary plus; indicates a positive value (usually redundant)+a
-Unary minus; negates the value of an expression-a
!Logical complement; inverts the boolean value!flag

Example 1: Using Post-Increment and Pre-Increment Operators

Below is an example that demonstrates the difference between post-increment and pre-increment operators.

Java
Java

. . . .

Explanation:

  • In int postIncrement = a++;, the original value of a (which is 5) is assigned to postIncrement before a is incremented to 6.
  • In int preIncrement = ++a;, a is incremented first (from 6 to 7) and then the updated value is assigned to preIncrement.

Example 2: Using Unary Minus and Logical Complement Operators

Below is an example that demonstrates how to use the unary minus to negate a number and the logical complement operator to invert a boolean value.

Java
Java

. . . .

Explanation:

  • int negatedNum = -num; uses the unary minus to change the sign of num, turning 10 into -10.
  • boolean invertedFlag = !flag; applies the logical complement, converting false to true.

These examples illustrate how unary operators modify individual operands. Experiment with these operators to observe how they affect the values during runtime.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next