Feb 4, 2016

Static in Java

The static keyword can be used at different levels in context of Java:
       ·         variables
       ·         methods
       ·         blocks of code
       ·         import

Let us try to understand each with an example.

1) static variable
       ·         A static variable is one which belongs to the class and not to objects (instance) of that class.
       ·         The static variable gets memory only once in class area at the time of class loading. These variables will be initialized first, before the initialization of any instance variables.
       ·         It can be used to refer the common property of all objects (that is not unique for each object) e.g. organization name of employees, college name of students etc. A single copy to be shared by all instances of the class.
       ·         A static variable can be accessed directly by the class name and doesn’t need any object.
       ·         Syntax : <class-name>.<variable-name>

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.


class CounterWithoutStatic {
 
            int count = 0; // will get memory when instance is created
 
            CounterWithoutStatic () {
                        count++;
                        System.out.println(count);
            }
 
            public static void main(String args[]) {
                        CounterWithoutStatic c1 = new CounterWithoutStatic ();
                        CounterWithoutStatic c2 = new CounterWithoutStatic ();
                        CounterWithoutStatic c3 = new CounterWithoutStatic ();
            }
}

Output: 1
       1
       1

Program of counter by static variable

class CounterWithStatic {

            static int count = 0; // will get memory only once and retain its value

            CounterWithStatic () {
                        count++;
                        System.out.println(count);
            }

            public static void main(String args[]) {
                        CounterWithStatic c1 = new CounterWithStatic ();
                        CounterWithStatic c2 = new CounterWithStatic ();
                        CounterWithStatic c3 = new CounterWithStatic ();
            }
}

Output: 1
       2
       3

Constants

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;

2) static method
       ·         A static method belongs to the class and not to the object (instance). They are also called Class methods.
       ·         A static method can be accessed directly by the class name and doesn’t need any object
       ·         Syntax : <class-name>.<method-name>
    Not all combinations of instance and class variables and methods are allowed:
           ·         Instance methods can access instance variables and instance methods directly.
           ·         Instance methods can access class variables and class methods directly.
           ·         Class methods can access class variables and class methods directly.
           ·         Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use this keyword as there is no instance for this to refer to.


    class Student {
    
     int rollno;
     String name;
     static String college = "IPU";
    
     static void change() {
      college = "DCE";
     }
    
     Student(int r, String n) {
      rollno = r;
      name = n;
     }
    
     void display() {
      System.out.println(rollno + " " + name + " " + college);
     }
    
     public static void main(String args[]) {
      Student.change();
    
      Student s1 = new Student(101, "Ayush");
      Student s2 = new Student(102, "Charu");
      Student s3 = new Student(103, "Sumit");
    
      s1.display();
      s2.display();
      s3.display();
     }
    }
    

      Output: 101 Aysuh DCE
             102 Charu DCE
             103 Sumit DCE

      main() method is static because object is not required to call static method if it were non-static method, JVM create object first then call main() method that will lead the problem of extra memory allocation.

      3) static block
             ·         The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM.
             ·         Is used to initialize the static data member.

        class Program {
        
                    static {
                                System.out.println("static block is invoked");
                    }
        
                    public static void main(String args[]) {
                                System.out.println("Hello main");
                    }
        }
        

        Output: static block is invoked
               Hello main

        4) static import
        ·         Using static import we can invoke static methods by using method name only.

        package com.javaTerritory.withStaticImport;
        import static java.lang.Math.*;
        
        class Program {
        
                    public static void main(String args[]) {
                                System.out.println("Square root 25: " + sqrt(25));
                                System.out.println("Log(100): " + log(100));
                                System.out.println("Pi: " + PI);
                    }
        }
        

        As you see in the code, when we put static import in our code, we can reference static methods and variables without using the class name. Normally we would use Math.sqrt() and Math.PI if we did not have static import.

        Hope above explanation helps. Please join at +Java Territory to stay updated with latest articles.



        0 comments:

        Post a Comment