Thursday, December 12, 2013

static keyword in java

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

static variable

If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object).
  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient.

static method

If you apply static keyword with any method, it is known as static method.
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.
There are two main restrictions for the static method. They are:
  1. The static method can not use non static data member or call non-static method directly.
  2. this and super cannot be used in static context.

static block

  • Is used to initialize the static data member.
  • It is executed before main method at the time of class loading.

No comments:

Post a Comment

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...