-5

Java 14

public class Ex14 {
    static String strDef = "At the point of definition";

    static {String strBlock = "In a static block";}

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

}

Result

$ javac Ex14.java

Ex14.java:10: error: cannot find symbol
        System.out.println(Ex14.strBlock);
                               ^
  symbol:   variable strBlock
  location: class Ex14
1 error

Could you help me understand why this error happens?

Michael
  • 4,273
  • 3
  • 40
  • 69

1 Answers1

0

Your strBlock variable is a local variables within the static initializer block. Its scope is limited to that block, just like any other local variable. If you want to be able to access it in the main method, you'll need to declare it as a field:

static strBlock; // Static field declaration

static {
    // Static field initialization
    strBlock = "Initialized in a static block";
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194