Java Programming Tutorial Index

Java Fundamentals

In Java, unary arithmetic operators are used to increasing or decreasing the value of an operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator decreases a value.



Increment and decrement unary operator works as follows:

Syntax:

val++;
val--;

These two operators have two forms: Postfix and Prefix. Both do increment or decrement in appropriate variables. These two operators can be placed before or after of variables. When it is placed before the variable, it is called prefix. And when it is placed after, it is called postfix.

Following example table, demonstrates the work of Increment and decrement operators with postfix and prefix:

Example Description
val = a++; Store the value of "a" in "val" then increments.
val = a--; Store the value of "a" in "val" then decrements.
val = ++a; Increments "a" then store the new value of "a" in "val".
val = --a; Decrements "a" then store the new value of "a" in "val".

Programs to Show How Assignment Operators Works

Example:

public class unaryop {
 public static void main(String[] args) {
  int r = 6;
  System.out.println("r=: " + r++);
  System.out.println("r=: " + r);
  
  int x = 6;
  System.out.println("x=: " + x--);
  System.out.println("x=: " + x);
  
  int y = 6;
  System.out.println("y=: " + ++y);

  int p = 6;
  System.out.println("p=: " + --p);
 }
}

Output:

r=: 6
r=: 7
x=: 6
x=: 5
y=: 7
p=: 5


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram