Static keyword in java
can be used for following three scenarios:
1. Class variables
2. Methods
3. Block of code
Static data members:
Static data members (variables) are
the variables which are to be used at class level. These are defined in a class
outside any method, block or constructors with the keyword “static”. These are
common to the entire class and only one copy will be available irrespective of
how many objects will be created. Static variables will be stored in static
memory. These are created when the program starts and destroyed when the
program stops.
Syntax:
Public static String
str1;
Or
Static public
String str1;
They can be accessed as beow:
ClassName.variableName;
Methods:
Just like
static variable, static method is a method which is common to the entire class.
Static methods are called directly using class name. These cannot be accessed
using any object reference. Static methods cannot access any non static member
of the class while other methods/blocks can use static methods.
Syntax:
Public static Integer
getTotal()
They can be accessed as below:
ClassName.methodName();
Static Blocks:
The static block is a block of
code inside a class which will be executed when a class is first loaded. Static
block is used to initialize the static members of the class just as constructor
helps in initializing the instance members.
Syntax:
Class Sample
{
Static
{
// code to be written
}
}
Important point:
When to use static and when not:
Statics are used when data is
not instance dependent and same state is needed for the static data for all
instances to be created. Static should be used only when they are actually required
reason being, as they create dependencies and references to other classes and
class loaders in JVM and they stay in memory for longer time. They won’t be
considered for garbage collection when they are done with current work as they
have to be de-referenced with their loading classes.
Example for static variables, static method and static
block:
package test;
public class StaticSample
{
//declaring static variable to have count of objects
private static int count = 0;
//constructor to increase count
public StaticSample()
{
count++;
}
//static
block which will be called at first time class is loaded
static
{
System.out.println("in static
block");
}
//static method
public static void printCount()
{
System.out.println(" Count value
: " +count);
}
}
//Main
class to see how static works.
package test;
public class MainClass
{
public static void main(String[] args)
{
static Sample sam1 = new
StaticSample();
static Sample.printCount();
static Sample sam2 = new
StaticSample();
static Sample.printCount();
}
}
The result for above
program would be as below:
in static block
Count value : 1
Count value : 2
No comments:
Post a Comment