Use of a
Static Block in a Class
Can anyone tell me that what is the use of
a static block in a class?
public class myclass{ static{ //some statements here } //some variables declared
here
This question was asked me in an interview.
so if anyone knows the answer please give me the answer.
Static loop is executed, when the class is loaded.
Got confused !!! Leave that and try this simple
example
Hopes you got cleared Jim
If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded. The following example shows a class that has a static method,some static variables,ana a static initialization block. class UseStatic {
static {
} As soon as the UseStatic class is loaded, all of the static statements are run.First, a is set to 3, then the static block executes(printing a message),and finally, b is initialized to a* 4 or 12.Then main( ) is called,which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b,as well as to the local varible x. Here is the output of the program: Static block initialized.
Sowbakia Nagaraj
Do you have a Java Problem?
Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|