0

I looked this issue and I am confused. He uses a static block. Why would he write a single line?

What is the difference between these two?

private static Pattern email_pattern = Pattern.compile(EMAIL_PATTERN);

And

private static Pattern email_pattern;

static {
    email_pattern = Pattern.compile(EMAIL_PATTERN);
}
Community
  • 1
  • 1
cguzel
  • 1,673
  • 2
  • 19
  • 34

2 Answers2

6

There is no difference in the behavior of your example. A static block can be used to do more logic than just assigning a var. No need to use the block in your example.

Henning Luther
  • 2,067
  • 15
  • 22
2

Both code fragments do the same thing, but most people will find the compact version easier to read.

There are things you cannot do in the single line assignment version, such as handling exceptions. In those cases you have to use an initializer block.

A third way would be to move the initializer code into a (static) method.

private static final Pattern pattern = doSomethingReallyComplexHere();
Thilo
  • 257,207
  • 101
  • 511
  • 656