Skip to content

Latest commit

 

History

History
236 lines (196 loc) · 7.85 KB

1.5.0_static_keyword.md

File metadata and controls

236 lines (196 loc) · 7.85 KB

Reference: here

Static Variable:

  • Static is a keyword used in Java.

  • it can be applied to a field, a method or an inner class.

  • Static variables-

    • A static variable is common to all the instances (or objects) of the class because it is a class level variable.
    • In other words you can say that only a single copy of static variable is created and shared among all the instances of the class.
    • Unlike non-static variables, such variables can be accessed directly in static and non-static methods.
    • Static variables are also known as class variables.
    • Local variables (method level variables) cannot be declared static.
  • A static field, method or class has a single instance for the whole class that defines it, even if there is no instance of this class in the program.

  • If you declare any variable as static, it is known as static variable and if you declare any method as static, it is known static method.

  • static variable are same for all objects but non-static variable different for different objects.

  • Static variable can be accessed directly. (If in same class)

  • static variable can be referenced by class name or object name ( note its both) but normally whenever we use static keyword we prefer using class name as it's value is same for all objects.

  • if variable j is declared non static it will give error if referenced through static method as non-static variable cannot be used in static context

  • if we want to initialize non-static variable we use constructor but when we have to initialize static variable we normally use static block as static variable is directly loaded into class loader and we need not assign value in constructor as it will be called every-time whenever object is initialized.

  • constructor will be executed when ever we create a object but static block will be executed when ever we load a class so note that static block will be executed first before constructor.So class is loaded only once and constructor is executed with every instantiation of object.

  • static block will always be executed before constructor as class is loaded first no matter what the sequence is there in program. Memory allocation for such variables happens when the class is loaded in the memory.

--> we can only access static variable inside static block.

example:

src/main/java/collections/main/java/corejava/example_static

Example 1- Static variables can be accessed directly in Static method-

class VariableDemo
{
   static int count=0;
   public void increment()
   {
       count++;
   }
   public static void main(String args[])
   {
       VariableDemo obj1=new VariableDemo();
       VariableDemo obj2=new VariableDemo();
       obj1.increment();
       obj2.increment();
       System.out.println("Obj1: count is="+obj1.count);
       System.out.println("Obj2: count is="+obj2.count);
   }
}

Output- Obj1: count is=2 Obj2: count is=2

Example 2- Static variables are shared among all the instances of class.

class JavaExample {
    //Static integer variable
    static int var1 = 77;
    //non-static string variable
    String var2;

    public static void main(String args[]) {
        JavaExample ob1 = new JavaExample();
        JavaExample ob2 = new JavaExample();
        /* static variables can be accessed directly without
         * any instances. Just to demonstrate that static variables
         * are shared, I am accessing them using objects so that
         * we can check that the changes made to static variables
         * by one object, reflects when we access them using other
         * objects
         */
        //Assigning the value to static variable using object ob1
        ob1.var1 = 88;
        ob1.var2 = "I'm Object1";
        /* This will overwrite the value of var1 because var1 has a single
         * copy shared among both the objects.
         */
        ob2.var1 = 99;
        ob2.var2 = "I'm Object2";
        System.out.println("ob1 integer:" + ob1.var1);
        System.out.println("ob1 String:" + ob1.var2);
        System.out.println("ob2 integer:" + ob2.var1);
        System.out.println("ob2 STring:" + ob2.var2);
    }
}

ob1 integer:99 ob1 String:I'm Object1 ob2 integer:99 ob2 STring:I'm Object2

Static methods-

  • The static keyword is used to create methods that will exist independently of any instances created for the class.
  • Only static or local variables can be accessed through static methods.
  • Static Methods can access class variables(static variables) without using object(instance) of the class. (On the other hand non-static methods and non-static variables can only be accessed using objects.)
  • Static methods can be accessed directly through static and non-static methods.* Static method can be accessed directly. (If in same class)
  • Or static method can be accessed by using class name dot method name. (If method is in same class or different class)
  • Or static method can be accesed by using object name dot method name. (If method is in same class or different class)
  • Static variables are also known as class variables. Local variables (method level variables) cannot be declared static.

Example 1- static method main is accessing static variables without object.

class JavaExample{
   static int i = 10;
   static String s = "Hello";
   //This is a static method
   public static void main(String args[]) 
   {
       System.out.println("i:"+i);
       System.out.println("s:"+s);
   }
}

Output- i:10 s:Hello

Example 2- Static method accessed directly through static and non-static method

class JavaExample{
 static int i = 100;
 static String s = "Hello";
 //Static method
 static void display()
 {
    System.out.println("i:"+i);
    System.out.println("i:"+s);
 }
 //non-static method
 void funcn()
 {
     //Static method called in non-static method
     display();
 }
 //static method
 public static void main(String args[])
 {
     JavaExample obj = new JavaExample();
     //You need to have object to call this non-static method
     obj.funcn();	  
          //Static method called in another static method
          display();
  }
}

Output- i:100 i:Hello i:100 i:Hello

Static Nested class-

  • A class can be made static only if it is a nested class. Nested static class doesn’t need reference of Outer class. A nested static class cannot access non-static members of the Outer class.

Example 1-

class JavaExample{
   private static String str = "Hello";

   //Static class
   static class MyNestedClass{
	//non-static method
	public void disp() {

	   /* If you make the str variable of outer class
	    * non-static then you will get compilation error
	    * because: a nested static class cannot access non-
	    * static members of the outer class.
	    */
	   System.out.println(str); 
	}

   }
 public static void main(String args[])
   {
       /* To create instance of nested class we didn't need the outer
	* class instance but for a regular nested class you would need 
	* to create an instance of outer class first
        */
	JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
	obj.disp();
   }
}

Output- Hello

Static blocks-

  • Static block is used for initializing static variables.This block gets executed when the class is loaded in the memory.

  • A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.

Example- Single static block

// executed after constructor

class JavaExample{
   static int num;
   static String mystr;
   static{
      num = 97;
      mystr = "Static keyword in Java";
   }
   public static void main(String args[])
   {
      System.out.println("Value of num: "+num);
      System.out.println("Value of mystr: "+mystr);
   }
}

Output- Value of num: 97 Value of mystr: Static keyword in Java