Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Demonstrate pre/ post increment operators better #149

Open
Locust1 opened this issue Apr 5, 2025 · 1 comment
Open

Demonstrate pre/ post increment operators better #149

Locust1 opened this issue Apr 5, 2025 · 1 comment

Comments

@Locust1
Copy link

Locust1 commented Apr 5, 2025

The second code snippet from the Unary section does not illustrate the core difference between the pre and post increment operators well (++i vs i++):
https://dev.java/learn/language-basics/using-operators/#unary

Both
System.out.println(++i);
and
System.out.println(i++);
produce the same output so it might be confusing as to what is the actual difference.

I would suggest replacing it with something along the lines of

int i = 3;

i++;
// prints "i = 4"
System.out.println("i = " + i);

++i;
// prints "i = 5"
System.out.println("i = " + i);

int j = ++i;
// prints "i = 6"
System.out.println("i = " + i);
// prints "j = 6"
System.out.println("j = " + j);

int k = i++;
// prints "i = 7"
System.out.println("i = " + i);
// prints "k = 6"
System.out.println("k = " + k);
@danthe1st
Copy link
Contributor

danthe1st commented Apr 5, 2025

Alternatively (instead of introducing two new variables), it might be a good idea to change the comments to include how the operators change the variables.
Something along the lines of the following (I'm just showing the idea, there's probably a better text for these things):

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        // prints 4
        System.out.println(i);
        ++i;               
        // prints 5
        System.out.println(i);
        // sets i to 6 and prints 6
        System.out.println(++i);
        // sets i to 7 and prints 6
        System.out.println(i++);
        // prints 7
        System.out.println(i);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants