Static Keyword
Methods and variables defined inside the class are called instance methods and instance variables, that is, a separate copy of them is created upon the creation of each new object. But sometimes, it becomes essential to create a member that is common to all the objects and accessed without using any specific object. It's the situation where we need the Static keyword.
What is the Static keyword and why do we use it?
The static keyword is used to declare members that belong to the class itself rather than to any individual instance of the class. A member declared as Static is shared among all the instances of the class and can be accessed directly by the class name i.e. without the need to create the object of the class.
We can declare both members and variables as Static.
Static variables
Static variables, also known as class variables, are the members that are associated with the class itself rather than any instance of the class. They can be accessed directly with the class name, just use the dot operator " . " between the name of the class and the static variable.
Format for declaring a variable as Static:
static dataType variableName;
In this statement, static refers to the keyword, dataType refers to the type of primitive datatype and variableName refers to the name of the desired variable. For example:
static int num;
where static is the keyword, int is the datatype and num is the name of the variable. When a static variable is not initialized they are initialized to its default values.
These variables are shared among all the instances of the class, i.e. if the value of any static variable is modified by one object, it is reflected in all the objects of the class.
Static method
Just like the static variables, the static methods are also directly associated with class i.e. they do not depend upon the object for being accessed. They can be invoked directly with the class name.
Static methods can directly access only the static members of the class, for accessing the non-static members (or variables) they need to create an object of the class.
Format for declaring a method as Static:
accessSpecifier static returnType methodName(parameters);
For example:
public static int num( int n1 );
In this static is the keyword, public is the access specifier, int is the datatype of the variable being returned and num is the name of the method.
Static methods can invoke only other static methods and also they can access only static data members.
Why the main method is always declared as static?
A method that is not declared as static can not be accessed without the creation of an object and main
is the first method to be executed. So, we do not declare the main
function as static it would not be called automatically on execution of the class and we would first need JVM to create an object for the class and this would not be a memory-efficient process, as it would be taking extra memory.