Throughout this section, you will gain an understanding of the static keyword in Java. This keyword serves a specific purpose in the language, allowing for the effective management of memory and the accessibility of class-level members when applied to variables, methods, blocks, and nested classes.
What is the Static Keyword in Java?
In Java, the static keyword is primarily utilized for memory management purposes. It can be employed with variables, methods, blocks, and nested classes. The static keyword is associated with the class rather than a specific instance of the class.
Types of Static Members
The static keyword can be used with the following:
- Variable (also known as a class variable)
- Method (also known as a class method)
- Block
- Nested class
Uses of static Keyword
Apart from managing memory, the static keyword in Java serves various other purposes. In the context of variables, it denotes that the variable is shared among all instances of the class and is associated with the class itself rather than individual instances.
Static methods are accessible globally within a program as they do not require an object instance to be created first. Static blocks are employed to initialize static variables or perform tasks that need to be executed only once when the class is loaded.
In addition, nested static classes have the capability to be created independently while remaining associated with the enclosing class. Additionally, static variables and methods can be accessed directly using class names, removing the necessity to instantiate an object. This feature is particularly advantageous for constants or utility methods.
Characteristics of static Keyword
Here are the characteristics of the static keyword:
- Belongs to the Class, Not the Object: Anything marked as static is tied to the class itself, not individual objects. It means all objects share the same static variables and methods.
- Access Without an Object: Since static members belong to the class, you can access them directly using the class name (ClassName.methodName). No need to create an object.
- Static Methods Cannot Use Instance Variables Directly: A static method does not know about specific objects, so it cannot directly access non-static (instance) variables or methods.
- Main Method is Static: The main method in Java is static so that Java can run the program without creating an object first.
- Executed Once When the Class is Loaded: A static block runs once when the class is first loaded, making it useful for initializing things like constants.
- Not Overridden Like Normal Methods: Static methods do not follow typical method overriding. If a subclass defines the same static method, it's more like re-declaring it rather than overriding it.
1. Java Static Variable
If we declare any variable as static, it is known as a static variable.
- The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
- The static variable gets memory only once in the class area at the time of class loading.
- Static variables in Java are also initialized to default values if not explicitly initialized by the programmer. They can be accessed directly using the class name without needing to create an instance of the class.
- Static variables are shared among all instances of the class, meaning if the value of a static variable is changed in one instance, it will reflect the change in all other instances as well.
Example of Static Variable
This example showcases the concept of a static variable in Java.
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Main class to show the values of objects
public class Main{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
Explanation:
This Java code showcases the utilization of static variables. Apart from the static variable named college, the Student class specifies two instance variables: rollno and name. It includes a constructor to assign the initial values to the instance variables and a display method to print out the rollno, name, and college values.
Two instances of the Student class, s1 and s2, are instantiated with distinct roll numbers and names within the TestStaticVariable1 class. Subsequently, the display method of each instance is invoked to showcase their specific details. To alter the college name universally for all instances, one can uncomment the line where Student.college is set to "BBDIT", illustrating the sharing of static variables across all class instances.
Example: Counter Without Using Static Variable
In this instance, we've established an instance variable called "count" that undergoes incrementation within the constructor. Due to the instance variable being allocated memory during object instantiation, each object possesses its own version of the instance variable. Any incrementation applied to it will not affect other objects, resulting in every object having the value of 1 stored in the "count" variable.
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
System.out.println(count);
}
}
public class Main{
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
1
1
Explanation:
This Java program showcases the concept of instance variables that are unique to individual objects created from a class. Within the Counter class, the count variable serves as an instance variable, being assigned memory whenever a new object of the class is created, with an initial value of zero.
Upon creating an object, the constructor will display the existing value of the count variable and then increment it. Within the main routine, three Counter instances (c1, c2, and c3) are established, each with its own count variable. Consequently, the count is incremented autonomously for every generated object, leading to a progressive display of the count values for each object.
Example: Counter Using Static Variable
As previously stated, a static variable is allocated memory only once; if an object modifies the value of the static variable, the value will persist.
//Java Program to illustrate the use of static variable which
//is shared with all objects.
class Counter{
static int count=0;//will get memory only once and retains its value
Counter(){
count++;//incrementing value of static variable
System.out.println(count);
}
}
public class Main{
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
2
3
Explanation:
The following Java code showcases the usage of a static variable that is accessible to all instances of a class. In the Counter2 class, the count variable is defined as static, guaranteeing that it is initialized once and maintains its value across all objects of the class.
Whenever an instance of the class is initialized, the constructor increases the static variable count and displays the updated value. Within the main function, three Counter2 instances (c1, c2, and c3) are created. Since they all utilize the common static variable count, its value increases successively with each object creation, showcasing the shared characteristic of static variables across all class instances.
2. Java Static Method
If we apply a static keyword with any method, it is known as a static method.
- A static method belongs to the class rather than the object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- A static method can access static data members and can change their value of it.
Example of Static Method
Let's consider another illustration to showcase the utilization of a static method in Java.
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Main class to create and display the values of object
public class Main{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
The following Java code example showcases the implementation of a static method within a class. Along with a static variable named college, the Student class specifies two instance variables: rollno and name. To modify the value of the static variable college, a static method named change is employed.
Moreover, within the class, there exists a constructor responsible for setting the initial values of instance variables and a display function that outputs the roll number, name, and college details. The primary function within the TestStaticMethod class demonstrates the application of the change method to update the college information.
Subsequently, the display function is employed to instantiate three Student instances (s1, s2, and s3) with unique roll numbers and names, showcasing their information. This demonstrates the impact of the static function change on the static attribute college across all class instances.
Example: Performing Normal Calculations
Let's explore an additional illustration of a static method that executes a standard calculation.
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
}
public class Main{
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:
Explanation:
In this Java example, we demonstrate the calculation of the cube of a specified number through the utilization of a static function. Within the Calculate class, the static function cube(int x) conducts three multiplications of the integer argument x in order to produce the cube value.
In this example, the main method of the same class showcases the direct utilization of the static method cube from the class Calculate without the need to instantiate an object of the class first.
In this illustration, the cube function is utilized with the parameter 5, and the output is stored in the variable result prior to being displayed on the console. This example showcases the simplicity and efficiency of employing static functions for regular calculations or tasks that do not necessitate the instantiation of objects.
Restrictions for the Static Method
Two primary limitations exist for static methods:
- Static methods are unable to utilize non-static data members or directly invoke non-static methods.
- The keywords "this" and "super" are prohibited within a static context.
Example:
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Output:
Compile Time Error
Explanation:
Within the Java code snippet offered, there is a class denoted as A, encompassing a non-static instance variable initialized to 40. Despite this, an endeavor is made to directly reference the instance variable a by employing System.out.println(a) within the main method of class A.
When working with static methods in Java, it is important to note that they are unable to directly interact with non-static variables. This limitation can result in a compilation issue. To access a non-static variable within a static method like main, an instance of the class containing the variable needs to be created first. Once the instance, for example, 'obj', of class A is created, the non-static variable 'a' can then be accessed through this instance. Therefore, to access 'a' within the main method, it is necessary to instantiate class A using code such as 'A obj = new A;' followed by 'System.out.println(obj.a);'.
3. Java Static Block
- It is used to initialize the static data member.
- It is executed before the main method at the time of class loading.
Example of Static Block
Let's consider an example to illustrate the concept of a static block in Java.
//Java program to illustrate the use of static block
public class Main{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("main() method is invoked");
}
}
Output:
static block is invoked
main() method is invoked
Explanation:
Within the provided Java code, there exists a class denoted as A2. This class contains a static block, which is a segment of code enclosed by curly braces and identified with the static keyword. Static blocks are executed singularly when the class is loaded into memory, preceding the invocation of the main method or the instantiation of any class object.
In this scenario, the static block includes the code System.out.println("static block is invoked"), which displays the text "static block is invoked" on the console upon the loading of the class A2 into memory.
Moreover, within the A2 class, there exists a main function that displays "Hello main" on the console upon execution. Given that the main function serves as the program's starting point, it necessitates explicit invocation, usually by the Java Virtual Machine (JVM) during program execution.
Consequently, upon executing the program, the static block is the initial code to run. It displays the message defined within the block. Subsequently, the main method is executed, outputting "Hello main" to the console.
Using Static Block to Run a Program
In the past, running a Java program was achievable by solely utilizing a static block that executed upon class loading. Nevertheless, starting from JDK 1.7, the presence of a main method has become mandatory, rendering it impossible for a program to function solely based on a static block.
In this instance, we will illustrate a Java program that incorporates a static block.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:
static block is invoked
Since JDK 1.7 and above, output would be:
Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Explanation:
In the Java code snippet, Class A3 contains a static block that triggers System.exit(0); to terminate the program. This action is taken after displaying "static block is invoked" on the console. As a result, upon loading into memory, the static block executes, outputs the message, and promptly halts the program to prevent further code execution.
4. Static Nested Classes
A static nested class is defined using the static modifier. It functions similarly to a standard top-level class but is enclosed for organizational purposes. Unlike inner classes, static nested classes are unable to access non-static members of the enclosing class directly.
Syntax
It has the following syntax:
class A{
static class B{}//static nested class
}
Example of Nested Static Class
Below is an illustration showcasing a static nested class that portrays a Library and a Book within it:
class Library {
static class Book {
void info() {
System.out.println("This is a library book");
}
}
}
public class Test {
public static void main(String[] args) {
Library.Book myBook = new Library.Book();
myBook.info();
}
}
Output:
This is a library book
Advantages of static Keyword
The following are the advantages of using static keyword in Java:
- Saves Memory: Instead of each object having its own copy of a variable, static variables are shared across all objects of the class. This saves memory because only one copy exists.
- Faster Access: Since static members belong to the class itself, we don't need to create an object to use them. We can just call them using the class name, making your code run faster.
- Great for Utility Methods: Some methods don't rely on object data, like Math.sqrt or Integer.parseInt. Marking them static allows us to use them directly without creating an object.
- Good for Constants: If a value never changes, like PI = 3.14159, making it static final ensures that there's only one copy, making your code more efficient.
- Keeps Code Organized: Static methods help keep related logic in one place. For example, if we have a DatabaseHelper class, its connect and disconnect methods can be static, so we do not have to create an object just to use them.
- Runs Automatically When the Class Loads: Static blocks execute when the class is loaded. It is useful for setting up configurations like initializing a database connection or loading files before our program starts.
- Reduces Object Dependency: Static methods do not rely on an object's state, making them useful in cases where creating an object would be unnecessary or inefficient.