Can we declare Static
Variables inside Main
method? Because I am getting an error message:
Illegal Start of Expression
You cannot, why would you want to do that? You can always declare it on the class level where it belongs.
As static variables are available for the entire class so conceptually it can only be declared after the class whose scope is global where as static block or methods all have their own scope.
In C, you can have statically allocated locally scoped variables. Unfortunately this is not directly supported in Java. But you can achieve the same effect by using nested classes.
For example, the following is allowed but it is bad engineering, because the scope of x is much larger than it needs to be. Also there is a non-obvious dependency between two members (x and getNextValue).
static int x = 42;
public static int getNextValue() {
return ++x;
}
One would really like to do the following, but it is not legal:
public static int getNextValue() {
static int x = 42; // not legal :-(
return ++x;
}
However you could do this instead,
public static class getNext {
static int x = 42;
public static int value() {
return ++x;
}
}
It is better engineering at the expense of some ugliness.
Because the static variables are allocated memory at the class loading time,and the memory is allocated only once.Now if you have a static variable inside a method,then that variable comes under the method's scope,not class's scope,and JVM is unable to allocate memory to it,because a method is called by the help of class's object,and that is at runtime,not at class loading time.
Obviously, no, we can't.
In Java, static
means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects.
This means that static
keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.
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);
}
}