Can we declare Static Variables inside Main method? Because I am getting an error message as "Illegal Start of Expression". Please reply.
+2
A:
Obviously, no, we can't.
In Java, static
means that it's a variable/method of class, it belongs to the whool class but not to one of its certain objects.
It means that static
keyword can be used only int a 'class scope' i.e. it doesn't have any sence inside methods.
Roman
2010-07-31 15:40:49
It could have the meaning it has in C functions ...From wikipedia: "Static local variables: variables declared as static inside inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again."
2010-07-31 15:44:14
@functional: my suggestion is based on tag `java` near the question.
Roman
2010-07-31 15:45:01
Ok, got that. I'm just saying that it could make sense to be inside methods too. That's all
2010-07-31 15:45:49
Ah, I see. I didn't know you could do that in C. But in Java, you definitely can't.
MatrixFrog
2010-07-31 15:47:06
@functional - it would only make sense in Java, if you also considered it made sense in C. Personally, I think that that was a flaw in the syntax of C language. It is a kludgy way of doing what Java and C++ do using visibility modifiers.
Stephen C
2010-07-31 16:41:14
+1
A:
You cannot, why would you want to do that? You can always declare it on the class level where it belongs.
dark_charlie
2010-07-31 15:41:34
Static variables inside methods are legal in C and C++, perhaps that is his background.
Matt Greer
2010-07-31 15:43:19
I know but Java isn't C++ :) Static variables in C/C++ have the advantage of not being deleted after the function ends so you can pass them anywhere. With Java's garbage collector you can just pass the variable around without any worries that's why I asked what his point was. Thanks for your comment.
dark_charlie
2010-07-31 15:52:21
+1
A:
You can use static variables inside your main
method (or any other method), but you need to declare them in the class:
This is totally fine:
public Class YourClass {
static int someNumber = 5;
public static void main(String[] args) {
System.out.println(someNumber);
}
}
This is fine too, but in this case, someNumber
is a local variable, not a static one.
public Class YourClass {
public static void main(String[] args) {
int someNumber = 5;
System.out.println(someNumber);
}
}
MatrixFrog
2010-07-31 15:44:57