Static Block in Java10 Sept 2024 | 4 min read When a block is decorated or associated with the word static, it is called a static block. Static Block is known as the static clause. A static block can be used for the static initialization of a class. The code that is written inside the static block run once, when the class is getting loaded into the memory. Invoking a Static BlockNow the question arises, how to invoke the static block? To invoke the static block, there is no specific way since the static block gets executed automatically, whenever in the memory the class is loaded. Observe the following illustration. FileName: StaticBlock.java Output: Inside the static block. Inside the constructor of the class. Inside the print method. Inside the constructor of the class. Explanation: By looking at the output, it is evident that the print statement of the static block gets executed first. Then, the print statement of the constructor of the class, after that print statement of the print() method, and after that, again, the constructor's print statement. Also, note that inside the main() method, we have invoked the constructor and the print() method of the class explicitly. However, no statement is written for invoking the static block. It shows that the static block is executed automatically, and that too before invoking the constructor of the class. Example - 1Let's see an example to get a better understanding of static block. FileName: StaticBlock1.java Output: Inside the static block. - 1 Inside the static block. - 2 Inside the static block. - 3 Inside the constructor of the class. Inside the method foo. Inside the constructor of the class. Explanation: It is evident by looking at the output that static blocks get executed first, and that too in the order the static blocks are written in the above code. It is also evident that more than one static block can exist in the code. Example - 2Let's see another example of a static block. FileName: StaticBlock2.java Output: /StaticBlock2.java:21: error: non-static method foo() cannot be referenced from a static context foo(); ^ /StaticBlock2.java:22: error: non-static variable st cannot be referenced from a static context System.out.println(st); ^ 2 errors Explanation: Static block can only access the static variables or static methods and will give an error if one tries to access any non-static variable/method. In order to run the program without any error, add the keyword static to the variable st, and method for as shown in the following program. FileName: StaticBlock3.java Output: Inside the method foo. 9 Inside the static block. - 1 Inside the constructor of the class. Static Block and Main MethodWe know that static blocks are loaded automatically (see the above examples) when the class is loaded. In other words, there is no need for a method to invoke the static blocks. Then the question arises is there any need of the main() method? The answer depends on the GDK version the user is using. If the user is using GDK version 1.06 or previous ones, the static blocks get executed without mentioning the main() method in the code. However, the program gives an error if the user is using the GDK version, which is higher than 1.06. Observe the following two programs. FileName: StaticBlock4.java Output: The print statement gets executed without main method. FileName: StaticBlock5.java Output: Error: Main method not found in class StaticBlock5, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application Next TopicAccessor and Mutator in Java |
An integer count is given to us associated with a string 'str' made up of lowercase English letters. The objective behind this particular problem is to find "equal count substrings." When every distinct letter appears within a substring exactly count times, the substring is said...
6 min read
The Java IO package offers several methods to append a string to an existing file in Java. Appending a string to a file means adding new data to the end of an existing file without overwriting or deleting the ious data. Approach: Appending string to a file. Appending...
4 min read
JDK 8 introduces the IntPredicate interface. The package java.util.function contains this interface. It works with an integer value and, given a condition, returns a predicate value. It can also be utilized in lambda expression since it is a functional interface. The Methods are given by: 1. test():...
2 min read
Fundamental ideas called serialization and deserialization are used to convert Java objects into a format that may be quickly transmitted, stored, or recreated. Serialization Serialization is the process of converting an object into a byte stream so that it may be sent over a network, saved in a...
4 min read
? Here, we are going to examine using loops to develop more efficient code. It is commonly accepted that implementing loops to solve a problem statement is an imprudent strategy. Despite this, there can be an abundance of scope for trial and error here. To put...
6 min read
In Java, final is a keyword that guarantees only the immutability of primitive types. And also guarantees that a variable is assigned only once. If an object is mutable, we can change the content of it even it is defined as final. In this section, we...
2 min read
Suppose we have a positive integer p, and we want the operations to be carried out on an array of integers nums, which contains the binary digits 1 through 2^p - 1. After performing any number of particular operations on the array elements, the objective is...
5 min read
? The dictionary meaning of advance is a forward movement or a development or improvement and the meaning of improve means thing that makes something better. All in all, we have to improve our basic knowledge to master in that particular field. Java is divided into two parts...
15 min read
Java 9 introduced several new features and enhancements to further improve the language's capabilities. Among these additions are the orTimeout() and completeOnTimeout() methods that are designed to enhance the handling of timeouts in CompletableFuture instances. These methods provide developers with more control and flexibility when dealing...
4 min read
An input array is given to us. That input array is the preorder traversal of a Binary Search Tree (BST). The task is to detect and print the leaf nodes of the Binary Search Tree. A leaf node is a node of a tree that has...
9 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India