- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
A static initialization block in Java
Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program.
A program that demonstrates a static initialization block in Java is given as follows:
Example
public class Demo { static int[] numArray = new int[10]; static { System.out.println("Running static initialization block."); for (int i = 0; i < numArray.length; i++) { numArray[i] = (int) (100.0 * Math.random()); } } void printArray() { System.out.println("The initialized values are:"); for (int i = 0; i < numArray.length; i++) { System.out.print(numArray[i] + " "); } System.out.println(); } public static void main(String[] args) { Demo obj1 = new Demo(); System.out.println("For obj1:"); obj1.printArray(); Demo obj2 = new Demo(); System.out.println("
For obj2:"); obj2.printArray(); } }
Output
Running static initialization block. For obj1: The initialized values are: 40 75 88 51 44 50 34 79 22 21 For obj2: The initialized values are: 40 75 88 51 44 50 34 79 22 21
- Related Articles
- A non-static initialization block in Java
- Why interfaces don't have static initialization block when it can have static methods alone in java?
- Java static block
- Initialization of local variable in a conditional block in Java
- Initialization of static variables in C
- Static Data Member Initialization in C++
- Why Java wouldn't allow initialization of static final variable in a constructor?
- How to execute a static block without main method in Java?
- What are the restrictions imposed on a static method or a static block of code in java?
- \nHow to throw an exception from a static block in Java? \n
- Can we throw an Unchecked Exception from a static block in java?
- Initialization of global and static variables in C
- What are the differences between a static block and a constructor in Java?
- C++ static member variables and their initialization
- Sequence of execution of, instance method, static block and constructor in java?

Advertisements