Saturday, December 3, 2016

Static Keyword in Java


The main purpose of static keyword in java is  memory management.
 The  static keyword can be used  in each of the  five cases.

  1.  static variables
  2.  static methods
  3.  static block
  4.  static nested class
  5.  Interface  static method(java 8 onward)

  • STATIC VARIABLES


In Java Variables can be declared with the “static” keyword.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 an instance.

Example: static int i = 0;

ADVANTAGE OF STATIC VARIABLE

It makes your program memory efficient (i.e it saves memory).
now let us execute a program without static variable.
Suppose there are 1500 students in a college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.if we don't  use static keyword at the variable college  then for all 1500 students the huge amount of memory space will be used which is not a good programming practice.
    class Student{
         int rollno;
         String name;
         String college="XYZ";
    }
program using static variable

package com.brainatjava.test;

public class Student {

   static String college ="XYZ";   int rollno;   String name;
  Student(int r,String n){   rollno = r;   name = n;   }
void display (){
System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){ Student s1 = new Student(10,"Rabi"); Student s2 = new Student(20,"Rohit");
s1.display(); s2.display(); } }
OUTPUT
10 Rabi XYZ
20 Rohit XYZ


  •  STATIC METHOD


Static Methods can access class variables without using object of the class. It can access non-static methods and non-static variables by using objects. Static methods can be accessed directly in static and non-static methods.

EXAMPLE OF STATIC METHOD
public class Test1 {
static int i =10;

 //Static method
 static void display()
 {
    //Its a Static method
    System.out.println("i:"+Test1.i);
 }

 void foo()
 {
     //Static method called in non-static method
     display();
 }
 public static void main(String args[]) //Its a Static Method
 {
     //Static method called in another static method
     display();
     Test1 t1=new Test1();
      t1.foo();
  }
}

OUTPUT
i:10
i:10

STATIC BLOCK


   It is used to initialize the static data member.It is executed before main method at the time of classloading.A class can have multiple Static blocks, which will execute in the same sequence in which they have been written in the program.

EXAMPLE  OF SINGLE STATIC BLOCK

public class ExampleOfStaticBlock {
static int i;
  static String str;
  static{
     i =30;
     str = "welcome to BrainAtJava";
  }
  public static void main(String args[])
  {
     System.out.println("Value of i="+i);
     System.out.println("str="+str);
  }
}
OUTPUT
Value of i=30
str=welcome to BrainAtJava

EXAMPLE OF MULTIPLE STATIC BLOCK


public class ExampleOfMultipleStaticBlock {
static int i1;
static int i2;

  static String str1;
  static String str2;

  //First Static block
  static{
     i1 = 70;
     str1 = "Hello";
 }
 //Second static block
 static{
     i2= 55;
     str2 = "java";
 }
 public static void main(String args[])
 {
 System.out.println("Value of i1="+i1);
 System.out.println("Value of str1="+str1);

          System.out.println("Value of i2="+i2);
     System.out.println("Value of str2="+str2);
 
   
  }
}
OUTPUT
Value of i1=70
Value of str1=Hello
Value of i2=55
Value of str2=java

Static Nested Class:

A static nested class in Java is simply a class scoped within another class.
We can think of it as the static members of the enclosing class.
We can access it without creating an instance of the outer class.Simple it can be accessed by outerclass.innerclass.We can follow the below example.

A static nested class in Java serves a great advantage to namespace resolution.  For example, if we have a class with an  common name, and in a large project, it is quite possible that some other programmer has the same idea, and has a class with the same name you had, then we  can solve this  name clash by making our class a public static nested class. And our class will be written as outer class, followed by a period (.) and then followed by static nested class name.

Let's take an example

 class Outernormal
{
    private int var = 20;
    private static int staticVar = 50;
    public static void staticmethod(){
   System.out.println(var);//Error: Cannot make a static reference to the non-static field mem
   System.out.println(staticVar);
    }
    static class InnerStatic
    {
        public void getFields ()
        {
            System.out.println(var); //Error: Cannot make a static reference to the non-static field mem
            System.out.println(staticVar);
        }
    }
}

public class StaticClassDemo
{
    public static void main(String[] args)
    {
        OuterStatic.InnerStatic is = new OuterStatic.InnerStatic();
        is.getFields();
    }
}

Interface  static method(java 8 onward):

 In Java8 onwards , we can define static methods in interface ,but we can’t override them in the implementation classes.

This  helps us in avoiding undesired results in case of wrong implementation of interface.

It is good for providing utility methods,for example any precondition  check.

It provides security by not allowing implementing classes to override them.

Let's see code sample below.
public interface MyInf {

 static boolean checkIfNull(String str) {
  System.out.println("Interface Null Check");

  return str == null ? true : false;
 }
}