Java ProgramsBasics & I/ODemonstrate Unary Operators

Demonstrate Unary Operators in Java

beginner·  Basics & I/O  ·  Operators

Problem

Unary operators act on a single operand — unary +/- flip or preserve sign, while ++/-- can appear before or after the variable, changing when the update takes effect relative to the expression it's used in.

Given a single integer, demonstrate unary plus, unary minus, and pre- and post-increment/decrement on it.

Input
5
Output
+a = 5

Java Program

Java
public class DemonstrateUnaryOperators { public static void main(String[] args) { int a = 5; System.out.println("+a = " + (+a)); System.out.println("-a = " + (-a)); System.out.println("a++ used in expression, prints: " + (a++)); // reads 5, then increments System.out.println("a is now: " + a); System.out.println("++a used in expression, prints: " + (++a)); // increments first, then reads 7 System.out.println("a is now: " + a); System.out.println("a-- used in expression, prints: " + (a--)); // reads 7, then decrements System.out.println("a is now: " + a); System.out.println("--a used in expression, prints: " + (--a)); // decrements first, then reads 5 System.out.println("a is now: " + a); } }

Output

+a = 5 -a = -5 a++ used in expression, prints: 5 a is now: 6 ++a used in expression, prints: 7 a is now: 7 a-- used in expression, prints: 7 a is now: 6 --a used in expression, prints: 5 a is now: 5

Core Logic

Comparing post-increment/decrement against pre-increment/decrement side by side shows exactly when each form updates the variable relative to when it's read.

How It Works
  1. 1+a and -a simply preserve or flip the sign of a, without changing a itself.
  2. 2a++ (post-increment) is read using a's current value first, and only afterward increments it — so the printed expression shows the old value.
  3. 3++a (pre-increment) increments a first, then the expression uses the new value — so the printed expression already shows the updated value.
  4. 4a-- and --a mirror the same before/after distinction, but decrementing instead of incrementing.
  5. 5After each increment or decrement, a's value is printed separately to confirm what it actually became.
Starting from a = 5: a++ prints 5 but leaves a at 6, while a following ++a prints 7 directly, since the increment happens before the read.
💡

Key Point: The position of ++/-- relative to the variable only matters when the expression's value is used immediately, as in a print statement or another calculation — as a standalone statement on its own line, a++; and ++a; have an identical effect.

Key Concepts

unary + operatorunary - operator++ operator-- operator

Related Programs