Java Reference
In-Depth Information
}
System.out.println();
// Start a new line
}
public static void main(String[] args) {
TryInitialization example = new TryInitialization();
System.out.println("\nFirst object:");
example.listValues();
example = new TryInitialization();
System.out.println("\nSecond object:");
example.listValues();
}
TyInitialization.java
When you compile and run this, you get identical sets of values for the two objects — as might be ex-
pected because the values array is static:
Running initialization block.
First object:
40 97 88 63 58 48 84 5 32 67
Second object:
40 97 88 63 58 48 84 5 32 67
How It Works
The TryInitialization class has a static member, values , that is an array of 10 integers. The static
initialization block is the code
static {
System.out.println("Running initialization block.");
for(int i = 0 ; i < values.length ; ++i) {
values[i] = (int)(100.0*Math.random());
}
}
This initializes the values array with pseudo-random integer values generated in the for loop. The out-
put statement in the block is there just to record when the initialization block executes. Because this
initialization block is static, it is only ever executed once during program execution, when the class is
loaded.
The listValues() method provides you with a means of outputting the values in the array. The print()
method you are using in the listValues() method works just like println() , but without starting a
new line after displaying the output, so you get all the values on the same line.
Search WWH ::




Custom Search