Naman
Naman

Reputation: 2373

Order of excecution, static blocks, fields

I know that static blocks are run before anything. But here, what happens when B.test() is called? Order of execution and setting of values? Later, when b1 is set to null, still how b1.i evaluates to 20?

class  B
{    
     static int i;
     static {
         i = 20;
         System.out.println("SIB");
     }
     static int test() {  
         int i = 24;
         System.out.println(i);
         return i; 
     }
}

public class Manager {
    public static void main(String[] arg) {
         B.test();
         B b1 = null;
         System.out.println(b1.i);  
    }
}

The output is:

SIB
24
20

Upvotes: 0

Views: 1379

Answers (5)

Michael
Michael

Reputation: 2634

What you did:             What really happened:
B.test()                  - static block of class B is run, static i set to 20, SIB is displayed
                          - test method is called, local property i set to 24, 24 is displayed
b1 = null                 - set reference for b1 to null. Note that this doesn't change the value of class B's static properties
System.out.println(b1.i)  - b1 is still Class B. It doesn't matter what its current reference is. Static i for class B is still 20, 20 is displayed

Upvotes: 1

trutheality
trutheality

Reputation: 23465

What happens is:

  • B.test() is called for the first time, before actually running it:
  • Class B is loaded,
  • Static initializer executed (B.i = 20 now)
  • Contents of B.test() method are executed
  • (creates a method-local int i = 24 (which shadows the static variable B.i) and prints it)
  • b1.i is interpreted as B.i (which is still 20) and it's printed.

Upvotes: 1

talnicolas
talnicolas

Reputation: 14053

The value of i here

static int i;
static {
    i = 20;
    System.out.println("SIB");
}

is set to 20 and never modified, so when you access b1.i, it's still 20.

In your test() method you are using another i variable that is not related to the static one.

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533510

But here, what happens when B.test() is called? Order of execution and setting of values?

There is no change.

Later, when b1 is set to null, still how b1.i evaluates to 20?

Because b1 isn't used, the field is static so you are actually using B.i

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198093

i is static, so b1.i is equivalent to B.i. Just setting b1 to null doesn't change any static variables.

When B.test() is called, first the B class is loaded, and the static blocks are run. Next, B.test() creates a new method-local variable called i, which is completely different from B.i. This new, local i is printed and returned. No changes are made to B.i, and certainly not just because you created a new B object reference that was null -- that would never have any effect on anything.

Upvotes: 3

Related Questions