Decrement operator in java with example

The decrement operators used to subtract 1 to previous value. Decrement operator is unary operator because only one variable is used.

There are 2 type in decrement operator. They are
1. Postfix decrement operator
2. Prefix decrement operator

Syntax:-

For postfix

variable--

For prefix

--variable

Both prefix and postfix decrement operator are same thing when they used independently(i-- or --i) ie subtract 1 to previous value. But they behave differently when they used in expression on the right hand side of assignment statement(num=i-- or num=--i)

Postfix decrement operator:-

class group{
public static void main(String arng[]){
int num, i;
i=3;
i--;
num=i--;
System.out.println("i="+i);
System.out.println("num="+num);
}
}

Output:-

i=1
num=2

Execution:-

In postfix decrement operator, fist assign value to left side variable(num) than decrement by 1(i)

Here in our example first i is three(i=3) than i decrement by 1(i--). here i value is 2.

Next statement is num = i--;

Here postfix is used so first i value is assigned to num ie 2 than i is decrement by 1 ie i value becomes 1.

Prefix decrement operator

class group{
public static void main(String arng[]){
int num, i;
i=3;
--i;
num=--i;
System.out.println("i="+i);
System.out.println("num="+num);
}
}


Output:-

i=1
num=1

Execution:-

In prefix decrement operator, first decrement(i) by 1 than result value is assigned to left side variable(num)

Here in our example first i is three(i=3) than i decrement by 1(--i). here i value is 2.

Next statement is num = --i;

Here prefix is used so first i is decrement by 1 ie i value becomes 1. Than value of i is assigned to num ie 1

Example:-

Program to fined sum of N odd number.

import java.util.Scanner;

class group{
public static void main(String arng[]){
int num, i,sum=0;
Scanner data = new Scanner(System.in);
System.out.println("Enter a number");
num=data.nextInt();
for(i=num;i>=0;i--)
{
if((i%2)==0)
continue;
else
sum=sum+i;
}
System.out.println("Sum of odd number:"+sum);
}
}


Previous Code:-
Increment operator

List Code:-
Java codes

Next Code:-
for loop

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top