Kevik
Kevik

Reputation: 9351

what are the differences in these two ways to initialize a static variable?

What are the differences between the following two examples, if used in an Android applications?

Example-1

public class ExampleClassOne {  
    public static int x = 9;
}

Example-2

public class ExampleClassTwo{   
  public static int x;
  static{   
      x = 9;    
  } 
}

Upvotes: 1

Views: 84

Answers (4)

Stephen C
Stephen C

Reputation: 718718

For this example there is no difference. The two forms do exactly the same thing. (Indeed, I suspect that the bytecodes produced will be virtually identical.)

There are cases where there is a difference. Or to be more precise, there is a difference in what you can express. A couple that spring to mind are:

  • A static initializer block can deal with exceptions (especially checked ones) but a initializer expression can't.

  • A static initializer block can initialize the static to the result of an arbitrarily complicated sequence of statements, but an initializer expression is limited to what you can compute in a single expression.


Having said that, I would recommend that you use the simpler initializer expression form wherever possible. Without doubt, it is more readable.

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49362

As per the Oracle tutorial:

public static int x = 9;

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate.

Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.

But in your case , with your code , it makes no difference.

Upvotes: 0

Mena
Mena

Reputation: 48404

Usually the static block is used for more complex initialization, for instance if you have a List and want to populate it.

Edit (rolled back ;) ) in your case initialization is equivalent though.

Upvotes: 0

AAnkit
AAnkit

Reputation: 27549

they both are same and would be called and initialized on class creation/initiation. there are no such differences.

Upvotes: 0

Related Questions