Static keyword in java
Static is a non-access modifier in Java . When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.
When a variable is declared as static, then a single copy of variable is created and shared among all objects at class level. We can create static variables at class-level only. Static block and static variables are executed in order they are present in a program.
When a method is declared with static keyword, it is known as static method. The most common example of a static method is main ()method. They can only directly call other static methods. They can only directly access static data.
Use the static variable for the property that is common to all objects. For example, in class Student, all students shares the same college name. Use static methods for changing static variables.
The static keyword is used in java mainly for memory management.It is used with variables,methods,blocks and nested class.It is a keyword that is used to share the same variable or method of a given class.This is used for a constant variable or a method that is the same for every instance of a class.The main method of a class is generally labeled static.
No objects needs to be created to use static variable or call static methods,just put the class name before the static variable or method to use them.static method can not call non static method.
In java language static keyword can be used for following:
1.variable(also known as class variable).
2.Method(also known as class method).
Static variable:If any variable is declared as static then it is known as static variable.
->static variable is used for fulfilling the common requirement.For example:company name of employees,college name of students etc. Name of the college is same for all students.
->The static variable allocate memory only once in class area at the time of class loading.
Advantage of Static variable:Using static variable we make our program memory efficient(i.e.It saves memory).
syntax for declaring static variable:
public static variableName;
syntax for declaring static method:
public static void methodName()
The static keyword is used when a member variable of a class has to be shared between all the instances of the class.
All static variables and methods belong to the class and not to any instance of the class.
We can access static variables without creating an instance of the class.As they are already available at class loading time, we can use them in any of our non static methods.
We cannot use non static methods and variables without creating an instance of the class as they are bound to the instance of the class.They are initialized by the constructor when we create the object using new operator.