Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in understanding output...

 
gylph knor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
System.out.print(i);
}
}



Output : 1,0




Thank You.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12087
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Fairhurst
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic