static is a keyword in java which is used very often in java programs. Sometimes beginners faces difficulty to understand what exactly the static
keyword does and why to use this. This tutorial explains different usage of static keyword and also covers different questions like when, how and why
do we use static keyword in java.
Generally you need an object of a class to access members like variables and methods of that class, because these members belongs to object or instance of that class. Each object have their
specific values for such members. But sometimes we need members that should belong to class rather than objects and should be same for all the objects. To achieve this java provides
static keyword. static members belongs to class not objects. You can access such members using class name itself rather than objects.
Let's see the different usage of static keyword.
staticvariablestaticmethodstaticblockstaticinner class
In this tutorial we will discuss about static variable and static method only. For static block refer
initializer blocks tutorial and for static inner classes refer inner classes in java tutorial.
Apart from this there is static import in java which also uses static keyword, refer package import tutorial for
static import in java.
Java static variable
A static variable is similar as normal variable except that it has a static keyword in it's declaration.
static variables are also called as class variables as these variables belongs to class not objects. These variables must be created inside
class but outside any method or block. If you create static variable inside any static or non-static
method or block, compiler will throw compilation error. The basic syntax of declaring a static variable is :
classclassName { access_modifierstaticdataType varName; access_modifierstaticdataType varName = value; } Example :classStudent {staticinttotal;public staticString collegeName ="SUMVS"; }
The access modifier of static variable can be public, protected, private or default(no modifier). The access modifier
decides visibility/accessibility of the variable within or outside the class. The data type of static variable can be primitive or non-primitive data type.
The name of variable is given by the programmer. The value of
static variable can be given while declaration or later in program. If static variables are not initialized with any value,
java will assign a default value as per their data type.
Static variable memory allocation
As soon as java virtual machine loads your class inside memory,
static variables of your class
are created inside the heap memory and it's created only once, it's not created separately for each object unlike instance variables.
As soon as the execution of your program finishes, static variables are removed from memory.
static variables belongs to class and is common to all objects of a class. There is only one copy of static variable available
that is shared with all the objects of that class, if changes are made to that variable value using one object, all other objects will also see the effect of changes.
The image below shows how two objects obj1 and obj2 of Student class shares a
static variable collegeName which is created only once.
How to access static variable in Java
Since static variables belongs to class, it can be accessed using class name as className.staticVarName.
You can also access static variable using object of a class as objName.staticVarName but you should prefer to access
static variable using class name as static variables belongs to class not objects. You can access static
variables inside static or non-static methods or blocks.
You can access static variables directly inside your class but outside the class(in other classes) you must need class name or object name to access the
static variables of a class.
Static variable program in Java
classStudent {staticinttotal = 40;staticString collegeName ="SUMVS"; }classStaticVarDemo {staticString test ="Testing static variable";public static voidmain(String [] args) { System.out.println(test+", "+ StaticVarDemo.test);// Accessing Student class static variablesSystem.out.println("Total students ="+ Student.total); System.out.println("college name ="+ Student.collegeName); } }
Output:
Testing static variable, Testing static variable
Total students = 40
college name = SUMVS
When to create static variable ?
You should create a static variable when you need a variable that should be same for all the objects of a class or in other way you need a variable that is
not different for each objects. For example a Student class can have a static variable as collegeName,
since it will be same for all the students of a college while variables like name, age, rollNo etc can be declared as instance variables since
these will be different for each students.
Static method in Java
static method is similar as normal method except that it has a static keyword in it's declaration.
The basic syntax of declaring a static method is :
access_modifierstaticreturn_type methodName(DataType param1, DataType param2 ...) {// one or more line of codereturnsome_value;// Needed if return_type is not void} Example :public staticintgetArea() {// one or more line of codereturnsome_value; }staticvoidcalculateVolume(doubleradius) {// one or more line of code}
The access modifier of a method can be public, protected, private or default(no modifier). The access modifier of a method decides visibility/accessibility of a method
within or outside the class. The return type of a method can be
primitive or non-primitive data type. If the method doesn't return a value, it's
return type must be void. The name
of method is given by the programmer. Parameters are optional, a static method may or may not have parameters.
How to access static method in Java
Since static method belongs to class, you can access them using class name as className.methodName(). You can also access
static method using object as objName.methodName() but you should prefer to access using class name as static
method belongs to class not objects. Static method can not access non-static variables or methods directly inside it's body, doing so will result in compilation error. You can create and access
local variables inside static method as you do in normal methods.
You can access static methods directly inside your class but outside the class(in other classes) you must need class name or object name to access the
static methods of a class.
Static method program in Java
classStudent {static inttotal = 50;staticString collegeName ="SUMVS";public static voidprintDetail() { System.out.println("total students = "+ total); System.out.println("college name ="+ collegeName); } }classStaticMethodDemo {intcount = 20;staticString test ="Learning static method";public static voidmain(String [] args) { StaticMethodDemo.testMethod();// testMethod(); // Can access testMethod directly as well.Student.printDetail();// Calling printDetail method of Student class// printDetail()// Can't access other class static method directly.}static voidtestMethod() {// count = count+2;// Static method can't access non-static variablesintnum = 30; System.out.println(test+", num = "+num); } }
Output:
Learning static method, num = 30
total students = 50
college name = SUMVS
When to use static methods in Java
There are not any defined rules but there are some observations that can be used to create static methods.
- You want to call method without creating instance of that class.
- If the method doesn't need to access/modify instance variables.
- If the method works only on arguments provided to it. For eg.
, this method only operates onstaticintfactorial(intnumber)numberprovided to it. - If it's a kind of utility method. For eg. built-in methods of
Mathclass likelog10(etc. These are utilities that performs common operations, it doesn't require any object states.doublea), sqrt(doublea), cbrt(doublea)


