what is the output? (wrt to post increment operator)
Forum » SCJP2 Discussion / operators » what is the output? (wrt to post increment operator)
Started by: itsraghzitsraghz
On: 1184053522|%e %b %Y, %H:%M %Z|agohover
Number of posts: 1
rss icon RSS: New posts
Summary:
post increment operator in method return value
what is the output? (wrt to post increment operator)
itsraghzitsraghz 1184053522|%e %b %Y, %H:%M %Z|agohover

What is the output of the below program?

public class Increment 
{
   public static int getNum(int x) 
   {
       return x++;
   }
   public static void main(String[] args) 
   {
      System.out.println(getNum(44));
   }
}

The options for the answers are :

(a) 44
(b) 45
(c) 46

Output:

The answer is :

(a) 44

Reason with Explanation by Henry:
When the getNum() method calculates to value to be returned, it will use the value of x before it gets incremented (post increment means the value of x will be incremented after it has been used).

Sure, the value of x will be incremented, but the value to be returned has already been calculated by then.

Reason with Explanation by me:
Its more or less the same of assignment.

When you have

int x = 2;
int y = x++;
System.out.println("x = "+x+", y = "+y);

The above SOP will print the value as:

x = 3, y = 2

Why? and How? The value of x is being used in the operation first (ie., assignment). After the appropriate operation (here assignment) is done, the value of x is incremented! Right?

The same holds good in terms of your method as well. The value of x is being used for its operation (here, return value) first and then its incremented. But that does NOT mean that the updated value of x (incremented here) will be reflected back because the updation happens only after the value of x is being used (returned).

Hope this helps!

unfold what is the output? (wrt to post increment operator) by itsraghzitsraghz, 1184053522|%e %b %Y, %H:%M %Z|agohover
New post
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.