16) Static keyword

Static Keyword

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

  1. variable (also known as class variable)

  2. method (also known as class method)

  3. block

  4. nested class

1) Java static variable

If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student{

int rollno;

String name;

String college="ITS";

}

Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created. All student has its unique rollno and name so instance data member is good. Here, college refers to the common property of all objects. If we make it static, this field will get memory only once.

  • Java static property is shared to all objects.

Example of static variable

package com.gs.ilp.corejava.staticKeyword;

//Program of static variable  
public class Student8 {
	int rol;
	String name;
	static String colg = "ITS";

	Student8(int r, String n) {
		rol = r;
		name = n;
	}

	void display() {
		System.out.println(rol + " " + name + " " + colg);
	}

	public static void main(String args[]) {
		Student8 s1 = new Student8(11, "Ram");
		s1.display();
	}
}

Output:11 Ram ITS

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor.

Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.

package com.gs.ilp.corejava.staticKeyword;

public class Counter {
	int count = 0;

	// get memory when instance is created
	Counter() {
		count++;
		System.out.println(count);
	}

	public static void main(String args[]) {
		Counter c1 = new Counter();
		Counter c2 = new Counter();
		Counter c3 = new Counter();
	}
}

Output:

1

1

1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.

package com.gs.ilp.corejava.staticKeyword;

public class Counter2 {
	static int count = 0;

	// get memory only once & 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

Differences:

2) Java static method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

Example of static method

package com.gs.ilp.corejava.staticKeyword;

//Program of changing the common property of all objects.
public class Student {
	int rol;
	String name;
	static String colg = "ITS";

	static void change() {
		colg = "BBDIT";
	}

	Student(int r, String n) {
		rol = r;
		name = n;
	}

	void display() {
		System.out.println(rol + " " + name + " " + colg);
	}

	public static void main(String args[]) {
		Student.change();
		Student s1 = new Student(11, "Ram");
		Student s2 = new Student(22, "Raj");
		Student s3 = new Student(33, "Sam");
		s1.display();
		s2.display();
		s3.display();
	}
}

Output:

11 Ram BBDIT

22 Raj BBDIT

33 Sam BBDIT

Another example of static method that performs normal calculation

package com.gs.ilp.corejava.staticKeyword;

//Program to get cube of a given number by static method  
public class Calculate {
	static int cube(int x) {
		return x * x * x;
	}

	public static void main(String args[]) {
		int result = Calculate.cube(5);
		System.out.println(result);
	}
}

Output:125

Restrictions for static method

There are two main restrictions for the static method. They are:

  • The static method cannot use non static data member or call non-static method directly.

  • this and super cannot be used in static context.

package com.gs.ilp.corejava.staticKeyword;

public class A {
	int a = 40; // non static

	public static void main(String args[]) {
		System.out.println(a);
	}
}

Output: Compile Time Error

Q) why java main method is static?

Ans) because object is not required to call static method if it were non-static method,

jvm create object first then call main() method that will lead the problem of extra memory allocation.

3) Java static block

Is used to initialize the static data member.

It is executed before main method at the time of class loading.

Example of static block

package com.gs.ilp.corejava.staticKeyword;

public class A2 {
	static {
		System.out.println("static block invoked");
	}

	public static void main(String args[]) {
		System.out.println("Hello main");
	}
}

Output:

static block invoked

Hello main

Q) Can we execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7/8

class A3{  
 static{  
System.out.println("static block");  
  System.exit(0);  
}  
}  

Output:static block (if not JDK7/8)

In JDK7 and above, output will be:

Output:Error: Main method not found in class A3,

please define the main method as:

public static void main(String[] args)

Static class in Java

Can a class be static in Java?

The answer is YES, we can have static class in java. But only nested classes can be static.

Java allows us to define a class within another class. Such a class is called a nested class.

What are the 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 (or non-static nested class) cannot be created without an instance of outer class.

4) Non Static inner Class cannot contain static method.

Example:

package com.gs.ilp.corejava.staticKeyword;

/* Java program to demonstrate how to implement static and non-static
classes in a java program. */
public class OuterClass {
	private static String msg = "Xceedance";
	private String msg2 = "India";

	// Static nested class
	public static class NestedStaticClass {
		// Only static members of Outer class is directly accessible in nested static
		// class
		public void printMessage() {
			// Try making 'message' a non-static variable, there will be compiler error
			System.out.println("Message from nested static class: " + msg);
			// System.out.println("Message from nested static class: " + msg2);
		}
	}

	// non-static nested class - also called Inner class
	public class InnerClass {
		// Both static and non-static members of Outer class are accessible in this
		// Inner class
		public void display() {
			System.out.println("Message from non-static nested class: " + msg);
			System.out.println("Message from non-static nested class: " + msg2);
		}
	}
}

How to create instance of static and non static nested class?

In order to create instance of Inner class we need an Outer class instance. Let us create Outer class instance for creating non-static nested class

package com.gs.ilp.corejava.staticKeyword;

public class TestNestedClass {
	public static void main(String args[]) {
		OuterClass outer = new OuterClass();
		OuterClass.InnerClass inner = outer.new InnerClass();
		// calling non-static method of Inner class
		inner.display();
		// we can also combine above steps in one step to create instance of
		// Inner class
		OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
		// similarly we can now call Inner class method
		innerObject.display();
		// create instance of nested Static class
		OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass();
		// call non static method of nested static class
		printer.printMessage();
	}
}

Last updated