Powered by Blogger.

Java Code - The "Static" keyword in Java Program

Introduction:-

What is the difference between a static class and a static member variable or method? I have asked this question in most of my interviews, and most of the time, it confuses candidates. So I thought of writing an informative article on it so that the difference is comprehensible, and fellow developers can add more information/valuable points.

Static Demystified:-

Let's start with the memory first. Whenever a process is loaded in the RAM, we can say that the memory is roughly divided into three areas (within that process): Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap only known as High Frequency Heap).

The static part holds the “static” member variables and methods. What exactly is static? Those methods and variables which don't need an instance of a class to be created are defined as being static. In C# (and Java too), we use the static keyword to label such members as static. For e.g.:

class MyClass
{
    public static int a;
    public static void DoSomething();
}

These member variables and methods can be called without creating an instance of the enclosing class. E.g., we can call the static method DoSomething() as:

MyClass.DoSomething();

We don't need to create an instance to use this static method.

Static Variable:-

In computer programming, a static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated.

In many programming languages, such as Pascal, all local variables are automatic and all global variables are allocated statically. In these languages, the term "static variable" is generally not used, since "local" and "global" suffice to cover all the possibilities. Static variables are global, and in languages that do make the distinction between global and static variables, both are typically allocated without any distinction within the compiled code.

In the C programming language, the function of static variables can be illustrated as such:

#include <stdio.h>

void func() {
        static int x = 0; // x is initialized only once across three calls of func()
        printf("%d\n", x); // outputs the value of x
        x = x + 1;
}

int main(int argc, char * const argv[]) {
        func(); // prints 0
        func(); // prints 1
        func(); // prints 2
        return 0;
}

The Static keyword:-

In Java technology, members (attributes, methods, and nested classes) of a class can be declare with static keyword that are associated with the class rather than the instances of the class. The static variable sometime called class variable and static method sometime called class method. A static variable is similar to global variable in other programming languages. We can use the static members of a class without creating the object or instance of that class. The static methods can only access the local attributes, static class attributes, and it’s parameters. Attempting to access non-static class attributes in a static methods will cause a compiler error. We can not override the static method. The main() method is a static method because the JVM does not create an instance of the class when executing the main method. The static block code executed once when the class is loaded.

The Static keyword Example:-

 public class TestStatic{
   public static int count = 10;

   public static void incrementCount(){
      count++;
   }

   public static void main(String[]args){
      for(int i=0; i<3; i++){
         System.out.println(”Count is : ”+TestStatic.count);
         TestStatic.incrementCount();
      }
   }
 }

Class Variable vs Instance Variable:-

“static” Keyword = Class Variables

Variables can be declared with the “static” keyword. Example:

static int y = 0;

When a variable is declared with the keyword “static”, its called a “class variable”. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create a instance.

No “static” Keyword = Instance Variables

Without the “static” keyword, it's called “instance variable”, and each instance of the class has its own copy of the variable.

Example:-

In the following code, the class “T2” has two variables x and y. The y is declared with the keyword “static”. In the main class “T1”, we try to manipulate the variables x and y in “T2”, showing the differences of instance variable and class variable.


class T2 {
    int x = 0; // instance variable
    static int y = 0; // class variable

    void setX (int n) { x = n;}
    void setY (int n) { y = n;}

    int getX () { return x;}
    int getY () { return y;}
}

class T1 {
    public static void main(String[] arg) {
        T2 b1 = new T2();
        T2 b2 = new T2();

        b1.setX(9);
        b2.setX(10);

        // each b1 and b2 has separate copies of x
        System.out.println( b1.getX() );
        System.out.println( b2.getX() );

        // class variable can be used directly without a instance of it.
        //(if changed to T2.x, it won't compile)
        System.out.println( T2.y );
        T2.y = 7;
        System.out.println( T2.y );

        // class variable can be manipulated thru methods as usual
        b1.setY(T2.y+1);
        System.out.println( b1.getY() );
    }
}

Static Methods Cannot Access Non-Static Variables: 

Methods declared with “static” cannot access variables declared without “static”. The following gives a compilation error, unless x is also static.

class T2 {
    int x = 3;
    static int returnIt () { return x;}
}

class T1 {
    public static void main(String[] arg) {
        System.out.println( T2.returnIt() );
    }
}

Summary:-

We examined the static keyword in C#, and saw how it helps in writing good code. It is best to think and foresee possible uses of the static keyword so that the code efficiency, in general, increases.

License:-

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Note:-

There's no such thing as static classs. “static” in front of class creates compilation error. However, there's a similar idea called abstract classes, with the keyword “abstract”. Abstract classes cannot be initialized.


0 comments:

Post a Comment