Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Static {} mean in the Java Syntax?

Tags:

java

static

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.

like image 921
sufyan siddique Avatar asked Nov 10 '11 16:11

sufyan siddique


People also ask

What is static {} in Java?

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.

What does static {} mean?

That means this static block will be initialized only once irrespective of how many objects you have created out of this class.

What is static class in Java?

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.


2 Answers

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.

like image 176
Jon Newmuis Avatar answered Sep 27 '22 21:09

Jon Newmuis


This is the block of code that will get invoked when your class is loaded by classloader

like image 42
jmj Avatar answered Sep 27 '22 22:09

jmj