- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 non-static initialization block in Java
Instance variables are initialized using initialization blocks. These blocks are executed when the class object is created and before the invocation of the class constructor. Also, it is not necessary to have initialization blocks in the class.
A program that demonstrates a non-static initialization block in Java is given as follows:
Example
public class Demo { static int[] numArray = new int[10]; { System.out.println("
Running non-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 non-static initialization block. For obj1: The initialized values are: 96 19 14 59 12 78 96 38 55 85 Running non-static initialization block. For obj2: The initialized values are: 38 59 76 70 97 55 61 81 19 77
- Related Articles
- A 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
- Non static blocks in Java.
- Initialization of static variables in C
- Static Data Member Initialization in C++
- Static and non static blank final variables in Java
- How to execute a static block without main method in Java?
- Why Java wouldn't allow initialization of static final variable in a constructor?
- What are the restrictions imposed on a static method or a static block of code in java?
- Can we make static reference to non-static fields in java?
- Can we throw an Unchecked Exception from a static block in java?
- \nHow to throw an exception from a static block in Java? \n
- What are the differences between a static block and a constructor in Java?

Advertisements