views:

90

answers:

3

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
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."
@functional: my suggestion is based on tag `java` near the question.
Roman
Ok, got that. I'm just saying that it could make sense to be inside methods too. That's all
Ah, I see. I didn't know you could do that in C. But in Java, you definitely can't.
MatrixFrog
@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
+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
Static variables inside methods are legal in C and C++, perhaps that is his background.
Matt Greer
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
+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