This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Problem in understanding output... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem in understanding output..." Watch "Problem in understanding output..." New topic

Problem in understanding output...

gylph knor

Joined: Jun 12, 2008
Posts: 20
Can anybody please explain me, how the output is being generated in this program?

class C{

static int f1(int i) {
System.out.print(i + ",");
return 0;

public static void main (String[] args) {
int i = 0;
i = i++ + f1(i);

Output : 1,0

Thank You.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11923

on this line:

i = i++ + f1(i);

first, we evaluate i. it is 0.
then, we increment it, making it 1.
we pass 1 to the method.

The method prints "1,", and returns 0.

we now add 0 and 0, giving 0.

we set i to 0.

we print i.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Paul Fairhurst

Joined: Jun 12, 2008
Posts: 7
In the main(), this line

i = i++ + f1(i);

will become

i = 0 + f1(1);

The i++ is post incrementing thus become zero for the assignment.
It it were pre incrementing as ++i then it would become one (i = ++i + f1(i); becomes i = 1 + f1(1)

The f1(i) is a new phrase of the assignment and takes the current value of i, now incremented to 1. If you output i in f1() you will see this.
[ June 13, 2008: Message edited by: Paul Fairhurst ]

<a href="" target="_blank" rel="nofollow">infoQuanta</a> - parallel java programming made simple
I agree. Here's the link:
subject: Problem in understanding output...
It's not a secret anymore!