1

In my Java class, I have statements in {} without any names/references associated with it and it appear to get executed before constructor is run. What is the purpose of it? Is it possible to call it like calling a method by associating a variable/reference to it? If not, can I change the order in which it is triggered?

package com.core.java;

public class App {

    public static void main(String[] args) {
        new App();
    }

    static { System.out.print("static block, "); }      
    App() { System.out.print("constructor, "); }    
    { System.out.print("what_is_this? "); }

}

I have seen similar construct in Ruby where it can be associated with a reference and be called at will. For instance

v = -> { puts "A Code Block" }
v.call #=> prints -> A Code Block
Bala
  • 11,068
  • 19
  • 67
  • 120
  • possible duplicate of [Use of Initializers vs Constructors in Java](http://stackoverflow.com/questions/804589/use-of-initializers-vs-constructors-in-java) – Joe Apr 26 '14 at 10:06
  • The duplicate flag makes a bit more sense if you know that `static { System.out.print("static block, "); }` is a *static initialiser*, and that the `{ System.out.print("what_is_this? "); }` is an *instance initialiser*. – JonK Apr 26 '14 at 10:10

1 Answers1

1

If you want to have a quick read on these constructs and what they may be used for, see

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

The comparison to Ruby is somewhat flawed, as this is only a syntactic similarity between Java and Ruby - in Ruby, the "{}" means something completely different to what Java uses this syntax for. The "-> {}" in Ruby is an expression returning a lambda, which is a callable object.

What is an initialization block?

Also helps explaining the case with some nice code examples.

Community
  • 1
  • 1
Sebastian Schuth
  • 9,999
  • 1
  • 20
  • 16