Introduction to Static Keyword in Java
Normally we create an object of the class using the new operator and access the methods and variables. Each instance of a class has its own copy of any member variables and methods. It is also possible to create member variables and methods that belong to the class independent of any object of that class.
So if we want to have one piece of storage for a particular piece of data, regardless of how many objects are created or even no objects are created, Or a method that is not associated with any particular object of a class. We can call that method if no instance of the class has been created. In both the scenario we can achieve using the static keyword.
A class contains two sections
- Variable declaration(instance variables)
- Method declaration(instance methods).
When we declare variables(s) or method(s) is/are static, it means that the data or method is not associated with any particular object instance of that class. Thus even if we never create an object of that class, we can still call them or access the piece of static data.
For a non-static data member or method, we need to create an object of the class as they belong to the particular object they are working with. Since static methods/variables don’t need any objects to be created before they are used, they can not access non-static members and methods. This is because non-static members and methods first tied with an object.
To remember easily we can say anything with the static keyword (modifier) associated with it will be the property of the class but not the property of the object. These are common to all instances of a class. Since there will one class and many objects are created from it, we can say the static keyword associated things are created only once and shared among the objects of that class.
This is somewhat a global variable or global function concept. The meaning of static varies from context to context. Static things load first while we execute any program. Static elements get executed only once at the beginning of the program. Java libraries contain a huge set of static members.
Static keyword can be applied to
- Class
- Methods
- Block
- Variable
- Import
Static Class:
Java, in general, does not allow normal classes to be static but it allows any number of classes created inside a non-static class. They are called Nested Inner class. Nested Inner classes can be static in nature.
Static Methods:
static methods are those methods that belong to a class. They don’t belong to the objects created from the class. It can access only static data but not any non-static data elements. A static method can call only a static method(s) but can not call any non-static methods. A static method can only be accessed directly without creating an object by using the <ClassName>.<MethodName()>.
An interesting thing, a static method can access the members of the class bt creating an object of the class. In that case, members can be static and non-static.
An instance method in a subclass can not override a static method in the base or parent class. Static method in a superclass can not be overridden by non-static methods in a subclass.
A static method in a child class can hide a static method in the superclass.
A static method can not refer to this or super keywords. So we can not call a non-static method from inside a static method. But we can call a static method from inside of a non-static method(by creating an instance of the class).
The restriction for static methods are as follows:
- static methods can not refer to this or super.
- static methods can only access static data members.
- static methods can only call other static methods.
class myStaticTest{
static int i=10;
}
class staticIncrementTest{
public static void increment(){
//Accessing a static variable from a static method by creating Object
myStaticTest SI=new myStaticTest();
SI.i++;
//Accessing a static variable from a static method directly
myStaticTest.i++;
}
}
The main method is a static method hence can be called without creating an object and before any other thing runs.
An example to call a static method from inside of a static method:
public class MyStaticTestDemo {
static int sum(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int ans = MyStaticTestDemo.sum(15, 13);
System.out.println(ans);
}
}
The output of the code: 28 In the above example if we remove the static modifier from the sum subroutine, it will become a nonstatic method. In that case, the static main will try to access the nonstatic sum() method. This is not allowed in java.JVM will throw the below exception: Exception in thread “main” java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method sum(int, int) from the type MyStaticTestDemo at com.techtravelhub.MyStaticTestDemo.main(MyStaticTestDemo.java:8)
An example to call a non-static method from inside of a static method:
public class MyStaticTestDemo {
int sum(int x, int y) {
return x + y;
}
public static void main(String[] args) {
MyStaticTestDemo mstd=new MyStaticTestDemo();
int ans=mstd.sum(12,13);
System.out.println(ans);
}
}
The output of the code: 25
Static Block:
A block that is loaded and executed as soon as JVM loads a java class. Even this happens before the execution of the main method.
There is a popular question asked to write a code to print Hello World without main. The same can be done through this.
A java class can contain one more static initialization block. The static block syntax is as follows:
static{
//code
}
A static initialization block is invoked implicitly/automatically as soon as the class is loaded.
A real example
public class myDemo{
static{
System.out.println("Hello World");
system.exit(0);
}
}
We need to terminate the code as after this the JVM will look for the main method which is not present and gives an error message.
$javac myDemo.java
$java -Xmx128M -Xms16M myDemo
Error: Main method not found in class myDemo, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend JavaFX.application.Application
The advantages of the static block
- It can be used as a dynamic initialization for static variables
- It can be used as a one-time activity, that class needs to be loaded once-like JDBC driver, sound driver.
- It can be used to load a small database or configuration files in Hashtable, properties.
Static Variables:
Again static variables belong to the class and initialized at first during execution. A single copy of the static variable is shared by all instances of the class. A static variable can be accessed directly by using <ClassName>.<VariableName>
a static variable is part of the class, they are defined in. As soon as the class is loaded, these variables are initialized to default values, in case they are not initialized by the developers. These variables act as global variables to track global information in an instance.
public Class myStaticTest{ static int i=10; }
now if we write two lines of code:
myStaticTest t1=new myStaticTest(); myStaticTest t2=new myStaticTest();
at this point, t1.i and t2.i will share the same i and have the same value as 10.
There are two ways to access static data:- by creating an object of that class like t1.i;
- directly through its class name like myStaticTest.i;
Remember that static variables are like normal variables and not constant hence we can do any operations on that variable like- t1.i=ti1.i+1; this will increase the i value by one and i becomes 11. Now all the places where this i is referred will get i=11
here is one example:
public class MyStaticTestDemo {
public static void main(String[] args) {
System.out.println(myStaticTest.i);
staticIncrementTest.increment();
System.out.println(myStaticTest.i);
}
}
class myStaticTest{
static int i=10;
}
class staticIncrementTest{
public static void increment(){
myStaticTest SI=new myStaticTest();
SI.i++;
myStaticTest.i++;
}
}Output of the code: 10 12
Another example:
class MyOperations{ static int addition(int x,int y) { return x+y; } static int substract(int x,int y) { return x-y; } static int multiply(int x,int y) { return x*y; } } public class TestMyOperations{ public static void main(String args[]) { int a=MyOperations.addition(10,15); int b=MyOperations.substract(15,10); int c=MyOperations.multiply(10,15); System.out.println("Addition of these two number "+a); System.out.println("subtract of these two number "+b); System.out.println("multiply of these two number "+c); } }
output of the code:
$javac TestMyOperations.java
$java -Xmx128M -Xms16M TestMyOperations
Addition of these two number 25
subtract of these two number 5
multiply of these two number 150
Another example for static and non static variables:class Student{ int a; //non static initialized to zero static int b;//static initaialized to zero when class is loaded Student() { b++; } public void getData(){ System.out.println(a); System.out.println(b); } // public static void increment() // { // a++; // } //The above code will throw an compilation error- non-static variable a cannot be referenced from a static context // a++; // ^ } public class Demo{ public static void main(String []args){ Student s1=new Student(); Student s2=new Student(); s1.getData(); s2.getData(); Student.b++; s1.getData(); } }
the output of the code:
$javac Demo.java
$java -Xmx128M -Xms16M Demo
2
2
3It is often told that static methods are not proper object-oriented design as they have the semantics of a global function. And with static methods, we do not send messages to the objects as there is no this keyword support. However, they are pragmatic and useful.
Static Imports:
Import directives or statements provide us to refer to a class. like javax.swing.JPanel for JPanel. If we see the directive is a little complex and compound in nature.Every time we need to mention in order to use them.To refer the static members we need to mention package name and variable name like-Math.Sqrt or System.out.
static imports are a little different thing than class, methods, and variables. The purpose of the static import eliminates the need of the qualifying a static member with the class name. The static import is similar like normal import.We can use the import statement to import classes from packages and use them without providing the qualifying package name. Similarly, we can use the static import statement to import static members from a class and use them without providing the fully qualified class name.
The syntax is as follows:
import static <packageName>.<subPackageName>.<className>.staticMemberName;
or
import static <packageName>.<subPackageName>.<className>.*;
Before introducing the static import feature,we had to use the static member with the fully qualifying class name.
It is introduced in java in Java 5.0.
Example:double areaOfCircle=Math.PI*radious*radious
PI is the static member of the Math class.
We can use the static member in the code without providing fully qualified class name. or interface name.static import feature eliminates the redundancy of using the qualified class name with the static member name and increase the readability of the code.Use of a Class:
import static java.lang.Math.*; public class MyMathOperations{ public void circle(double r){ double area=PI*r*r; System.out.println("The area of the circle is"+area); } public static void main(String args[]) { MyMathOperations mathOps=new MyMathOperations(); mathOps.circle(2.3); } }
The output of the code:
$javac MyMathOperations.java
$java -Xmx128M -Xms16M MyMathOperations
The area of the circle is16.619025137490002Use of an interface:
public interface Student_Grade { public static final double StudentsWithAGrade=.5; public static final double StudentsWithBGrade=.25; }
import static Student.Student_Deatils.Student_Grade; Class StudentFinalGrade{ public static void main(String args[]){ double A_grade_Student=StudentsWithAGrade*StudentsWithCurrentGrade; double B_grade_Student=StudentsWithBGrade*StudentsWithCurrentGrade; } }
Similarly if we import java.lang.System.out then we can directly use out.println() instead of System.out.println().
static import statements requires a (packageName) even for classes in the standard package like java.lang. So it is not possible to do a static import from a class which stays in the default package.
Another Example:public class StaticTest{ public static void main(String []args){ int count=0; StaticClass x,y; //x.printCount(); //y.printCount(); // As we have not initialized the x,y jvm will throw an error stating that x,y might not have been initialized. At this point, as we have not called the constructor the increment operator will not get executed and will hold the default value as count=0; the output will be 0,0,0 StaticClass.printCount(); // prints default value of the count as 0 x=new StaticClass(); x.printCount(); //as the constructor is called , count value is increased by 1 so the output value is 1 y=new StaticClass(); y.printCount(); //as the constructor is called , count value is increased by 1 so the output value is 2 } } class StaticClass{ static int count; StaticClass() { count++; } public static void printCount() { System.out.println(count); } }
Output of the code:
$javac StaticTest.java
$java -Xmx128M -Xms16M StaticTest
1
2Read more: class-virtualmachineerror-in-java
The conclusion on Static keyword in Java
- The method belongs to the class and not associated with a particular object of the class.
- Each Enum constants are static fields that refer to the object for the corresponding values.
- Java language actually helps to move forward towards an international character set of 16 bits along with a supplement of 21 bits character set.
- In Java pass, the object often means pass the object reference class variables are such fields. Fields are shared among objects of the class. We can make variables class-specific by declaring them static. This is an Object variable.