Elementary Static Variable question

OK, I guess this is a pretty basic question but I'm asking it anyway.

Say I have a class (Class1) that contains a few static variables and a static method to initialize them all to default values.

Can I then manipulate these variables in other classes (Class2 and Class3), without ever creating an instance of Class1? I understand that static means the value remains consistent across all instances of a Class. But if the class has not been instantiated, can the values really be stored in and accessed from the variables contained in that class?

So, basically, can I replace:

Class1 spiffy = new Class1();

spiffy.InitializeValues();

a = spiffy.var1;

With:

Class1.InitializeValues();

a = Class1.var1;

[763 byte] By [thespiffa] at [2007-11-27 10:23:08]
# 1

yes

anamea at 2007-7-28 17:20:11 > top of Java-index,Java Essentials,Java Programming...
# 2

Just to expand a little on "Yes":

It's not so much that static members are consistent across all instances, more that they do not belong to any instance at all. They belong to the class itself. As a by-product, they appear to be consistent across all instances, but if you're accessing a static member through an instance, that's the wrong way to do it

georgemca at 2007-7-28 17:20:11 > top of Java-index,Java Essentials,Java Programming...
# 3

> Can I then manipulate these variables in other

> classes (Class2 and Class3), without ever creating an

> instance of Class1?

Yes. First time you mention Class1 in your code, Class1 gets loaded by jvm. Jvm finds and loads Class1.class into its internal representation of a class. In this process, static variables of Class1 get storage alocated to them, and they can be used by the rest of the program.

boruthadzialica at 2007-7-28 17:20:11 > top of Java-index,Java Essentials,Java Programming...
# 4

"georgemc ": he asked 1 question

So, basically, can I replace:

and the answer is yes :)

maybe I should have explained it little bit more :)

anamea at 2007-7-28 17:20:11 > top of Java-index,Java Essentials,Java Programming...
# 5

Haha,

A "yes" or "no" was all I requested, but I do appreciate the other responses.

I'm bored at work right now, so I'm cleaning up warnings in code that I inherited from somebody else. If I had written the code myself, I would have seen the warning and written it the correct way from the start. But since I didn't write the code...I wanted to make sure the wasn't a good reason for the other guy to do things the way he did. In the interest of not breaking things.

thespiffa at 2007-7-28 17:20:11 > top of Java-index,Java Essentials,Java Programming...
# 6

> I'm bored at work right now, so I'm cleaning up

"All work and no play makes Jack a dull boy"?

anamea at 2007-7-28 17:20:12 > top of Java-index,Java Essentials,Java Programming...