• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem in understanding output...

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
reply
    Bookmark Topic Watch Topic
  • New Topic