The static
keyword in Java is a non-access modifier (keywords used to provide additional functionality such as synchronization etc), used primarily for memory management. The keyword static
is used to refer to the common property of all objects.
The static
keyword can be applied to variables, methods, blocks, and nested classes:
A static variable can be created by adding the static
keyword before the variable during declaration.
static datatype variable-name
Using a static variable will create one copy of the count variable which will be incremented every time an object of the class is created.
class Counter {static int count = 0;Counter(){count ++;}public void getCount() {System.out.printf("Value of counter: %d \n", count);}public static void main( String args[] ) {Counter c1 = new Counter(); //count incremented to 1c1.getCount();Counter c2 = new Counter(); //count incremented to 2c2.getCount();Counter c3 = new Counter(); //count incremented to 3c3.getCount();}}
All objects of the Counter class will have the same value of count at any given point in time.
Note:
static
variables can be created at class level only- A
static
variable is allotted memory once
public class foo {public static void foo2(){//code}}
class Citizen {static String country;Citizen() {country = "Pakistan";}public static void setCountry(String c) {country = c;}public void getCountry() {System.out.printf("Current country: %s \n", country);}public static void main( String args[] ) {Citizen c1 = new Citizen();Citizen c2 = new Citizen();Citizen c3 = new Citizen();c1.getCountry();c2.getCountry();c3.getCountry();Citizen.setCountry("USA");c1.getCountry();c2.getCountry();c3.getCountry();}}
Note:
static
methods cannot use this or super keywords- Abstract methods cannot be
static
static
methods cannot be overriddenstatic
methods can only accessstatic
variables and otherstatic
methods
static {//code}
class Foo {static int a;static int b;static {a = 10;b = 2 * a;}public static void main( String args[] ) {Foo foo = new Foo();System.out.printf("a = %d\t b = %d ", foo.a, foo.b);}}
Note:
- There can be multiple
static
blocks in a class
The static
nested class can be accessed by the outer class without creating an object of the outer class.
class OuterClass {static class InnerClass {//code}}
class OuterClass {static String message = "Hello World!";static class InnerClass {static void getMessage(){System.out.println( message );}}public static void main( String args[] ) {OuterClass.InnerClass.getMessage();}}
Note:
- A
static
nested class cannot access instance variables and methods of the outer class without the object’s reference- A
static
nested class can access allstatic
variables and methods of the outer class- In Java, the outer class cannot be
static
In Java, the main
method is always static
because it is executed before creating an instance of the class which contains the main
method.
Free Resources