HomeLanguagesJavaWhat is the Difference Between i++ and ++i in Java?

What is the Difference Between i++ and ++i in Java?

++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator.

Increment in java is performed in two ways,

1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1.

2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.

Example

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4

Example 1

Java




// Java program to demonstrate pre and post increment
// operators
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // initialize i
        int i = 0;
        System.out.println("Post-Increment");
  
        // i values is incremented to 1 after returning
        // current value i.e; 0
        System.out.println(i++);
  
        // initialized to 0
        int j = 0;
        System.out.println("Pre-Increment");
  
        // j is incremented to 1 and then it's value is
        // returned
        System.out.println(++j);
    }
}


Output

Post-Increment
0
Pre-Increment
1

Example 2: Cannot apply the increment operator (++) on a constant value

Java




// Applying increment operator on a constant value
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        int x = ++10;
  
        System.out.println("Hello");
    }
}


Output

prog.java:8: error: unexpected type
          int x = ++ 10;
                     ^
  required: variable
  found:    value
1 error
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS