Increment operators in java with example

The increment operators used to adds 1 to previous value. Increment operator is unary operator because only one variable is used.

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

Syntax:-

For postfix

variable++

For prefix

++variable

Both prefix and postfix increment operator are same thing when they used independently(i++ or ++i) ie adds 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 increment operator:-


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

Output:-

i=2
num=1

Execution:-

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

Here in our example first i is zero(i=0) than i increment by 1(i++). here i value is 1.

Next statement is num = i++;

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

Prefix increment operator


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


Output:-

i=2
num=2

Execution:-

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

Here in our example first i is zero(i=0) than i increment by 1(++i). here i value is 1.

Next statement is num = ++i;

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

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=0;i<=num;i++)
{
if((i%2)==0)
continue;
else
sum=sum+i;
}
System.out.println("Sum of odd number:"+sum);
}
}


Previous Code:-
else if statement

List Code:-
Java codes

Next Code:-
Decrement operator

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top