Mobile Ad-Hoc Networks
Structured Query Language(SQL)
Let's Test Out
C Programming Language
HTML & CSS
STATIC KEYWORD JAVA
Static Keyword In JAVA | Core Java Tutorial | Minigranth
Features of Java
First Java Program
Executing Java Program
Comments In Java
Java Data Types
Operators In Java
Loops In Java
Arrays In Java
Command Line Arguments
Recursion In Java
OOPs In Java
Classes, Methods & Objects
Inheritance In Java
Dynamic Method Dispatch
Abstraction In Java
Encapsulation In Java
Packages In Java
Strings In Java
Java String Programs
Static Keyword : Introduction
There will be time when you want a class member to be common to all the object of the class, i.e. all the objects of the class will share that member.
Here static keyword comes into play.
To access any member of the class it is done by using object with
But static keyword before any
member makes it independent of the object.
Static Keyword : The Discussion
Static keyword can be applied to:
Let us discuss them one by one along with their respective syntax and examples.
A variable preceded with static keyword is called
. Static variable is common to all class objects.
Static variable is independent of the objects hence is accessed using class name rather then object name.
The above diagram show that static variable a is common to all objects of a class.
Static Variable : Example
Static Variable : Output
As we can see that value of static variable is common to all objects and it is not
when accessed again.
The most common example of static method we have seen till now is the
Static methods are those methods which are made static by preceding them with static keyword. Static methods access static data only.
Static methods are invoked using class name rather than object name.
There are some
that are applied to static methods, such as :
Static methods always access static data. They can’t access non-static data.
This keyword cannot be used with static method.
Super keyword cannot be used with static method.
Let us take an example of static method.
Static Method : Example
Static Method : Output
Static block is used to initialize static variables. Static block is always executed before main block.
Let us take an example of static block and see if it executes before main block.
Static Block : Example
Static Block : Output
We can see in the output that the static block is executed before main block and the static variable a is assigned value before