DEV Community

Raghavan alias Saravanan Muthu
Raghavan alias Saravanan Muthu

Posted on

Interesting Java Puzzle - Instance Initializers

Instance Initializer Test in Java


Can you guess what would be the output of the below Java code?


public class InstanceInitializerTest 

    public static void main(String[] args) 



The list of possible outputs are :

1. Snowy
2. Snowy
3. Feathers
4. Feathers


The right answer is

(3) Feathers


The instance initializers are the code blocks defined between a pair of curly braces - { and }. They dont really matter even if they are present inside a method, and they are actually counted.

In the above program, when we run the program, the main() method gets executed and inside which we have an instance initializer, and it gets executed. As that was the only one executable statement inside the main() method, the program execution finished there.

You may wonder why the other instance initializer - which prints Snowy was not executed. As you see, the 2nd instance initializer was not bound to a method, instead it was bound to the class. As we have not initiated the class, the instance initializer at the class level was not invoked.

Work for Brain

Try instantiating the class (inside the main() method - of course) and see the change in the output.

You would get the output as either (2) Snowy , Feathers OR the (4) Feathers, Snowy depending upon where you instantiate the class - before or after the instance initializer inside the main() method.

Remember, the order of the initializers matter a lot :)

Top comments (0)