Static keyword in Java

The static keyword is used in Java mainly for memory management, It is used with variables, methods, blocks and nested class, the static keyword is used for sharing the same variable or method of a given class.

The static keyword is used for a variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static. Any change that occurs to static variable or method, it will reflect in all the instance of the Class.

We do not have to create objects to call or to use the static variables or methods, we can call them just by specifying their Class name.

We need to mention static keyword on the declaration of items, just before the name. We can use the static keyword along with the following items.

  • Variable
  • Method
  • Block
  • Nested class

Static variables in Java

We can declare a variable as static, then a single copy of the variable is created and shared among all objects at the class level. If the static variable is not private, we can access it with ClassName.variableName

Static variables are, essentially, global variables. All instances of the class share the same static variable.

Below example shows, how we can call the static variable of Sample class inside Test class

class Sample {
	public static String website = "chercher tech";
}
public class Test{ public static String author = "karthiq"; public static void main(String args[]) { System.out.println("Author "+ author +" manages website " + Sample.website); } }

static-varaibles-java

If you keenly notice in the above example, I have just used author variable without providing the class reference. We can access the same class variable without using the class name.

System.out.println("Author "+ author +" manages website " + Sample.website);

We can access the static variables not only inside the static method but also with a non-static method.

class Sample {
	public static String website = "chercher tech";
}
public class Test{ public static String author = "karthiq"; public void someMethod() { System.out.println(author + " ---> " +Sample.website ); } public static void main(String args[]) { System.out.println("Author "+ author +" manages website " + Sample.website); Test te = new Test(); te.someMethod(); } }

static-variable-in-non-static-methods

You cannot access any static variables inside a class but outside methods/blocks, You can access static variable only inside blocks and method
static-variables-outside-methods-blocks-inside-class

We cannot create local variables as static if we do, then we get below error
error: illegal start of expression static int i = 0;

Static methods

Static methods are also called class methods because it belongs to the class rather than the object of a class. Static methods can be invoked directly using the class name itself rather than creating an instance and invoking from the instance.

Static Methods can access class variables(static variables) without using an object(instance) of the class, however non-static methods and non-static variables can only be accessed using objects.
Static methods can be accessed directly in static and non-static methods.

The syntax for invoking static method is:

ClassName.staticMethod()

The complete code for calling a static method

public class Test {
	public static String author = "karthiq";
	public static void classMethod() {
	    System.out.println(author + " ---> " +Sample.website );
	}
	public static void main(String args[]) {
	    System.out.println("Author "+ author +" manages website " + Sample.website);
	    classMethod();

Test te = new Test(); te.classMethod(); } }

static-method-called-using-object

In the above program, did you notice below two lines

Test te = new Test();

te.classMethod();

Yes, you can access the static methods using objects as well

static block in Java

The static block is a block of code inside a Java class but outside the methods that will be executed only once when a class is first loaded into the JVM by a class-loader.

static block can access static member only

Static block is used for initializing the static variables. A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.

public class Test {
	static int months;
	static String site;
	static{
	  months = 16;
	  site = "Chercher tech";     
	}
	public static void main(String args[])
	{
	  System.out.println(site + " is "+months+" months old");
	}
}

static-blocks-java

The static blocks run even before running the main method of the class.

public class Test {
	static{
	    System.out.println("block 1");
	}
	static{
	    System.out.println("block 2");
	}
	public static void main(String[] args) {
	    System.out.println("block main");
	}
	static{
	    System.out.println("block 3");
	}
}

static-block-runs-before-main

Few Points about Static block in Java
  • Static blocks are also called as Static Initialization Blocks, a class can have any number of static blocks and they can appear anywhere inside a java class.
  • Static block gets executed when the class is loaded in memory.
  • The Java runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
  • We cannot write static blocks inside a static method and non-static method
  • Only static variables can be accessible inside a static block
  • We can call a static method inside a static block.
  • If you try to access non-static variables or methods inside a static block, it gives a compile time error
    Cannot make a static reference to the non-static method from the type static block
Why are static blocks not allowed inside static methods in Java?

There is no use for putting static initializers, or blocks, inside static methods.

The purpose of static initializers is to initialize the class static variables when the class is first loaded and initialized. This is guaranteed to run before any method or constructor is called. Therefore, putting a static initializer inside a class would contradict its purpose.

Static classes

Java allows us to define a class within another class and it is called a nested class. The class which enclosed nested class is known as Outer class. In Java, we can’t make Top level class static. Only nested classes can be static.

  • Nested static class doesn’t need the reference of Outer class
  • A static class can access non-static members of the Outer class
  • we can access static methods present in the static class with class reference
  • We can write static block {}, static methods() and static variables inside a static class.
  • A class can have multiple static classes.
  • A static class cannot be accessible if it is present inside a static block {}
  • A static class can contain another static class inside it, which means that a nested static class inside a static class
public class Test {
	public String name = "chercher tech";
	public static String author = "karthiq";
	//Static class
	static class NestedClass{
	    public static void staticMethod() {
	        System.out.println("I am a static method"); 
	    }
	    //non-static method
	    public void someMethod() {
	        System.out.println("static author name " + author); 
	        System.out.println("Non static website name " + new Test().name);
	    }
	}
public static void main(String args[])
{ NestedClass.staticMethod(); NestedClass obj = new NestedClass(); obj.someMethod();
} }

static-non-static-class-nested-java-keyword

Frequently asked questions

difference between static and non-static keyword in Java:

A static method belongs to the class and a non-static method belongs to an object of a class. Static methods are useful if you have only one instance where you're going to use the method, and you don't need multiple copies (objects). Non-static methods are used if you're going to use your method to create multiple copies.

A static method can, however, be called both on the class as well as an object of the class. A static method can access only static members. A non-static method can access both static and non-static members because, at the time when the static method is called, the class might not be instantiated.

Memory is allocated multiple time whenever a new object is created for non-static variables and methods, Memory is allocated for these variables only once in the program for static variables.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions