Static in Java

Static:
       Static keyword in java mainly useful for memory management. We can use this static keyword with variables (Also known as class variable), methods(Also known as class method), blocks and nested class. 

        Static variables belonged to the class. Static attributes exists independently of any instances of a class and can access even when no instances of a class created.  A static variable is shared by all objects of the class. Static variables have the longest scope; they are created when the class is loaded, and they survive as long as the class stays loaded in the Java Virtual Machine. Static variables are allocated space in the heap area.

You can mark as static for the below things:

  • Methods
  • Variables
  • Block
  • Inner class
You can't mark as static for the below things:
  • Constructors
  • Classes (unless they are nested)
  • Interfaces
  • Inner class methods and instance variables
  • Local variables
What is the difference between class and instance variables in java?
         Class variables are associated with class. There is exactly one copy of the variable regardless of the number of objects of the class and the same copy is shared by all the objects.
         Instance variables are associated with instances of the class i.e objects. Means, every object of the class will have its own copy of the instance variables. 

Can we declare static variables under any method(Static or non-static)?
We cannot declare the static variables under any method as it has class scope. If you declare it in class level that can be stored in class memory and can be shared to all the objects. If You declare that under any method then they can be stored in separate stack and cannot be shared. 

Ex: 

class Counter2
{
    static int count = 0;// will get memory only once and retain its value
    Counter2() {
        count++;
        System.out.println(count);
    }
    public static void main(String args[]) {
        Counter2 c1 = new Counter2();
        Counter2 c2 = new Counter2();
        Counter2 c3 = new Counter2();
    }
}
Output:
1
2
3

Static final variables:
static final variables are constants.

Key point:
final variable always needs initialization, if you don’t initialize it would throw a compilation error. have a look at below example-
public class MyClass{
    public static final int MY_VAR;
}
Error: variable MY_VAR might not have been initialized


Static Method:(Also called Class Method)
If you apply static before any method, it is known as static method.
  1. A static method to the class rather than object of a class
  2. A static method can be invoked without the need for creating an object
  3. Static method can access the static data member and can change the value of it
  4. All static methods are resolved at compile time
Advantages:
  • Globally accessible
  • One instance per JVM
  • Can be accessed by using class name
  • Contains a single value applicable to all instances
  • Load up on JVM start up
Disadvantages: (Design approaches)
  • Static members are always part of memory weather they are in use or not, but it hardly   impact
  • Static members are created with a particular intention, so it requires clear vision of your requirement
  • To synchronize a static method you need some extra efforts
  • Static methods are difficult to mock during testing
  • Are not tied to objects so doesn’t  reflect pure OOP

Why java doesn’t allow overriding static methods?

Reason: Static methods belong to the Class and not to the objects.

public class first {
    static void main() {
        System.out.println("this is my method");
    }
}
class second extends first {
    void main() {
        System.out.println("this is second");
    }
    public static void main(String a[]) {
        second n = new second();
        n.main();
    }
}

Output :
Compile time error as 
(first.java:10: error: main() in second cannot override main() in first
void main()
     ^
  overridden method is static
1 error)

Static methods can be hided but not overridden.

Method Hiding:
Method hiding means subclass has defined a class method with the same signature as a class method in the super class. In that case the method of super class is hidden by the subclass. It signifies that : The version of a method that is executed will NOT be determined by the object that is used to invoke it. In fact it will be determined by the type of reference variable used to invoke the method. 

Ex: 

public class first {
 public static void foo() {
  System.out.println("Dog");
 }
}
class second extends first {
 public static void foo() { // hides Dog.foo()
  System.out.println("Cat");
 }
 public static void main(String args[]) {
  first.foo();// it obviously prints Dog
  second.foo();// it obviously prints Cat
  first f = new first();// Prints Dog
  f.foo();
  first f1 = new second();// prints Dog.
  f1.foo();
 }
}

Key point: Static methods can accessed by class objects also.

Can static method access instance variables ?
Ans: Static methods cannot access the instance variables.
But we can access them indirectly using the instance of those variables. Static methods may even access private instance variables via an object reference.
Ex:
public class first {
    private int num;
    public first(int count) {
        num = count;
    }
    public static void main(String args[]) {
        first s = new first(10);
        System.out.println(s.num);
        s.add(20);
        System.out.println(s.num);
    }
    private void add(int num1) {
        num += num1;
    }
}
Output:
10
30

Why can't static method access 'this' and 'super'?

1.We don't instantiate static methods in java. Hence static methods cannot access 'this' because 'this' always refers to the current object.(Static methods are not tied to any object.)
2.  Super needs inheritance hierarchy and it is also works on objects. Like 'this', super also not used with static method.

Why can't we call static methods using object in java?

     We can access the static methods by instances but it is considered to be a bad programming practice. Generally we call the static methods by class name. Using the class name makes it is clear that the member belongs to the whole class of objects rather than to a single instance.    
      When you call a method via the object reference, it is generally meant that the method is going to manipulate on the state of that object and not affect any other objects. But static methods are shared among all the objects, and whatever manipulation you do in those methods are visible across all objects. So basically, its a conflict of concept.  

When should static be used in fields and methods in java?    
For methods: when there is no state(State: what the methods have and Behavior: what the methods do)

For variables: constants or global variables.

Why should the 'main' method in 'java' program be static?
The "public static void main" is just a convention. main() is just a starting point of a program which tell the JVM where to start. Now if you want to the main() to be called via an object,then for it, a class needs to be made. Suppose you have a program having multiple classes in a single .java file, then how would JVM know where to start?  It is made static so that it is available to the JVM at load time.

Main method is

Public because JVM has to see outside from package.
Static because JVM calls it without any object of class in which it is declared.
Void because it does not return anything.


Examples of Static method:
1. 

class first
{
    static void dis()
    {
        System.out.println("this is static method");
    }
    public static void main(String a[])
    {
        dis();
    }
}

Output:
>javac first.java
>java first
this is static method

2.
class first
{
    public void display()// It needs object
    {
        System.out.println("this is instance method");
    }
    static void dis()
    {
        System.out.println("this is static method");
    }
    public static void main(String a[])
    {
        first f = new first();// Object creation
        f.display();
        dis();
    }
}

Output:
>javac first.java
>java first
this is instance method
this is static method

3.
import java.lang.Math;
class first {
    public static void main(String[] args) {
        int res;
        res = Math.min(100, 200); // calling static method min by writing class name
        System.out.println(result);
        System.out.println(Math.max(1000, 2000));
    }
}


Output:
>javac first.java
>java first
100
2000

4.
class first {
    int rollno;
    String name;
    static String college = "myCollege";
    static void change() {
        college = "University";
    }
    first(int r, String n) {
        rollno = r;
        name = n;
    }
    void display() {
        System.out.println(rollno + " " + name + " " + college);
    }
    public static void main(String args[]) {
        first.change();
        first s1 = new first(111, "nixan");
        first s2 = new first(222, "mihceal");
        first s3 = new first(333, "Jack");
        s1.display();
        s2.display();
        s3.display();
    }
}
Output:
>javac first.java
>java first
111 nixan University
222 mihceal University
333 Jack University

Static Block:
Static block is also called static initialization block. It is declared like normal block enclosed with { }, but preceded by static. 

static {
//code here
} 
Functionality:(Advantages)
  • A class can have any number of static initialization blocks, and they can appear anywhere in the class body.
  • The run time system guarantees that static initialization blocks are called in the order that they appear in the source code. 
  • And don't forget, this code will be executed when JVM loads the class.
  • JVM combines all these blocks into one single static block and then executes further.
Disadvantages:
  • There is a limitation of JVM that a static initializer block should not exceed 64KB.
  • You cannot throw Checked Exceptions.
  • You cannot use this keyword since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.

    Key point: If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM, then static variables/methods referred and the static block both will be executed.  

    Ex:
    public class StaticBlockExample
    { 
        static 
            {
            System.out.println("static block1");//Executed firstly
            }
        public StaticBlockExample()
            {
            System.out.println("constructor");
            }
        public static String staticString = "Static Variable";
        static 
            { 
            System.out.println("static block2 and "+ staticString);//Executed secondly  
            }  
    public static void main(String[] args){
        StaticBlockExample statEx = new StaticBlockExample();
    //StaticBlockExample() method gets executed.
        StaticBlockExample.staticMethod2();
        }
        static 
            {//Executed after second one
            staticMethod(); 
            System.out.println("static block3"); 
            }
        public static void staticMethod()
        {//staticMethod(); in 3rd static block directly calls this method without any instantiation.
        System.out.println("This is static method");   
        }
        public static void staticMethod2() 
        {
            System.out.println("This is static method2");
        }
    }

    Output: 
    >javac StaticBlockExample 
    >java StaticBlockExample
    static block1
    static block2 and Static Variable
    This is static method
    static block3
    constructor
     

    This is static method2

    Nested Static class:
    Can a class be static?

    Yes. Java allows us to define a class in another class called nested class. The class which encloses the nested class is outer class. We cannot make outer class as static. Only nested class can be static.

    Key point: "The static keyword does not do to a class declaration what it does to a variable or a method declaration."
    • Static nested class can only access the static members of outer class including private
    • Static nested class cannot access non-static member or method
    Can we write instance method in nested static class?
    Yes.
    Ex: 

    class OuterClass {
        static int data = 50;
        static class InnerClass {
            void msg() {
                System.out.println("Normal Method Result " + data);
            }
        }
        public static void main(String args[]) {
            OuterClass.InnerClass obj = new OuterClass.InnerClass();// object creation for static nested class
            obj.msg();
        }
    }
    

    Output:
    Normal Method Result  50 

                   In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object. 


    class outer {
        static int data = 50;
        static class Inner {
            static void msg() {
                System.out.println("static value is " + data);
            }
        }
        public static void main(String args[]) {
            TestOuter2.Inner.msg();// no need to create the instance of static nested class
        }
    }


    Output:
    Static value is 50 

    Differences between static and non-static nested classes? 
    1) Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.
    2) Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.
    3) An instance of Inner class cannot be created without an instance of outer class and an Inner class can reference data and methods defined in Outer class in which it nests, so we don’t need to pass reference of an object to the constructor of the Inner class. For this reason Inner classes can make program simple and concise.
     
    What is a nested interface ?
    Any interface declared inside a class or an interface. It is static by default.

    Why outer classes are not static in java?
    An outer class is already implicitly static.Non-static nested class (= inner class) means the inner class implicitly has a reference to its parent class. That's why, for nested class, you can distinguish between static and non-static. This does not make sense for outer classes.
    (Need more clarity...)

    Ex:
    public class first
    {
     private static String hello = "    needtolearnmore   ";
     private static class myclass {// static inner classs
      public void foo()
      {
       hello.trim();
       System.out.println(hello);
      }
     }
     public static void main(String a[])
     {
      first.myclass h = new first.myclass();
      h.foo();
     }
    }
    
    Output:
    needtolearnmore

    Examples:
    public class first {
        private int i;
        private static String name = "This is a static String";

        public first(int a) {
            this.i = a;
        }

        public static void StaticMethod() {
            System.out.println("I am a static method");
            System.out.println(first.name);
        }

        public void myMethod() {
            System.out.println("This is a normal method");
            System.out.println(first.name);
            System.out.println("instance variable: " + this.i);
        }

        public static void main(String a[]) {
            first.StaticMethod();
            first f = new first(10);
            f.myMethod();
        }
    }
    Output:

    >javac first.java
    >java first
    I am a static method
    This is a static String
    This is a normal method
    This is a static String
    instance variable10



    No comments:

    Post a Comment