DEV Community

Saravanan B
Saravanan B

Posted on

Core Java-Static keyword

Public class HelloWorld {
public static void main(string[] args){
System.out.println("Hello World");
}
}

For Static block, method and variable we don't need to create a object reference to access it we can directly access it by calling the class.method and varaible.
Static block is executed at compile time itself.

Static
Static - class level (No matter how many objects is created it will share the same block or method).
Non-Static - Object level.

Example :
Banking Example -
AccountBalance is non static object level.
Interest rate, Bank name is a static class level.

Static block is executed before the main method. If we have 2 static block it will be executed in order after that main method is executed.

Static methods-
A static method is called with class name.
Static Variable-
A static Variable is used to declare a variable for memory management.
Example:
ClgName = "SRM";
its common for every student.

Image description

Image description

Non Static
Any functionality that belongs to object is called non-Static.
Non-Static Variable, Non-Static User defined Methods, Non-Static Block and Constructor.

Image description

Default Constructor - If we don't create a constructor java compiler itself create a constructor. So at the time of object creation it will not cause any error.

Object Reference Student s1 = new Student(); here s1 is object reference. it will hold the address of the object in memory.
It will allow to access the object members (varaibles or methods) from non static context.

Image description

Before assigning a object to reference variable initially it was null. after assigning it to new object memory is created.

Image description

This Keyword This keyword is used to refer the current object address. If we use this.variable it will print the value of the variable.

Image description

Creating object inside a static method.

Image description

Invoke a non static method in object.

Image description

Top comments (0)