Day25: Using the Static Keyword

 Using the Static Keyword

The static keyword is also called as non-access modifier. In java it is used in 3 places:
  1. We can declare "Static" data member.
  2. We can declare "Static" method.
  3. We can have static initializer block in Java.
Special Note : In Java we cannot declare a local var as static.

class Data
{
    int a;  //instance variable
    int b; //instance variable
}

  1. The variables a and b are called non-static OR instance.
  2. They will be allocated space in Heap Area, the moment an object or data class gets created.
  3. They will have as many copy created as we will create object of data class. i.e., for every object of data class a and b will have separate copy.

class Data
{
int a;
static int b;
}

In Above code, the data member 'a' is still called instance variable. But the data member 'b' is  called static OR class level OR shared variable.

The Static variable 'b' will be loaded in memory as soon as the data class will be used by the programmer. It means that before any instance variable get created for a class, Java loads Or creates the static variable.

Static variable do not live in stack Or heap area. Rather java loads them in a special area of RAM called Method Area Or perm-gen(Permanent -Generation) Area.

Logically, Java Recommended to use static for every such data member whose single copy needs to be created for every object like 'pi', rate of Interest offered by a bank OR school name for a class called student etc.

public class Data
{
public class Data
{
public int a;
public static int b;
}
}

Driver Class:

public class UseData
{
public static void main(String [ ] args)
{
Data D1 = new Data();
Data D2 = new Data();
Data D3 = new Data();
}
D1.a = 10;
D2.a = 20;
D3.a = 30;
System.out.println(D1.a);
System.out.println(D2.a);
System.out.println(D3.a);

D1.a = 10;
D2.a = 20;
D3.a = 30;
System.out.println(D1.b);
System.out.println(D2.b);
System.out.println(D3.b);
 


Comments

Popular posts from this blog

Day2 : Compiling Java Program with Examples

Day1: Introduction to Java and its feature

What does System.out.printf( "%-15s%03d\n", s1, x) do?