++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
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 0 ;
System.out.println( "Post-Increment" );
System.out.println(i++);
int j = 0 ;
System.out.println( "Pre-Increment" );
System.out.println(++j);
}
}
|
OutputPost-Increment
0
Pre-Increment
1
Example 2: Cannot apply the increment operator (++) on a constant value
Java
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