The entwinement of keywords with variables in Java plays a significant role. In total, there are fifty-seven keywords in Java. Among them, the static keyword plays a vital role in memory management. Programmers use it with various other elements of programming. This article will talk about the Static keyword in detail.
What is Static Keyword in Java?
In Java, static members belong to the class rather than their specific objects. It means that you can access or use any statically declared program element without object creation. Programmers use the static keyword before the method, variable, and class name.
Programmers use this non-access modifier to share the same method or variable of a given class. For creating a static member, precede the declaration with the static keyword. Another significant fact about static members is - once a member is declared static, programmers can access those members before creating the object of the class.
Example
Here is a simple example showing the use of the static keyword.
import java.lang.System.*;
class Main
{
// This is a Static method
static void staticmeth()
{
System.out.println(" We can create the static method without creating the object of the class. ");
}
// This is a normal method
public void NormalMeth() {
System.out.println(" This public method needs to be invoked by creating the object of the class. ");
}
public static void main(String[] args)
{
staticmeth();
Main o1 = new Main();
o1.NormalMeth();
}
}
Here we have declared staticmeth() as static inside which we have placed a message. Now, within the main() you can note that, without creating the class object, you have called the static method. staticmeth() method is used before creating the object of the Main class.
Static Variables
Static variables are those variables that have a unique copy and are globally accessible by any object. Programmers declare the static variables by placing the static keyword followed by the variable name. All the class instances share this variable so that the data becomes sharable to all the classes. We can create static variables at the class-level only.
Syntax
static data_type variable_name;
Example
Here is a code snippet showing the use of static variables.
import java.lang.System.*;
class Main
{
// This is a Static method
static void staticmeth()
{
System.out.println(" We can create the static method without creating the object of the class. ");
}
// This is a normal method
public void NormalMeth() {
System.out.println(" This public method needs to be invoked by creating the object of the class. ");
}
public static void main(String[] args)
{
staticmeth();
Main o1 = new Main();
o1.NormalMeth();
}
}
Within the Stud class, we have created a static String-type variable institute. We also have a constructor that is fetching the student-name and roll number. Then we are printing the institute value from within the disp() method. Note that, when we call the disp() method from within the main(), the institute value remains the same throughout.
Use of Static Variables in Java
- Variables declared as static are common to all the class instances.
- It allows us to create a single copy of the variable utilized and shared with other class instances.
- A Java program initializes a static variable before the creation of any class object.
- We can use static variables when we want to have a variable that illustrates something about the class itself.
- When we need a variable's value same for all the class objects, we declare a variable static.
Static Methods
We might require situations where we need to perform certain operations that are not dependent on any class instance creation. Such a situation demands creating a static method. One common example of a static method in Java is the main().
Syntax
static method_name()
Any static method belongs to a class and not the object. Also, we do not require to create the class object for invoking the static method. A static method is able to access the static data member and as well as alter their value.
Example
Here is a code snippet showing the creation and use of the static method.
import java.lang.System.*;
import java.util.*;
class Main
{
// This is a Static method
static void staticmeth()
{
System.out.println(" This is a static method without creating the object of the class. ");
}
// This is a normal method
public void NormalMeth() {
System.out.println(" This is a public method which requires invoking by creating the object of the class. ");
}
// main() started from here
public static void main(String[] args)
{
// static method invoked before the creation of object
staticmeth();
Main o1 = new Main();
o1.NormalMeth();
}
}
Here we have declared staticmeth() as static inside which we have placed a message within it. Now, from the main() programmers can call the static method without creating the class object. staticmeth() method is used before creating the object of the Main.
Use of Static Method in Java
- When we want to put any code or operation that is not dependable on any object creation, programmers need to place the code within the static variable.
- We declare a method 'static' when we want to share a particular code by all other instance methods.
- When we want to change or override our method definition, we use the static method.
- If we wish to write utility classes whose functionality should remain the same throughout the program execution, the static method comes to the rescue.
Static Block
To use static variables in a program, we sometimes need to initialize them. Programmers use the static block to initialize static variables. Static blocks get executed at the beginning once when the program loads the class.
Example:
import java.lang.System.*;
import java.util.*;
class Main
{
// declaring static variable
static int x = 10;
static int y;
// creating static block
static {
System.out.println( " This is a static block. \n " );
x = 12;
y = x / 3;
}
public static void main(String[] args)
{
// instance of the class not created
System.out.println(" This is executed from main. ");
// accessing the static variables from main()
System.out.println(" Printing the value of x : "+ x);
System.out.println(" Printing the value of y : " + y);
}
}
We have created a class Main and declared the static integer type variable x. Then we have created a static block by simply placing the static keyword with the curly braces where we showed the output and performed some operations. Note that, we do not have to create any class instance within the main(), still the static block gets executed at the beginning. Also, we can access the static block values from anywhere within the program as shown by printing within the main().
Use Static block in Java
- It helps in initializing the static data member.
- If we wish to execute or store any value in a variable before the execution of main(), i.e., at the time of class-loading, the static block comes to the rescue.
Static Class
Java allows programmers to define a class within another class. It is called the nesting of classes. It enables programmers to group logical operations into different classes keeping in mind the use of encapsulation. Nesting of classes also brings readability, and the code becomes easy to maintain. They are called non-static nested classes or inner classes.
Non-static Nested Class Syntax
class Outer_Class
{
....
class Nested_Inner_Class
{
....
}
}
Programmers can define a static nested class by using the static keyword with the nested class. Creating a static nested class makes the inner class object firmly united with the outer class object. A static nested class will not be able to reach any non-static data member or method. Only by using the outer class name, the static nested class can access the non-static class members.
Static Nested Class Syntax
class Outer_Class
{
....
static class Nested_Inner_Class
{
....
}
}
Example of Nested Class (Non-Static)
import java.lang.System.*;
import java.util.*;
class Outer_Class {
// inner class
class Inner_Class {
public void disp() {
System.out.println(" The inner class is called ");
}
}
// Accessing the inner class
void disp_InnerClass() {
Inner_Class in = new Inner_Class();
in.disp();
}
}
public class Main {
public static void main(String args[]) {
// Instantiating outer class for invoking
Outer_Class out = new Outer_Class();
out.disp_InnerClass();
}
}
In this program, we have created two nested classes that are not static by nature. To access the method or any member of the inner class, we can simply call it using the object of the outer class as shown in these two lines
Outer_Class out = new Outer_Class();
out.disp_InnerClass();
Example of Static Nested Class
import java.lang.System.*;
import java.util.*;
// Outer class created
class Main
{
static int numb = 30;
// Inner class created with Static keyword
static class InnerMain
{
void result()
{
System.out.println(" Value is: " + numb);
}
}
public static void main (String args[]) {
Main.InnerMain o1 = new Main.InnerMain();
o1.result();
}
}
In this program, we have created two nested classes where the inner class is declared as static. Now, if you try to access the result() method or any member that is declared within the inner class from the outer class object, you will face difficulty in accessing it directly. To access the static nested class members, you have to invoke them by calling the outer class followed by the period operator and then the inner class and then create the object as shown:
Main.InnerMain o1 = new Main.InnerMain();
Now, using that object, you can access the members of the static nested class: o1.result();
Use Static Class in Java
- We can instantiate a static class without instantiating any other class objects.
- Programmers can implement class member security using the static nested class declaration. It is because you cannot create the instance of an inner class without creating the instance of the outer class.
- Again, static inner classes can help make your program concise and manageable.
- If we want to preserve encapsulation in our program, static classes are the best. It is because they cannot access the non-static members.
- The static class helps in grouping classes together.
Difference Between Static and Non-Static Nested Class in Java
- A static nested class can directly reach or use the static members of the outer class. But to use the members of the outer-class, an outer class object creation is a must.
- A static nested class does not require a reference of the outer-class, whereas a non-static nested-class requires one.
- The static nested class declaration requires the static keyword in the inner class, whereas a non-static nested class does not require any static declaration.
Conclusion
The static keyword plays a significant role in the Java programming environment. Programmers can use it with variables, methods, blocks, and classes. The static class helps in accessing the primary member of the enclosing class with an object reference. If you know how to use the static keyword properly with all the different programming elements, you can benefit from it.