← Back to Chapters

Java Unary Operators

➕ Java Unary Operators

? Quick Overview

Unary operators in Java work on a single operand. They are commonly used to increment, decrement, negate values, or reverse boolean results.

? Key Concepts

  • Operate on only one variable or value
  • Increase or decrease values by 1
  • Convert positive to negative and vice versa
  • Work with both numeric and boolean data

? Syntax / Theory

  • + Unary plus
  • - Unary minus
  • ++ Increment
  • -- Decrement
  • ! Logical NOT

? Code Example(s)

? View Code Example
// Demonstrating Java unary operators
class UnaryDemo {
public static void main(String[] args) {
int a = 10;
System.out.println(+a);
System.out.println(-a);
System.out.println(++a);
System.out.println(--a);
boolean flag = false;
System.out.println(!flag);
}
}

? Live Output / Explanation

Output Explanation

Unary plus prints the value as-is, unary minus negates it, increment and decrement change the value by one, and logical NOT reverses the boolean value.

? Interactive Playground

Click the buttons to visualize the difference between prefix and postfix operators.

Integer (int x)

x = 10
Console Output: Ready...

Boolean (boolean flag)

flag = true
Console Output: Ready...

✅ Tips & Best Practices

  • Prefer pre-increment in expressions for clarity
  • Use unary operators sparingly to keep code readable
  • Avoid complex expressions with multiple unary operators

? Try It Yourself

  • Change the value of a and observe the output
  • Test post-increment and post-decrement operators
  • Apply unary operators to different data types