Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how does a post increment operator act in a return statement?

Tags:

java

operators

Given the following code, will ixAdd do what you'd expect, i. e. return the value of ix before the increment, but increment the class member before leaving the function?

class myCounter {
    private int _ix = 1;

    public int ixAdd()
    {
        return _ix++;
    }
}

I wasn't quite sure if the usual rules for post / pre increment would also apply in return statements, when the program leaves the stack frame (or whatever it is in Java) of the function.

like image 965
Hanno Fietz Avatar asked Mar 17 '09 15:03

Hanno Fietz


People also ask

Can you use a return statement with a ++ in Java?

a++ returns the value of a before it was incremented. Show activity on this post. From the java doc: The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.

How does post increment work in Java?

The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one. if the expression is a = b++; and b is holding 5 at first, then a will also hold 5.

What does i ++ return in Java?

What is Postfix Operator in Java. In Postfix increment, the ++ operator appears after the variable, i.e., “i ++”. The post-increment operator first, returns the variable's original value, and afterward, increments the variable's value by 1.

What is post increment operator?

2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;


1 Answers

The key part is that a post increment/decrement happens immediately after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated. For instance, suppose you wrote:

class myCounter {
    private int _ix = 1;

    public int ixAdd()
    {
        return _ix++ + giveMeZero();
    }

    public int giveMeZero()
    {
        System.out.println(_ix);
        return 0;
    }
}

That would print out the incremented result as well, because the increment happens before giveMeZero() is called.

like image 175
Jon Skeet Avatar answered Oct 29 '22 15:10

Jon Skeet