Static Keyword in Java

Static Keyword in Java

 

In Java programming language, the static keyword is used to refer to memory. In Java the static keyword can be applied to variables, methods, nested class, and blocks, etc. In Java programming language the static keyword is used with class usually.

The following are the terms in Java programming language that can be static:

  1. Variables
  2. Methods
  3. Block
  4. nested class

 

Java Static Variable:

In java if a variable is declared as static, then it will be called a static variable. A static variable in java is used to refer the common property of all objects. This property is not unique for each object. As an example we can consider a company for the employees. It should be noted that company is not unique for each employee rather all the employees work in the same company. Similarly a school or college for students is not unique for all the students.

In Java programming language, the static variable gets memory only once in class area. This is done when the class is loaded.

 

Advantages of Static variable:

  1. Static variables save memory and the program becomes memory efficient.
  2. In a program constants can be defined without taking an additional memory when static variables are used for each class and
  3. The constants can also be accessed without creating an executable file to be run on the computer.

 

Understanding problem without static variables:

Consider the following example to understand problem without static variables:

CODE:

class Employee {

int id;

string name;

string company = “AKS”;

}

In the above example suppose you have 100 employees in the company, these all instance data members will get memory every time when an object will be created. As all the employees will have a unique id and a unique name therefore, the instance data members will be good. But the company will not be unique for each employee. The company is referring to a common property for all employees or objects. Therefore, the variable company should be made static to get memory only once.

 

Example of Static variables:

Consider the following example in which we have defined a class employee and made one of its data members static:

CODE:

class Employee {

int id;

string name;

static string company = “AKS”;

Employee (int n, string n1) {

no = n;

name = n1;

}

void display () {

system. out. println (no + “ ” + name “ ” + company);

}

public static void main (sting args []) {

Employee e1 = new Employee (121, “Stuart”);

Employee e2 = new Employee (122, “Bill”);

e1. display ();

e2. display ();

}

}

OUTPUT:

121 Stuart AKS

122 Bill AKS

In the above example, a class named ‘Employee’ is declared that has three data members and one method or member function and one parameterized constructor. The record will be passed from the main function by using the objects as constructor arguments that is n and n1. Here n is the number of the employee and n1 is the name of the employee. These arguments will be assigned to the data members then in the parameterized constructors. It can be seen that no record is passed to the data member ‘company’ because it is a static variable and it is initialized only once. The static variable ‘company’ will be the common property of all objects.

The display () method is used to display the record and is called through an object of class Employee.

The objects get the memory in the heap area and the reference variables refer to the objects allocated in the heap memory. In the above example both e1 and e2 are the reference variables that refer to the objects allocated in memory.

 

Program of counter without static variable:

Consider the following example in which we are going to create an instance variable:

CODE:

class Counter{

int add = 0;

Counter () {

add ++;

system. out. println (add);

}

public static void main (string args []) {

Counter a1 = new Counter ();

Counter a2 = new Counter ();

Counter a3 = new Counter ();

}

}

OUTPUT:

1

1

1

In the above example, an instance variable is created named add which belongs to the class ‘Counter’. This instance variable is incremented in the constructor. Each object created will have a copy of the instance variable because the instance variable gets the memory when an object is created. When the instance variable is incremented it will not be applied on the object, therefore, each object created will have a value 1 in the add instance variable.

 

Program of counter by static variable:

Consider the following example in which we have created a static variable:

CODE:

class Counter{

static int add = 0;

Counter () {

add ++;

system. out. println (add);

}

public static void main (string args []) {

Counter a1 = new Counter ();

Counter a2 = new Counter ();

Counter a3 = new Counter ();

}

}

OUTPUT:

1

2

3

In the above example, the add variable is declared as a static variable. This variable will get memory only once. When the object changes the value of the static variable the static variable will retain its value because they get the memory only once. The value of the static variable ‘add’ is incremented by 1 in the default constructor and as we created three objects therefore, the default constructor will be called three times and will increment the value of the static variable three times and will print its value three times too. At first the value of the static variable was initialized at zero, when the object is created, the value of static variable became 1 and is printed. Again another object is creates, the value of static variable is incremented by 1; now its value is 2 and is printed and so on.

 

Java static method:

If before any method, the static keyword is used then the method will be static method. The method which is declared as static belongs to the class in which it is declared rather than to object of the class. The static method can be called or invoked without creating an instance of the class. We can use the static method to change the value of the static data member and can also access the static data members through a static method in the class.

 

Example of static method:

Consider the following example in which we have changed the value of a static data member from the static method:

CODE:

class Employee {

int id;

string name;

static string company = “AKS”;

static void alter () {

company = “ITC”

Employee (int n, string n1) {

no = n;

name = n1;

}

void display () {

system. out. println (no + “ ” + name “ ” + company);

}

public static void main (sting args []) {

Employee. alter ();

Employee e1 = new Employee (121, “Stuart”);

Employee e2 = new Employee (122, “Bill”);

e1. display ();

e2. display ();

}

}

OUTPUT:

121 Stuart ITC

122 Bill ITC

In the above example, a class named ‘Employee’ is declared that has three data members one of which is static and two methods or member functions and one parameterized constructor. The record will be passed from the main function by using the objects as constructor arguments that is n and n1. Here n is the number of the employee and n1 is the name of the employee. These arguments will be assigned to the data members then in the parameterized constructors.

It can be seen that no record is passed to the data member ‘company’ because it is a static variable and it is initialized only once. The static variable ‘company’ will be the common property of all objects. But we can change the value of this static variable by using a static method. In the code above we used “static void alter ()” method to change the value of the static data member. The static method is called or invoked directly from the name of the class. It can be seen that when the display () method is called it displayed the latest values and the value of the static variable that is company is changed.

We can conclude that through static methods we can access static data members. We can change their values also.

The display () method is used to display the record and is called through an object of class Employee.

The objects get the memory in the heap area and the reference variables refer to the objects allocated in the heap memory. In the above example both e1 and e2 are the reference variables that refer to the objects allocated in memory.

 

Another example of static method that performs normal calculations:

Consider the following example in which we are finding the square of a number by using a static method:

CODE:

class Square {

static int sq (int x) {

return x * x;

}

public static void main (string args []) {

int result Square. sq (4);

system. out. println (result);

}

}

OUTPUT:

16

In the above example, the static method is used to find the square of an integer. The method is called directly by using the name of the class and the result is saved in another variable named as ‘result’. Then this variable is printed and square of integer is displayed. The method has a return type that is integer and this return values is saved in the variable ‘result’ which is then printed in main function.

 

Restrictions for static method:

In Java programming language there are two main restrictions for the static methods:

  1. Static method can only use static data member and can only call static methods directly.
  2. The keywords ‘this’ and ‘super’ cannot be used with static context.

Consider the following example:

CODE:

class B {

int x = 2;

public static void main (string args []) {

system. out. println (x);

}

}

OUTPUT:

Compile time Error

In the above example, the main method is static and hence it cannot access the non static data member that is why we got a compilation error.

Q. Why Java main method is static?

Ans. If the main () method is not static then the JVM first had to create the objects then call the main function because of this reason a lot of memory will be consumed. And also the object is not required to call the static method.

 

Java static block:

In Java programming language the static block is used to initialize the static data member. The Java static block is executed before the main method that is at the time when class is loaded.

Example of Static block:

Consider the following example in which we have used the static block:

CODE:

class B {

static {

system. out. println (“Static block is called”);

}

public static void main (string args []) {

system. out. println (“Main method”);

}

}

OUTPUT:

Static block is called

Main method

In the above example, it can be seen that the static block is executed first that is before the main function. We used the print statements to display the message that demonstrate that which either static block was executed first or the main method.

Q. Can we execute a program without main function?

A program without the main method can be executed by using the static block but this was only supported by the previous versions of the JDK. A program without the main method but having a static block cannot be executed in the 1.7 version of the JDK.

Consider the following example in which we have used the static block without main function, we checked that if our program runs or not without the main function, also assume the version to be not JDK 1.7.

CODE:

class B {

static {

system. out. println (“Static block is invoked”);

system. exit (0);

}

}

OUTPUT:

Static block is invoked

If the version was JDK7 or above then output will be:

OUTPUT:

Main method not found in class B, please define the main method as:

public static void main (string args [])