-2
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?

  • Where is your output statement? – Neeraj Jain May 22 '17 at 06:15
  • 1
    In the latter `static` initialization block, your two local variable declarations are masking the fields. – Logan May 22 '17 at 06:17
  • I don't think this should be marked as duplicate since the OP is asking for explanation for misbehaviour in their code. It's not the case they come across some term and ask for explanation, but ask for explanation for not working code. – gonczor May 22 '17 at 06:21

3 Answers3

4

In the second case you redefine B and H as new, local variables.

gonczor
  • 3,994
  • 1
  • 21
  • 46
4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

In the second case, you're introducing two local variables. They override the static fields, and are only available in the static initializer.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24