Difference between Static and Non Static keyword in Java

Static also known as Class level context

Static —-Class Level

No Matter how many object we create for that class, it will share the same static context. Whether it is block, properties and methods.

We don’t even to create an object to access a static context.

We just need to use class name.

Non Static —- Object Level

For non-static context we need to create object to access the context.

In the above example Withdrawl() method and CheckBalance() values will change to every bank customer but interest and Interest Calculation will be same for the entire bank customer.

So here interest and calculateInterest() method is static and withdrawl() and checkBalance() methods are non static

Now we will see about static blocks

Static block is executed only once.

It will be executed as soon as the class is loaded and before main method executed.

Result

If we have multi static block then once the class is loaded the static block will execute in order see the example bellow.

Result.

Now we will see about Static Methods.

We are going to create static method inside a class like bellow example and we need to call it.

t will work if we call by creating object also.

Result.

  • It is a static method we need not to create object
  • We can call straight with class name itself.
  • It will work if we call by creating object also.

Now we are going to see about Static Variables.

In java for Global variable default value will be zero.

Here we are going to create a static variable as global.

See in the bellow example we are calling the static variable with it class name.

Result:

Here we are getting zero value because a global variable has default value of zero.

Java training courses are clearly educate for java concepts.

Spread the love