Initialising variables in a constructor or in the class body

Hi guys,

This has been bothering me recently as I create more and more classes for my game. Is there a real world difference between these 2 fictional classes:

class PlaceHolder {

  int x;

  public PlaceHolder() {
    this.x = 5;
  }
}
class PlaceHolder {

  int x = 5;

  public PlaceHolder() {
    //  nothing doing here
  }
}

As far as I can tell they do the same thing. Am I right in this observation or is there a reason to do one over the other?

I notice in my code that I vary between the 2 styles and sometimes in the same class!

AFAIK, Compiler will make the first class def. from the second.

I believe you are correct, Stranger.

Also, the third option: instance initializers!


class Foo {

    int x;
    
    {
        x = 5;
    }

}

The only really useful thing about them is that they run before any constructors, so they can be a good place for doing things common to multiple constructors.
(Although calling this() is seen more frequently)

EDIT: also useful if you need to initialize things in an anonymous class, which can’t have constructors.