• 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

Object Initialization

 
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following piece of code prints out "Counter = 0". I just cant figure this out. I thought it would have printed "Counter = 1". Could someone please explain this?


public class A {

private static int counter;

public A() {
System.out.println("Counter = " + getCounter());
}
public static int getCounter(){
return counter++;
}

public static void main(String[] args) {
A a1 = new A();
}
}
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the difference between these two methods...
 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at this statement

return counter++;

What this will do is increment the value of counter after the statement is executed. Its called postfix operator. So after this statement is executed the value of counter is 1 (which is what you are thinking), but it returns counter as 0 to calling method.
[ March 07, 2006: Message edited by: Jay Ashar ]
 
david allen
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,

I really do know this rule and I am very suprised it caught me out. I think it was the fact that it was on the return statement that did it.

thank you
david
reply
    Bookmark Topic Watch Topic
  • New Topic