Daksh
Daksh

Reputation: 31

Static and Non-Static initialization blocks in Java

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);

    }
}

Upvotes: 0

Views: 686

Answers (2)

Ritika Goel
Ritika Goel

Reputation: 305

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.

Upvotes: 1

k5_
k5_

Reputation: 5568

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

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

Upvotes: 8

Related Questions