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
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: 10Explanation
++(Increment): Increases the value by 1.--(Decrement): Decreases the value by 1.- Prefix (
++a): Increments first, then uses the value. - Postfix (
a++): Uses the value first, then increments.
Try Yourself
- Complex Expression: What is the value of
aandbafterint b = a++ + ++a;ifastarts at 5? Trace it. - Loop Counter: Write a
whileloop that prints numbers from 10 down to 1 usingn--. - Boolean Not: Use
!to toggle a boolean variable inside a loop. - Character Increment: Can you do
char ch = 'A'; ch++;? What does it print? - Brain Twister: What is the output of
int x = 5; System.out.println(x++ + ++x);?
