1

What makes this line of code execute?

The code gives an output of 11, but I was expecting it to be 1

package methodcalling;

public class MethodCalling {

public static int cakes = 1;
public final static int UNIT = 10;
static{cakes += UNIT;}      // what makes this line of code execute

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

1 Answers1

2

A static block is executed as the class gets loaded (i.e. directly after static variables are initialized). Therefore cakes += UNIT; is executed before main.

Turing85
  • 18,217
  • 7
  • 33
  • 58