Wednesday, February 24, 2016

Use of keyword static in C,C++ and Java

Dear Folks, 
If any one knows C,C++ and Java then a clear understanding of keyword static is must for its proper use. 
Let's first see it's use in C.
In C language, this keyword is used to create variables for static storage class. In C, there are four basic storage classes, Namely
 1.Automatic 2.Register 3. Static and 4. External


The behavior of static storage class is that, it's default initial value is zero, scope is local to the block in which it is declared. The interesting feature of this type of variable is that, the life of this variable persists between function calls. It means, when the control exits the function in which it is declared, the variable will not be destroyed from memory, it exists and when the function is visited  next time, this variable will not be recreated, instead the old one, which has been created in the first call is used with old value.


  Following C code snippet will make you understand this concept.
void display()
{
 static int k;
 printf("%d\n", ++k);
}

main()
{
 display();
 display();
 display();
}
The output here is
1
2
3
As, k is a static variable , it's default initial value is zero, in the first call it gets incremented to 1, and  then for second call, k is not recreated, instead existing k is used with old value. So the increment operator  when applied on k, it becomes 2, and so also for third call.

Let's understand, its use in C++ and Java ...
Normally, in C++ and Java keyword static is used to create class variables and 
class methods.


A static variable or class variable is one, which has a common state(value) for a particular attribute, for all objects of a class.Similarly a static method(or member function) is  one, which is used to describe common behavior of all objects.



// This Java code snippet make you understand how static keyword is used... 
class Account
{
  private static double minbal;

  static void setMinBal( double x)
  {
      minbal=x;
  }
 static void dispalyMinBal()
  {
     Systm.out.println(minbal);
  }
}

class DemoStatic
{
  public static void main(String arg[])
  {
     Account.setMinBal(10000);
     Account.displayMinBal(10000);
  }
}


In this example, minbal is static variable, which represents a common value for all accounts(objects), and setMinBal() and displayMinBal() are static methods which are common for all accounts. So they have been invoked with the help class name, instead of object.


Do you find this post useful, Help me in improving this, by sending comments and feedback.

  



1 comment:

  1. sir, if you have any video lectures on "this" reference, please post.

    ReplyDelete