I came across this Java code:
static { String aux = "value"; try { // some code here } catch (Exception e) { } String UUID_prefix = aux + ":"; }
I am new to Java, please explain what is happening here.
The static keyword is a non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class.
That means this static block will be initialized only once irrespective of how many objects you have created out of this class.
A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
This is a static initialization block. Think of it like a static version of the constructor. Constructors are run when the class is instantiated; static initialization blocks get run when the class gets loaded.
You can use them for something like this (obviously fabricated code):
private static int myInt; static { MyResource myResource = new MyResource(); myInt = myResource.getIntegerValue(); myResource.close(); }
See the "Static Initialization Blocks" section of Oracle's tutorial on initializing fields.
This is the block of code that will get invoked when your class is loaded by classloader
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With