JavaRush /Java Blog /Random EN /Coffee break #142. What role does the static keyword play...

Coffee break #142. What role does the static keyword play in Java?

Published in the Random EN group
Source: FreeCodeCamp The static keyword can be used in different parts of Java code such as variables, methods, and static blocks. Today we will find out exactly how it can be applied in practice. The main purpose of using the staticCoffee break #142.  What role does the static keyword play in Java?  - 1 keyword in Java is to save memory. When we create a variable in a class that will be accessed by other classes, we must first create an instance of the class and then assign a new value to each instance of the variable. This is necessary so that the values ​​of the new variables are the same for all new classes/objects. But when we create static variables, their value remains constant in all other classes and we don't need to create an instance to use the variable. This way we create the variable once, so the memory is allocated only once. You will understand this better with a few examples in this article.

How to create a static variable in Java

To understand how to use the static keyword when creating variables, let's look at the usual way of creating variables that are shared by each instance of a class.
class Student {
    String studentName;
    String course;
    String school;

    public static void main(String[] args) {
        Student Student1 = new Student();
        Student Student2 = new Student();

        Student1.studentName = "Ihechikara";
        Student1.course = "Data Visualization";
        Student1.school = "freeCodeCamp";

        Student2.studentName = "John";
        Student2.course = "Data Analysis with Python";
        Student2.school = "freeCodeCamp";

        System.out.println(Student1.studentName + " " + Student1.course + " " + Student1.school + "\n");
        // Ihechikara Data Visualization freeCodeCamp
        System.out.println(Student2.studentName + " " + Student2.course + " " + Student2.school);
        // John Data Analysis with Python freeCodeCamp
    }
}
I'll explain what happened in the above code step by step. We have created a Student class with three variables - studentName , course and school . We then created two instances of the Student class :
Student Student1 = new Student();
Student Student2 = new Student();
The first instance is Student1 , which has access to variables created in its class, has the following values:
Student1.studentName = "Ihechikara";
Student1.course = "Data Visualization";
Student1.school = "freeCodeCamp";
The second instance had the following meanings:
Student2.studentName = "John";
Student2.course = "Data Analysis with Python";
Student2.school = "freeCodeCamp";
If you look closely, you will find that both students have the same school name - “freeCodeCamp”. But what if we had to create 100 students for the same school? This means that we will initialize the variable with the same value 100 times, allocating new memory each time. This may not be a problem for some, but in a large codebase it can significantly slow down the program. To solve this issue, we will use the static keyword to create the school variable . After this, all instances of the class can use this variable. Something like this:
class Student {
    String studentName;
    String course;
    static String school;

    public static void main(String[] args) {
        Student Student1 = new Student();
        Student Student2 = new Student();


        Student1.studentName = "Ihechikara";
        Student1.course = "Data Visualization";
        Student1.school = "freeCodeCamp";


        Student2.studentName = "John";
        Student2.course = "Data Analysis with Python";

        System.out.println(Student1.studentName + " " + Student1.course + " " + Student1.school + "\n");
        // Ihechikara Data Visualization freeCodeCamp
        System.out.println(Student2.studentName + " " + Student2.course + " " + Student2.school);
        // John Data Analysis with Python freeCodeCamp
    }
}
In this code, we have created a static variable called school . Notice that the static keyword precedes the data type and variable name: static String school = "freeCodeCamp"; . Now when we create a new instance of our class, we don't need to initialize the school variable for each instance. In our code, we assigned a value to a variable only in the first instance, and then it was inherited by the next instance. Note that changing the value of a static variable anywhere in the code overrides the value in other parts of the code where it was previously declared. Thus, you should only use the static keyword for variables that are intended to remain constant in the program. You can also assign a value to a variable when you create it so that you don't have to declare it again when you instantiate the class: static String school = "freeCodeCamp"; . This is what you get if you use this method:
class Student {
    String studentName;
    String course;
    static String school = "freeCodeCamp";

    public static void main(String[] args) {
        Student Student1 = new Student();
        Student Student2 = new Student();


        Student1.studentName = "Ihechikara";
        Student1.course = "Data Visualization";

        Student2.studentName = "John";
        Student2.course = "Data Analysis with Python";

        System.out.println(Student1.studentName + " " + Student1.course + " " + Student1.school + "\n");
        // Ihechikara Data Visualization freeCodeCamp
        System.out.println(Student2.studentName + " " + Student2.course + " " + Student2.school);
        // John Data Analysis with Python freeCodeCamp
    }
}
Now you will see how to initialize static variables using static blocks.

How to create a static method in Java

Before we look at the example, here are some things you need to know about static methods in Java:
  • Static methods can only access and modify static variables.
  • Static methods can be called/used without creating an instance of the class.
Here's an example to help you understand this:
class EvenNumber {

    static int evenNumber;

    static void incrementBy2(){
        evenNumber = evenNumber + 2;
        System.out.println(evenNumber);
    }

    public static void main(String[] args) {
        incrementBy2(); // 2
        incrementBy2(); // 4
        incrementBy2(); // 6
        incrementBy2(); // 8
    }
}
In the above code, we have created an integer ( evenNumber ) in a class called EvenNumber . Our static method is called incrementBy2() . This method increments the value of the integer evenNumber and prints its value. Without creating an instance of the class, we were able to call the incrementBy2() method in the program's main method . Each time we called the method, evenNumber was incremented by 2 and printed. You can also append the class name to a method using dot notation when calling the method: EvenNumber.incrementBy2(); . Each static method belongs to the class, not to instances of the class.

How to create a static block in Java

Static blocks in Java are similar to constructors. We can use them to initialize static variables, they are executed by the compiler before the main method .
class Block {

    static int year;

    static {
        year = 2022;
        System.out.println("This code block got executed first");
    }

    public static void main(String[] args) {

        System.out.println("Hello World");
        System.out.println(year);
    }
}
In the code above, we created a static integer variable year . We then initialized it in a static block:
static {
        year = 2022;
        System.out.println("This code block got executed first");
    }
As you can see, a static block can be created using the static keyword followed by curly braces. In the static block of our code, we initialized the year variable with the value 2022. We also printed out some text - “This code block got executed first.” In the main method we printed “Hello World” and a static variable year . In the console, the code will be executed in this order:
This code block got executed first Hello World 2022
This clearly demonstrates how the code in the static block is executed first before the main method .

Conclusion

In this article, we talked about the static keyword in Java. This is a keyword that basically helps us optimize memory in programs written in Java. We also saw how to create static variables and methods with examples. Finally, we talked about static blocks, which can be used to initialize static variables. Static blocks are executed before the main method. Happy coding!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION