0

Why does this code print 11 and not 10. Clearly , i++ in the static initialization block is executed.
But , why i-- in the non-static block is not executed.
What's happening here ?

class ClassOne
{
    static int i = 10;

    {
        i--;
    }

}

public class Main extends ClassOne
{
    static
    {
        i++;
    }

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

    }
}

0

2 Answers 2

8

Non-static initialization blocks will be called on instance creation.

You never create a new instance, so the block is not executed.

Sign up to request clarification or add additional context in comments.

2 Comments

Anyway, please don't use instance initialization blocks. Many don't know they even exist, and it is very confusing to find them in code. Just stick to regular constructors or field initialization.
never say never. There are legitimate (but rare) uses for them.
1

This is specifically related to instance initializer blocks and static initializer block. In the above example, the block with i-- is instance initializer block and will be executed each time a new instance of either Main or ClassOne is created.

Static initializer blocks are executed at the time of class loading. So when Main class is being loaded into memory it's parent class is loaded first, and then the variable is getting loaded into memory as well. Thereafter static block in Main gets executed, resulting in 11 to be printed on the console.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.