We discussed this and super keywords of Java in our previous article. They are very important when we discuss references and instances of the class. Today again, we are going to discuss the most basic and prominent topic of Java programming language, which is about usage and understandings of the static and final keyword of Java. It’s going to be fun learning them altogether.
I hope you are excited to learn about the static and final keyword in Java.
Understanding static keyword in Java
A programmer needs to optimize the performance of the code and one way to achieve this by optimizing the memory of the program. The static keyword in java is one of them, which is very helpful in memory management. Places, where the static keyword is used, are:
- Variables
- Methods
- Blocks
- Nested Classes
A static variable, or method, or block or Nested class belongs to class memory instead of instance memory.
Let’s understand the usage of java’s static keyword on above mentioned locations with some sample programs.
Java’s static keyword with variables
A variable is called a static variable when it is declared with the static keyword. Therefore, a static variable shares the common property among all the objects of the same class. It doesn’t have any unique value, for example, School’s name, Company’s name. It saves the memory, hence, makes program memory efficient.
Static members get memory at the time of class loading, and it occurs only once. Therefore, the static property is shared among all the objects of the same class and it never changes whenever a new object is created for the class.
Sample Program
package my.project; class Employee{ int empid; String name; static String company ="INVIUL"; Employee(int id, String nam){ empid = id; name = nam; } public void display (){ System.out.println(empid+" "+name+" "+company); } } public class TestEmployee{ public static void main(String args[]){ Employee e1 = new Employee(101,"Avinash"); Employee e2 = new Employee(102,"Mishra"); e1.display(); e2.display(); } }
Counter Program with the Instance variable
package my.project; class CounterProgram{ int count=0; CounterProgram(){ count++; System.out.println(count); } } public class TestClass { public static void main(String args[]){ CounterProgram c1=new CounterProgram(); CounterProgram c2=new CounterProgram(); CounterProgram c3=new CounterProgram(); } }
In this program, the instance variable gets a new memory address for each object; hence, count value never changes. It always shows 1.
Counter Program with Static variable
package my.project; class CounterProgram{ static int count=0; CounterProgram(){ count++; System.out.println(count); } } public class TestClass { public static void main(String args[]){ CounterProgram c1=new CounterProgram(); CounterProgram c2=new CounterProgram(); CounterProgram c3=new CounterProgram(); } }
This program is different from the above program as a static variable has the common sharing with all of the objects of the class; hence, we see an increment in count value whenever a new object is created.
Java’s static keyword with methods
A method becomes static when it is initialized with a static keyword. Some of the important points about static methods are listed below:
- A static method can only manipulate static variables or data members (it cannot access non-static variables or data members directly)
- A static method belongs to class area, not instance area
- An object is not required to invoke the static methods of the class
- this and the super keyword is restricted to be used with static components
Notes: Java main method is static which saves lots of memory by JVM; otherwise, it would have created an object for every run which apparently generates extra memory.
Sample Program
package my.project; class Calculate{ public static int add(int a, int b, int c){ return a+b+c; } } public class TestClass { public static void main(String args[]){ int result=Calculate.add(5, 6, 7); System.out.println(result); } }
Java’s static blocks
There is interesting stuff about static blocks in Java. Till Java v1.6, the static block was also used to execute the program and after the next version that is v1.7, the only main method is used to run the Java program. Isn’t it interesting?
Anyways, static blocks are used to initialize the static data members of the class and it gets executed before the main method at the time of classloading. Do you know why?
Just imagine, if JVM invokes the main method which is static in nature, so it would have static data members and if it’s required to assigns values to those data members before it triggers the main method then how such things will be possible? Thus, to overcome such a situation static block plays a vital role and it assigns the values to static data members and it gets executed before the main method. Hence, the problem solved.
Sample Program
package my.project; public class StaticBlockClass{ static{System.out.println("I am static block");} public static void main(String args[]){ System.out.println("I am main method"); } }
Understanding the final keyword in Java
Unlike static keyword, the final keyword is not used for memory management; rather, it is used to put restrictions on variables, methods, and classes.
Let’s begin our learning journey to understand the final keyword at different locations in Java.
Java’s final keyword with variables
A java variable called a final variable when the final keyword is used with it. If you want to create constants in Java then use the final keyword with the variable, therefore, you can’t change the value of the final variable. An uninitialized final variable doesn’t have any value; hence, it is called a blank final variable. A blank final variable can be initialized from the constructor of the class.
A final variable can also be static, if you assign a static keyword to a blank final variable then such static blank final variable can be initialized from static block only.
Sample Program
package my.project; class Car{ final int speedlimit=90; }
Blank final variable without static
package my.project; public class Car{ final int speedlimit; Car(){ speedlimit=40; System.out.println(speedlimit); } public static void main(String args[]){ new Car(); } }
Static final blank variable
package my.project; public class MyData{ static final int iData; static{ iData=50;} public static void main(String args[]){ System.out.println(MyData.iData); } }
Java’s final keyword with methods
You cannot override final methods. It becomes constant.
Notes: A final method can be inherited & overloaded, but cannot be overridden.
Sample Program
package my.project; class FourLegAnimal{ final void eating(){ System.out.println("Eating...");} } public class Dog extends FourLegAnimal{ public static void main(String args[]){ new Dog().eating(); } }
Java’s final keyword with class
The restriction is the characteristics of the final keyword; therefore, if you make any class as final then you cannot extend that class.
Sample Program
package my.project; final class FourLegAnimal{ final void eating(){ System.out.println("Eating...");} } public class Dog extends FourLegAnimal{ public static void main(String args[]){ new Dog().eating(); } }
One question you may ask here is about making a constructor final. Well, a constructor does not give any return type explicitly, nor we use it for an inheritance, hence, there is no use to put a restriction on any constructor by using the final keyword.
This was all about the static and final keyword in java. Stay connected for more programming articles and do not forget to join our Facebook group.