JavaIntermediate#oop

What is the difference between instance initializer blocks and constructors?

Instance initializer blocks run every time an object is created, right before the constructor body, and are useful for shared initialization logic across multiple constructors. Static blocks run once when the class is loaded.

Example
class Demo {
  int x;
  { x = 10; System.out.println("instance block"); }
  static { System.out.println("static block, runs once"); }
  Demo() { System.out.println("constructor"); }
}

Related Questions

1
JavaBeginner#object#fundamentals

What is the difference between == and equals() when comparing objects that don't override equals()?

Open
2
JavaIntermediate#object#hashmap

What is the purpose of the hashCode() method and its contract with equals()?

Open
3
JavaBeginner#fundamentals

What is the instanceof operator?

Open