18 Oct 2022
18 Oct 2022
The static variable can be used to refer the common property of all objects.(eg:
company name of employees).
In java applications it is possible to access the static variables either by using the
respective class object reference (or) by using respective class name directly.
Static variables never be ‘local variables’.
Static block and static variable will have equal priorities, so these execute in
defined order.
If a static variable and a local variable is having same name, Then compiler will
first search for local variable and then static variable.
For the static variables it is not required to perform
initialization explicitly jvm will always provide default
values.
If we declare a static variable as final then 100% we
should perform initialization explicitly whether we are
using or not otherwise we will get compile time error.
For final static variables JVM won't provide any default
values, JVM will provide default values only for static
variables.
Final static variables can be initialized inside a static
block. (any where else we will be getting compile time
error)
Static Method
If you apply static keyword with any method, it is known as static method
A static method can be invoked without the need for creating an instance of
a class.
static method can access static data member and can change the value of it.
In java applications it is possible to access the static methods either by
using the respective class object reference (or) by using respective class
name directly.
Restrictions for static method:
➢ The static method can not use non static data member or call non-static
method directly.
Static Method Vs Instance Method
Static Method Instance Method
A method i.e. declared as static is known as A method i.e. not declared as static is
static method. known as instance method
Object is not required to call static method. Object is required to call instance methods.
Non-static (instance) members cannot be static and non-static variables both can be
accessed in static context (static method, accessed in instance methods.
static block and static nested class) directly.