Java static keyword – static variable, static methods, static blocks

static keyword: – static keyword is used for memory management. static keyword belongs to class rather than objects.

Rules of static variables: – 

  • static variables initialize only once at the execution of the program.
  • static variables initialize before the initialization of the instance variables(instance variables are those variables which are created inside the class but outside the method).
  • A single copy of static variables is shared by all instances of the class.
  • A static variable can be accessed directly by the class name(class_name.static_variable) and it does not need any object.
  • static variable can’t be declared inside the constructor.
public class Test{
  static int i;
	public static void main(String args[]){		
		Test.i=100; // static variable directly accessed by class name		
	}	
}

The problem without a static variable Example: –

public class Test{
	int i=1000;
   Test()   // constructor
    {
	   i++;
	  System.out.println(i);   
   }
   
	public static void main(String args[]){	
		Test test = new Test();
		Test test1 = new Test();
		Test test2 = new Test();	
	}		
}

Result:-

1001
1001
1001

 

Example With static variable: –

public class Test{
	static int i=1000;	
   Test()   // constructor
    {
	   i++;
	  System.out.println(i);   
   }
	public static void main(String args[]){
		Test test = new Test();
		Test test1 = new Test();
		Test test2 = new Test();	
	}
		
}

Result:-

1001
1002
1003

static methods in java: –

  • static methods belong to class rather than the object of the class.
  • static methods can only access static data i.e static variables.
public class Test{
 static int i;

 public static void main(String args[]){
 Test.mytest();

 }
 static void mytest(){
 Test.i=100+100;
 System.out.println(i);
 }
}
  • A static method can only call a static method. it cannot call nonstatic methods.
public class Test{
	static int i;
	public static void main(String args[]){		
		Test.myExp();	
	}
	static void myExp(){	
		Test.mytest();
	}
	
	static void mytest(){	
		Test.i=100+100;	
		System.out.println(i);
	}
  • a static method cannot use this or super keyword.

static block in java: – 

static block is executed before the execution of the main method. this can be a good approach if you to run some piece of code before the main method.

An example of a static block with code:-

public class Test{
	static{	
		System.out.println("static block");	
	}
	public static void main(String args[]){		
		Test test = new Test();
		test.mytest();		
	}
	void mytest(){	
		System.out.println("mytest method");	
	}		
}

Result

static block
mytest method

 

 

 

 

 

 

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts

Categories: