Static keyword in java

Every instance of a class has its own state and behavior, whenever the state of a particular instance is modified, other instances are not affected.

In java, a static keyword is normally applied to class members or methods in order to make them shared between all instances, the static keyword forces the variable or the method to only have one copy in the memory regardless how many instances of the class are created.

1. Static variable

A static variable is a variable which belongs to the class and has one value shared between all instances of the class. Any modification done on the variable is reflected on all the instances.

The typical usage of a static variable is when you define programatically an incremental ID of a class, in the following example, we define a Student class which holds id and name , the id is assigned programatically and is incremented upon each object creation.

In the above class, we define ID as an instance variable since its value should be unique and different between all instances, at the same time we define a static variable called studentNumber which is incremented at each object creation. Each time a new instance of the class is created, the ID variable is assigned to the latest value of studentNumber.

In order to understand how static variables work, we create the following test method:

Output:

we notice here that the value of studentNumber is shared between student1 and student2, while at the same time we are able to set a unique ID for each student.

2. Static method

A static method is a method which is shared between all instances of the class, developers normally use static keyword with utility methods which do some common functionality that is regularly used anywhere in the application, utility methods are invoked by the class name without the need to create an object before. e.g. <ClassName>.<MethodName>

Some rules apply when defining a static method:

  1. Static methods can’t use instance variables, they usually take input from the parameters , perform some business then return some result.
  2. Static methods can’t invoke a non-static method.
  3. Static methods can’t be overridden.
  4. You can’t use this keyword inside a static method.

A typical example of a static method is an email validator , which takes as input an email then checks whether its valid or not.

3. Static block

A static block is a block of statements inside a java class which is executed when a class is first loaded into the JVM e.g. it is initialized the first time the class is referenced in the code.

Normally, static blocks are used for initializing static class variables, and they are different from constructors in that static blocks execute only once at the time of class loading and initialization by JVM while constructor is called every time a new instance of the class is created.

P.S: you can’t use instance variables or invoke instance methods inside the static block.

A typical example of using a static block is when you support retrieving an Enum instance by its value, to do that you define a hashmap as a static variable which maps each value to its corresponding Enum instance, the map is initialized and filled inside a static block before the Enum is ever used in the application.

4. Some points to consider when using static keyword

  1. Static variables and methods are accessed through the class name: <ClassName>.<variableName> or <ClassName>.<methodName>
  2. Static keyword can be applied to variable, method, or inner class, it can’t be applied on top level class.
  3. Static fields are initialized at the time of class loading opposite to instance variables which are initialized at the instance creation.
  4. If a static block throws an exception, then you may get java.lang.NoClassDefFounfError when you try to access the class which failed to load.

5. Disadvantage of static keyword

Using the static keyword inside your application would lead to some serious problems:

  1. Static variables are shared between all class instances, this causes major problems in multi-threaded environments where multiple threads can access and modify the variable at the same time. So developers should take attention when accessing the static variables inside the application, and they should surround each access with Synchronized block.
  2. Static methods can’t be mocked, mocking is a mechanism used in unit testing in order to fake the business of some methods, when a method is defined as static there is no way to mock its business.

 

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
husseinterekParas Chawla Recent comment authors
newest oldest most voted
Paras Chawla
Guest
Paras Chawla

[Author] Static methods can’t be mocked, mocking is a mechanism used in unit testing in order to fake the business of some methods, when a method is defined as static there is no way to mock its business.

[Reader] By writing above, do you mean that if we run JUnit test case on any utility method having static keyword, it won’t run ?
Thanks for the article. Keep writing