Developer community
0 votes
971 views
asked by Guru (24.6k points) 29 51 78 | 971 views

1 Answer

0 votes
Executed for each object that is created.
Can initialize instance variables in a class.
public class MainClass {
  static int[] values = new int[5];

  {
    System.out.println("Running initialization block.");
    for (int i = 0; i < values.length; i++) {
      values[i] = (int) (100.0 * Math.random());
    }
  }

  void listValues() {

    for (int value : values) {
      System.out.println(value);
    }

  }

  public static void main(String[] args) {
    MainClass example = new MainClass();
    System.out.println("\nFirst object:");
    example.listValues();

    example = new MainClass();
    System.out.println("\nSecond object:");
    example.listValues();
  }
}
Running initialization block.

First object:
35
17
1
42
7
Running initialization block.

Second object:
45
78
49
56
38
answered by Sr Member (4.8k points) 10 23 31

Related questions

0 votes
2 answers
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 23 31 | 36 views
0 votes
1 answer
asked by sara Guru (24.6k points) 29 51 78 | 120 views
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 23 31 | 27 views
0 votes
1 answer
asked by john Guru (27.1k points) 32 50 97 | 55 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users