Operators

Java Program to Demonstrate Unary Operators

A Java program to demonstrate the usage of unary operators.

Problem Description

Write a Java program to demonstrate the usage of unary operators (++, --).

Code

UnaryOperators.java
public class UnaryOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 10;

        System.out.println("Post-increment (a++): " + (a++)); // Prints 10, then a becomes 11
        System.out.println("Value of a: " + a);

        System.out.println("Pre-increment (++b): " + (++b)); // b becomes 11, then prints 11
        System.out.println("Value of b: " + b);
        
        System.out.println("Post-decrement (a--): " + (a--)); // Prints 11, then a becomes 10
        System.out.println("Value of a: " + a);

        System.out.println("Pre-decrement (--b): " + (--b)); // b becomes 10, then prints 10
        System.out.println("Value of b: " + b);
    }
}

Output

Post-increment (a++): 10
Value of a: 11
Pre-increment (++b): 11
Value of b: 11
Post-decrement (a--): 11
Value of a: 10
Pre-decrement (--b): 10
Value of b: 10

Explanation

  1. ++ (Increment): Increases the value by 1.
  2. -- (Decrement): Decreases the value by 1.
  3. Prefix (++a): Increments first, then uses the value.
  4. Postfix (a++): Uses the value first, then increments.

Try Yourself

  1. Complex Expression: What is the value of a and b after int b = a++ + ++a; if a starts at 5? Trace it.
  2. Loop Counter: Write a while loop that prints numbers from 10 down to 1 using n--.
  3. Boolean Not: Use ! to toggle a boolean variable inside a loop.
  4. Character Increment: Can you do char ch = 'A'; ch++;? What does it print?
  5. Brain Twister: What is the output of int x = 5; System.out.println(x++ + ++x);?