0

Why can't we declare static variables inside a static block because static attributes ,when are allotted memory during class loading time and also ,with the class loading only the static block gets executed then why is there a restriction that we can't do this.

Also,during class loading when the main method gets loaded then why cant we even declare our static variables inside the main method also.

1
  • Java needs to know what variables a class has at compile-time, not run-time. Commented Nov 17, 2014 at 23:35

2 Answers 2

3

Any variable declared within ANY block will be block-local - they can not be static for that simple reason.

Sign up to request clarification or add additional context in comments.

Comments

1

You can declare a variable static inside a static block because static variables and methods are class instead of instance variable and methods.

This means that you wont be able to see a static field inside a method because it will be inside an inner scope and won't be a class variable at all...

For example:

static int a;
static int b;
public static int sum(){
    return a+b;
}

This is completely legal because when calling this method, then it will perform operations with variables that have already been loaded. if you do it the other way around, who will this variable belong to?

Another reason is that all variables declared inside a static block will be static too by default.

3 Comments

Correction - any variable declared within a block will be block-local
yes sir ,I understood but why is the following code giving error public class qu3 { static { static int a=90; } }
Because you cant have a CLASS variable inside a local scope

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.