• 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 variables and where they are stored

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello friends,
in the K&B book for 1.4 page 99 it says that "static variables,too,can be accessed without having an instance of a class .But if there are instances, a static variable of a class will be shared by all instances of that class;there is only one copy"
can anyone please explain the meaning of the above lines to me? especially,what they mean by having only one copy,do they mean the different instances using them have their own copy of the variable with the master copy in the memory like the volatile instance variables.
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What they really mean in K&B is this ,

Forget abt where the static variable is stored ,
just remmeber that there is only one copy and there are several ways
to access it

Consider the following ,

class Static
{
static int a;
{
public static void main(String args[])
{
System.out.println(a); //prints 0
System.out.println(Static.a); //prints 0
System.out.println(new Static().a); //prints 0

///this is my favorite

Static variable =null;

System.out.println(variable.a); //prints 0 , no NullPointerException!!!

Static var1=new Static();
Static var2=new Static();
var1.a=10;
var2.a=20;

////this proves that there is only one copy

System.out.println(var1.a); //prints 20

}}

Again , there are several ways to refer to a static variable
but there is only copy

Hope i hav cleared ur doubt

santhosh sharma (scjp 1.4 100%)
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic