K
K
koshiii2014-08-29 14:45:31
Java
koshiii, 2014-08-29 14:45:31

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

4 answer(s)
X
xmoonlight, 2014-08-29
@xmoonlight

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

M
Max, 2014-08-29
@AloneCoder

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

F
Flasher, 2014-08-29
@Flasher

int t = 1;
System.out.println(++t); //2
int e = 1;
System.out.println(e++); //1
System.out.println(e); //2

I
IgorBond, 2014-08-30
@IgorBond

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++);
        }

Pre-increment:
int x = 0;
        while(x != 5) {
            System.out.println("pre " + ++x);
        }

Conclusion:
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 question

Ask a Question

731 491 924 answers to any question