Answer the question
In order to leave comments, you need to log in
How to work with pre-increment and post-increment correctly?
I can not understand in any way how to work with these operators
int i = 2;
i = i++;
System.out.println(i); // 2
i = i++;
System.out.println(i); // 2
int j = 7;
j = ++j;
System.out.println(j); //
8j = ++j;
System.out.println(j); // nine
Answer the question
In order to leave comments, you need to log in
int i=3;
int a=i++; //a=3
int b=i; //b=4
int i=3;
int a=++i; //a=4
int b=i; //b=4
Why are you assigning values
? Everything works correctly.
Post-increment increments by one but returns the original value
Pre-increment increments by one and returns the new value
int t = 1;
System.out.println(++t); //2
int e = 1;
System.out.println(e++); //1
System.out.println(e); //2
The main difference between the post-increment and pre-increment operators is as follows:
In post-increment, the calling code first gets the value of the variable, and then the value of the variable is incremented by one.
In a pre-increment, the value of the variable is incremented at the beginning, and then the calling code gets the value of the variable.
Post-increment:
int x = 0;
while(x != 5) {
System.out.println("post " + x++);
}
int x = 0;
while(x != 5) {
System.out.println("pre " + ++x);
}
post 0
post 1
post 2
post 3
post 4
pre 1
pre 2
pre 3
pre 4
pre 5
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question