Java ‘Static’ Key Word

Dhanuka lakshan
2 min readOct 28, 2020

Java static key word use for memory management mainly.The static key word can be use Classes,methods,varibles and block.These are all built into the class template.We can’t to use ‘super’ and ‘this’ key word static context.Super key word invoke the parent class construcor. ‘this’ key word invoke the own varaibles,methods and own constructor.We can invoke the static methd without Object.super key word invoke only non-static things.Totally non-static variable ‘super’ cannot be referenced from a static context. this and super key words applies class of instance.

We can execute the java class with out main() method using static block.But it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main() method.

class Demo{
static{
System.out.println("I am a static block..");

}
}
Result:
/usr/lib/jvm/jdk1.8.0_261/bin/java
Error: Main method not found in class Demo, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Static method and static variable can be execute the static context.

class Demo{
int a=10;
static int b=20;
private static void method1(){
System.out.println("I am static method.."+b);
}
private void method2(){
System.out.println("I am non static method.."+a);
}
public static void main(String[] args) {
method1();

}
}
Result:
I am static method..20
But we can execute the non static variable and method using object.class Demo{
int a=10;
static int b=20;

private static void method1(){
System.out.println("I am static method.."+b);
}

private void method2(){
System.out.println("I am non static method.."+a);
}
public static void main(String[] args) {
Demo d = new Demo();
d.method2();
d.method1();

}
}

If you use the static key word for variable.Java 8 interface changes default method and static method.

interface Dog{
static void eat(){
System.out.println("Dog is eating..");
}
}

class Demo implements Dog{
public static void main(String[] args) {
Dog.eat();
}
}
Result:
/usr/lib/jvm/jdk1.8.0_261/bin/java
Dog is eating..

If you need to do the computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded.Static Variable can be accessed directly in a static method.Nested static class doesn’t need reference of Outer class.A static class cannot access non-static members of the Outer class.

--

--

Dhanuka lakshan

I’m a Software engineering student who is currently studying @Institute_of_Java And Software Engineering(IJSE), I like coding and learn about new tech.