Static Keyword
Is used to define class members.
In a class we can have following 3 types of class members:-
- STATIC DATA MEMBERS
- STATIC INITIALIZE BLOCK
- STATIC METHODS.
(1) STATIC DATA MEMBERS
Represents class
attributes. A single copy of static data members is created when the class is
loaded. This copy can be shared by all the objects of the class.
For example -
- class A
- {
- int a, b;
- static int c;
- -------
- -------
- }
When we create objects of this class in some other class what
happens is explained in the given adjoining fig1.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpzm0ANndOtINxVSYnxtn3PH91GuOB9TkcIhlR0qVb0IvL9HdkA_DUEXLVxJm87H1XYA4YielPBmgYOKqD13ug4-qJ0yU2b1_1nEAFXJgkCt0JbAOrXADS6jxM7iaogwr76I5izAhi9N5v/s1600/uptuexam_core_java.png)
Fig1.
For
the execution of a Java Application, memory is divided into three parts called
·
Stack
- LOCAL VARIABLES of methods are stored in STACK.
·
Heap
- OBJECTS are created in the HEAP.
·
Class
Area - STATIC DATA MEMBERS are saved
in CLASS AREA.
(3) STATIC METHODS.
- class A{int a, b;static int c;--------------------public static void main(String[] args){A x = new A();A y = new A();--------------------------}}
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjbFl67ZxXSLazkWoZDHn3FQMkXnp0azQ845lpx8ltehTYgFhFCD0wD4grT-5aXYy9NwpEeCJwJcK4Nsa9yI5dhLAhYzB1JrSiVf5H06-1LoeMJoE7-8AgIJTLheWkqtA60BmIPoYuj8ma/s1600/uptuexam_core_java.png)
Memory Representation
During the execution of main() method of class A.
Static
Initializer Block- is used to initialize static
data members of a class.
Syntax
–
static
{
Statements
}
Static initialize is executed only once, just after a class is loaded.
In Java, a class can be loaded in either of the following ways:-
(1). Through Explicit Introduction.
(2). Through Implicit References.
In the first approach class to be loaded is explicitly introduced to the JRE.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGhGofhoOKK7_2QZdE2lcF1dyPlMWHDuRg9-ahnfzrVyB_2cTqvPWtHNT5zVcaOdHDRjOiZLqmHZ_PE11RhRvOQuhiUn026XeaR9kxCDyBgZz7mHY9hu9rHgkWMLYVN10Kz-FHeztCg3dR/s1600/uptuexam_core_java.png)
Only a single class is loaded in an application using explicit introduction. Rests of the classes are loaded through implicit reference.
When a reference of a class is encountered first time in an already loaded class then JRE implicitly loads it before performing the operation represented by the class reference.
- class A
- {
- public static void main(String[ ] args)
- {
- B x = new B();//Reference of B is contained in A
- -------------
- -------------
- }
- }
- class B
- {
- -------------
- -------------
- }
No comments:
Post a Comment