public static void main(String args)
Chap3Ex7 ch = new Chap3Ex7();
im getting something related to :
Chap3Ex7.java:6: illegal start of expression
static int i=15;
my question is can't we use static variables in static block ,whenever i remove static keyword it is working fine,
i declared same variable i in both Initialisation blocks , i think that is not the problem because of both are having different blocks
Sure you can initialize a static variable in a static initializer. You just can't declare a static variable in a static initializer. The latter is what you tried to do. Replace your code by some code which declares a static variable, then uses a static initializer to initialize it.
jami siva wrote:is any more explanation for why we can'nt declare static variables in static block
You are allowed to code a local variable in a block, but you can't declare a member in any block. As far as "why" -- that's just the rule. The Java Language Specification says "A block is a sequence of statements, local class declarations and local variable declaration statements within braces." So, members, such as static fields, can't be declared in a block.
This rule exists because any variable declared within curly braces has scope till those braces. Now when you declare a variable static, you are making it a class variable, which has wider scope than local or instance variable. If static variable was allowed, it could have become conflict of interest. So the rule.