
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Static Blocks in Java with Example
A block of code that is associated with the static keyword is called as static block. This block executes when classloader loads the class. Remember, if your code contains any static block, it will be invoked before the main() method.
In this article, we will learn how to create and invoke static blocks in Java along with its use case. But, before that let's understand the static keyword.
What is Static Keyword?
The static keyword in Java is a non-access modifier. This keyword is used with variables, methods, blocks of code and classes. A class, method or variable declared with a static keyword belongs to the class itself rather than to any specific instance of the class.
This means static members can be accessed without creating any objects of the class. You can access them using the class name itself.
How to Create Static Block in Java?
Creating static blocks in Java is quite simple and easy. You just need to put your code inside curly braces and precede it with the static keyword as shown below ?
static { // your code }
How to Invoke Static Block in Java?
There is no specific rule available to invoke static block. When the class is loaded in the memory this block is executed automatically by Java Virtual Machine.
Example
A Java program that demonstrates the static block is given below ?
class Demo{ static int val_1; int val_2; static{ val_1 = 67; System.out.println("The static block has been called."); } } public class Main{ public static void main(String args[]){ System.out.println(Demo.val_1); } }
On executing, this code will display the following output ?
The static block has been called. 67
Key Points to Remember
Please note down the below listed points as they are important from interview perspective ?
- A static block is also known as a static initialization block as it is used for static initialization of classes and variables.
- They are executed before the main method and even before any objects are instantiated.
- Static blocks can't access instance variables or methods directly because they are part of the class, not part of any object. However, they can access static variables and methods.
- These blocks are executed only once when the class is loaded. Even if you create multiple objects of the class, the static block will be executed only once due to the fact that a static block belongs to the class not object.
- You can run your Java code written inside a static block without creating the main() method on JDK version 1.6 or previous.