Java Static Initializer Block

  • + 5 comments

    No You can't do that because we need to reference the variables in main method,as main method is non-editable.so the only option you have that while compiling, when JVM loads (.class) file in the memory intialize all those variables at the same time that can be done when you declare variables as static.

    static boolean flag=true;
    static Scanner in=new Scanner(System.in);
    static int B=in.nextInt();
    static int H=in.nextInt();
    static
    {
       
        if(B>0 && H>0)
            flag=true;
        else
        {
            flag=false;
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        }
            
    }
    

    Note: variables inside the static block is not static.