Help: Adding static variable confusion. Inside or outside main()?
Hey guys,
I'm a starter so I had a doubt related to placement of a static variable. On line 5, for "static int d=5" compiler issues "illegal start of expression". But when I place it outside main() as Instance variable it works and prints "Hello 5". Why this thing?
public class AbstractClass {
public static void main(String args[]) {
String s = "Hello";
static int d=5;
System.out.println(s);
System.out.println(d);
}
}
10 Months Ago
Last Updated
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Thanks a lot anand. Appreciate the clarity.
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
actually, we can't declare a local variable as being static :) (potato, potatoe)
you have three options: either you have it as a local (non-static) variable that is defined within the main method, or you have it on class scope, either static or non-static.
stultuske
Industrious Poster
4,370 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 23
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 10 Months Ago by
stultuske
and
anand01