DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Raghavan alias Saravanan Muthu
Raghavan alias Saravanan Muthu

Posted on

Interesting Java Puzzle - Instance Initializers

Instance Initializer Test in Java

Problem

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

Code

public class InstanceInitializerTest 
{

    public static void main(String[] args) 
    {
        {
            System.out.println("Feathers");
        }
    }

    {
        System.out.println("Snowy");
    }
}

Options

The list of possible outputs are :

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

Solution

The right answer is

(3) Feathers

Explanation

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)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.