Categories: Java

Static keyword in Java

In Java, the static keyword is mostly used to control memory. It is also used to share a class’s identical variable or method. Static keywords can be used with variables, methods, blocks, and nested classes.

The static keyword refers to a class rather than a specific instance of that class. A constant variable or a method that is the same for every instance of a class is designated with the static keyword.

In Java, the static keyword is a non-access modifier that can be used for the following:

  1. Blocks
  2. Variables
  3. Methods
  4. Classes
Static variables:

When a variable is declared as static, a single copy of the variable is made at the class level and shared among all objects. Static variables, on the other hand, are effectively global variables. The static variable is shared by all instances of the class.

Important considerations for static variables include:

  • Only at the class level can we establish static variables.
  • In a program, static blocks and static variables are executed in the order in which they appear.

The Java program below shows how static blocks and static variables are executed in the order in which they appear in a program.


class Student
{
    int roll;
    String name;
    static String school = "Coderzpy High School";

    public void show()
    {
        System.out.println(roll + "-" + name + "-" + school);
    }

    public static void main( String[] args )
    {
        Student s1 = new Student();
        s1.roll = 11;
        s1.name = "Abhijit";
        s1.show();

        Student s2 = new Student();
        s2.roll = 28;
        s2.name = "Ankit";
        s2.show();
    }

}
 
Output:
11-Abhijit-Coderzpy High School 
28-Ankit-Coderzpy High School
Static methods:


The static method is defined as a method that is declared using the static keyword. The main() method is the most common example of a static method. Any static member of a class can be accessed before any objects of that class are generated, and without requiring a reference to any object.

Static methods are subject to the following constraints:

  • They can only call other static methods directly.
  • They can only access static data directly.
  • They are not allowed to use the words “this” or “super” in any way.


The java application to demonstrate static method constraints is shown below:


class Test
{

  public static void color(String c)
  {  
    System.out.println("color is "+c);
  }

  public static void main (String[] arg)
  {
    color("black");   //static method color() is called without any instance of class.
  }
}
 
Output:
color is black
Static block:

Static data members are initialized using the static block. The static block runs before the main() procedure.

You can declare a static block that gets executed exactly once when the class is first loaded if you need to do the computation to initialize your static variables.

Consider the Java program below, which demonstrates the use of static blocks.


class Test
{
 static int a = 10;
 static int b;
 
 // static block
 static {
  System.out.println("Static block initialized.");
  b = a * 4;
 }

 public static void main(String[] args)
 {
 System.out.println("from main");
 System.out.println("Value of a : "+a);
 System.out.println("Value of b : "+b);
 }
}
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40
Static Classes:


If a class is nested, it can only be made static. We can’t use the static modifier on top-level classes, but we can use it on nested classes. Nested static classes are an example of this type of class. A reference to the Outer class is not required for a nested static class. In this scenario, a static class can’t access the Outer class’s non-static members.


import java.io.*;

public class Demo {

 private static String str = "Hello Coderzpy!";

 // Static class
 static class MyNestedClass {
  
  // non-static method
  public void disp(){
  System.out.println(str);
  }
 }
 
 public static void main(String args[])
 {
  Demo.MyNestedClass obj
   = new Demo.MyNestedClass();
  obj.disp();
 }
}
Output:
Hello Coderzpy!

Note: also read about the Garbage Collection in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago