Skip to main content

Static keyword in Java (Static class, variable, method and block)


In this blog we learn about Static Class, Variables, Methods and Block in Java.

What is Static Keyword in Java? | What is static class, variable, method and block in java?

Static keyword is used for memory management in java.
Static keyword used in java with class, variables, methods. We can also use static block in java.

Static members are class specific means we can directly access without creating object of class. that is main advantage of static.
We can directly use static members using class.

In java, Math class have almost static data member using that we can directly work on math function without creating object of that.

Static keyword is reserved in java means we can not used as identifiers.

Static can be from following :-
  • Static Class
  • Static Variables
  • Static Methods
  • Static Blocks
Example :- Static demo using Math class method and variable.
class StaticDemo{
    public static void main(String args[]) {

        double piValue = Math.PI;
        System.out.println("Pi Value = "+ piValue);

        double absoluteValue = Math.abs(-1.2);
        System.out.println("Absolute Value = " + absoluteValue);       

        double squareRoot = Math.sqrt(25);
        System.out.println("Square Root of 25 is = "+squareRoot);      
       
    }
}

Output :-
Pi Value = 3.141592653589793
Absolute Value = 1.2
Square Root of 25 is = 5.0

Static Class
Static class used only with nested class. In java root class is not declare with static but we can declare static class in nested. nested means class inside class.
Means we can only use static class in inner class.
Following main criteria of static class.
  • Nested static class doesn’t need reference of Outer class
  • A static class cannot access non-static members of the Outer class
lets see example for better understanding  of static nested class.

public class StaticDemo {

    //Static nested class
    static class NestedStaticClass{
       
        //non-static method
        public void display(){
            System.out.println("Inside Nested Static Class");
        }
    }
   
    public static void main(String args[]){
        StaticDemo.NestedStaticClass obj = new StaticDemo.NestedStaticClass();
        obj.display();
    }
}

Output :-
Inside Nested Static Class

Why we use static class?
A good example of static class is in defining utility or library classes where instantiation would not make sense.
A great example is Math class that contains some mathematical constants such as PI and E that simply provides mathematical calculations like we shown above example.

Static Variables
Static variable means declare variable with static keyword.
  • Static String CollegeName
In java when we create static variable then only one single copy created and use all over java class as single copy. All instances of class share same static variable.

Static variable is created at class level means we can not create static variables inside method. if we try to create one it gives error.

Static variables are created only once when class is load.

Static variable is used to refer common properties of object. Means like if there is Student object and for all student object college name is same so we can assign college name variable as static so we do not have to assign different variable for same name.
Class Student {
    String studentName;
    int rollNumber;
    static String collegeName = "College_Name";
}
So, when different student object created then only one collegeName variable created.
Following main criteria for static variable.
  • Static variables declare only at class level.
  • Static variables are executed as it defined in our class.
Lets see example of static variables.
class Student{
    //instance variable
    int rollNumber;
    String studentName; 
    //static variable
    static String collegeName ="IIT"; 
   
    //constructor 
    Student(String studentName, int rollNumber){ 
        this.studentName = studentName;
        this.rollNumber = rollNumber;
    } 

    void displayStudent() {
        System.out.println(studentName + " " + rollNumber + " " +collegeName);

    } 


public class StaticDemo{ 
    public static void main(String args[]){ 

        Student objOne = new Student("StudentOne", 1); 
        Student objTwo = new Student("StudentTwo", 2); 
        Student objThree = new Student("StudentThree", 3); 
       
        objOne.displayStudent(); 
        objTwo.displayStudent(); 
        objThree.displayStudent();

    } 
}

Output :-
StudentOne 1 IIT
StudentTwo 2 IIT


Lets see how Static variable is memory efficient.
Example :- Static variable for memory efficint
class StaticDemo{
   
    static int numberOne = 0; 
    int numberTwo = 0; 

    StaticDemo(){ 
        System.out.println("Static Variable = " +numberOne++ +" "+
            "Non Static Variable = "+numberTwo++);
    } 
     
    public static void main(String args[]) {
        //creating objects 
        StaticDemo obj1 = new StaticDemo(); 
        StaticDemo obj2 = new StaticDemo(); 
        StaticDemo obj3 = new StaticDemo();
    }
}

Output :-
Static Variable = 0 Non Static Variable = 0
Static Variable = 1 Non Static Variable = 0
Static Variable = 2 Non Static Variable = 0

In above example, numberOne is static and numberTwo is non static variable. so static variable created once and use every time when we create new object so when we create three new object static variable is use same old variable so its value changing from 0 to 3.
But non static variable is created every time and it does not sum its number because every time we create new object non static variable created again.

Advantages of Static variables
  • Static variables are memory efficient.
  • No need to declare extra variable for same name like college name, office name, etc.

Static Methods
When method are declared with static keyword its called static method.
In java, main is static method this is best example of static method that you can refer.
Main method is static in java so we can directly call this method without creating object.
  • Static method can access only another static method, but non static method can call static method.
  • Static method can not call another non static method.
  • We can directly call static method without creating Object.
  • Using static method we can change static data member value.
  • Static methods can not refer super keyword or this keyword.
Lets see example of static method.

class StaticDemo{
    static String BlogName = "Programming Blog";
   
    //Static method
    static void staticMethod()
    {
        System.out.println(BlogName);
    }

    // Non-static method
    void nonStaticMethod()
    {
        //Static method called in non-static method
        staticMethod();
    }
 
    //Static method
    public static void main(String args[])
    {

         //You need to create object to call this non-static method
        StaticDemo obj = new StaticDemo();
        obj.nonStaticMethod();
 
        //Static method called in another static method main
        staticMethod();
    }
}

Output :-
Programming Blog
Programming Blog

Static Blocks
Static blocks are used to initialize static variables. Static blocks are executed when class is load.
In java, we can have more than one static blocks. and they load as we defined in our class.
Static block executed before main method.
Static block is defined using static keyword name only.
Syntax of Static block:-
static {
    // Static data member
}

Lets see simple example of static block
Example 1 :- Static block demo
class StaticDemo{

    static {
        System.out.println("Inside Static Block");
    }
 
    public static void main(String args[])
    {
        System.out.println("Main Method");
    }
}

Output :-
Inside Static Block
Main Method

You can see at above example static block load before main method and print "Inside Static Block" and after run main method.

Example 2 :- Static block with two static block
class StaticDemo{

    static {
        System.out.println("Inside First Static Block");
    }
   
    static {
        System.out.println("Inside Second Static Block");
    }
 
    public static void main(String args[])
    {
        System.out.println("Main Method");
    }
}

Output :-
Inside First Static Block
Inside Second Static Block
Main Method

Example 3 :- Static block with static variables and method.
class StaticDemo{
   
   static int numberOne = 10;
   static int numberTwo = 20;
   static int numberThree = 30;

   static {
       System.out.println("Inside First Static block.");
       //Change The value of number one
       numberOne += numberTwo;
   }
   static {
       System.out.println("Second Static block.");
       //Change the value of number two
       numberThree = 40;
   }

   static void display() {
       System.out.println("Number One = " + numberOne);
       System.out.println("Number Two = " + numberTwo);
       System.out.println("Number Three = " + numberThree);
   }

   public static void main(String args[]) {
       display();
   }
}

Output :-
Inside First Static block.
Second Static block.
Number One = 30
Number Two = 20
Number Three = 40

OTHER ARTICLES YOU MAY LIKE :-

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...