• 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

Static

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



Output of Line 1 is 0. :roll:
I thought it would be NullPointerException..

Help ..
 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
static keyword means that decleration is part of the class not the object, so you can invoke getM() by calling staticFun.getM() or by simply calling getM() because you are inside the class.

you can access getM() by ref pointing to staticFun, like this
new staticFun().getM(), but this cause irreadable code, you shouldn't do this.

and because all attributes initialized with 0 in java when class is loaded in case of static attribute, or when object is instantiated for instace variables. so the output is 0

hint:
static have nothing to do with instace, it works on the ref type. so there is no chance to have nullPointerException.
you may be just miss to read "static"

you will find 1000 tutorial on the web for static context.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ranchers,

Two remarks, first:
static members (both variables and methods) can be accessed through an instance of the class,
even if the instance is null:

prints twice "Hi Nishant!", no exceptions.


However it is bad coding style to do so. Static members should be accessed through the class name.



Second:

in the original code from Nishant, there would be also no null pointer exception, if the variable a was not static. The method returns a new instance of staticFun. And this instance is not null, even though it is not referenced by any variable.



Yours,
Bu.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic