It's not a secret anymore!
The moose likes Java in General and the fly likes initialization of variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "initialization of variables " Watch "initialization of variables " New topic

initialization of variables


Joined: Jan 28, 2000
Posts: 3
can the instance and static variables be initialized at definition time.the confusion is ,since the class is only a structure(template)and doesn't take space in memory .so where does it stores the data.


class ex{
int a=10;
be yourself

be yourself
paul wheaton

Joined: Dec 14, 1998
Posts: 20972

Each time you create a new class, memeory is set aside on the heap to store the attributes (instance variables) of the new object.
Right after the memory is allocated, all of the attributes are initialized to something. Then the constructor is called.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Doug Gschwind
Ranch Hand

Joined: Dec 17, 1998
Posts: 44
To expand this further, I imagine that the class variables are stored with the loaded Class instance, where as the instance variables are stored with the instances of the class on the heap as Paul described.
Class variables, those with the static keyword can be initialized at declaration time or within the static {} block. The static block is a special block of code that is executed, if it exists, after a class has been loaded and before the first instance is constructed. Thus, a class variable x can be initialized with private static int x = 5; or via the following:
class SomeClass
private static int x;
// This block gets executed after
// the class has been loaded but
// before any instances have been
// created.
x = 5;
Instance variables can be initialized in one of three places: at declaration, within the instance initialization block, or within a constructor itself. At declaration, this means private int x = 5;. The instance initialization block is another special block of code that is executed, again if it exists, as part of the construction of an instance of a class. I cannot remember if the instance initialization block is executed before or during the constructor being called, but it can be done as follows:
class SomeClass
private int x;
// instance initialization block.
x = 5;
Then of course, the initialization within a constructor is very straightforward.
I agree. Here's the link:
subject: initialization of variables
It's not a secret anymore!