What is Java static keyword, static variable, static method?

What is Java static keyword, static variable, static method?

Java static is keyword used as an access modifier. It modifies the accessing technique of variables and methods in Java coding. "static" keyword can be applied to variables, methods, inner classes and blocks.

We know, to call an instance variable and method, Java requires an object (and thus Java maintains encapsulation). But declaring a variable and method as static, an object is not required to call. That is, a static variable and static method can be called without the help of an object. It is the facility static gives but we loose encapsulation. Of course, it is not a minus point as sometimes between objects encapsulation is not required. In this tutorial, we discuss each concept clearly.

A Java static variable or method can be called in three ways.

  1. without object
  2. with object
  3. with class name

1. Using Java static variable

Java static
The code is well commented. The same case with methods also and let us see one example.

2. Using Java static methods

Java static
Why static variable is called a “class variable”?

3. Does static maintain Encapsulation?

First let us write an example and then discuss.

Java static

In the above code, observe the screenshot, if emp1 salary changes emp2 salary is also gets effected and similarly when emp2 salary is changed, emp1 salary gets effected. This is not encapsulation. With static variable encapsulation is not maintained. Why it is so? It is because the same salary variable (or address) is referred (or pointed) by all the objects of the class. That is, all objects of the whole class uses the same location. For this reason, static variable is known as class variable. Note that, with non-static variable, each object maintains its own location (or copy) separately.

4. When to use Java static variables?

  1. When encapsulation is not required. For example, three partners exist in a business with a joint account. If the balance in the account is 1 lakh, if one partner draws one lakh, other partners cannot draw one lakh again. That is, between all the partners there should be a common balance variable and it is achieved with static keyword as static balance.
  2. Many methods of many classes in Java API are declared static to allow the Programmer to call them without then need of creation of object. Ex: Character and Math etc.

Leave a Reply

Your email address will not be published. Required fields are marked *