Java Static Initializer Block datatype

static int B,H; 
static boolean flag = true;
static {
    Scanner scan = new Scanner (System.in);
     B = scan.nextInt();
     H = scan.nextInt();
    scan.close();

And

static int B,H; 
static boolean flag = true;
static {
    Scanner scan = new Scanner (System.in);
   int B = scan.nextInt();
   int H = scan.nextInt();
    scan.close();

Why has these two functions different output for B and H? What's the difference with and without defining an int before B and H?

Jon Skeet
people
quotationmark

Well in your second code, B and H are local variables within the block - you're not assigning to the field at all. That's exactly the same as if you were writing a method...

Forget static initialization for the minute - imagine you had this code:

public class Foo {
    private int value;

    public void calculateValue() {
        int value = new Random.nextInt(5);
    }

    public int getValue() {
        return value;
    }
}

Now if you run:

Foo foo = new Foo();
foo.computeValue();
System.out.println(foo.getValue());

... it will print 0, because the computeValue() method just declares a new local variable.

The exact same thing happens with a static initializer block. In this block:

static {
    Scanner scan = new Scanner (System.in);
    int B = scan.nextInt();
    int H = scan.nextInt();
    scan.close();
}

... you're declaring new local variables B and H - so they don't affect the static fields B and H at all.

people

See more on this question at Stackoverflow