Can we declare Static
Variables inside Main
method? Because I am getting an error message:
Illegal Start of Expression
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With