How to declare a static variable inside the Main method?

Can we declare Static Variables inside the Main method? Because I get the error message:

 Illegal Start of Expression 
+7
java static-variables
source share
6 answers

Obviously not, we cannot.

In Java, static means that it is a class variable / method, it belongs to the whole class, but not to one of its specific objects.

This means that the static can only be used in the "scope of the class", i.e. it does not make sense inside the methods.

+26
source share

You can use static variables inside your main method (or any other method), but you need to declare them in the class:

This is completely normal:

 public Class YourClass { static int someNumber = 5; public static void main(String[] args) { System.out.println(someNumber); } } 

This is also good, 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); } } 
+6
source share

Since static variables are allocated memory during class loading, and memory is allocated only once. Now, if you have a static variable inside the method, then this variable falls under the scope of the method, not the scope of the class and the JVM cannot allocate memory for it, because the method is called using the class object, and this is at run time, not during class loading.

+4
source share

Since static variables are available for the entire class, so conceptually it can be declared only after a class whose global scope is where, as a static block or methods, everyone has their own scope.

+3
source share

You cannot, why do you do this? You can always declare it at the class level where it belongs.

+1
source share

In C, you can have statically allocated locally restricted variables. Unfortunately, this is not directly supported in Java. But you can achieve the same effect using nested classes.

For example, the following is allowed, but this is bad engineering, since the scope of x is much larger than it should be. There is also an unobvious dependency between the two members (x and getNextValue).

 static int x = 42; public static int getNextValue() { return ++x; } 

I would like to do the following, but this is not legal:

 public static int getNextValue() { static int x = 42; // not legal :-( return ++x; } 

However, you could do it,

 public static class getNext { static int x = 42; public static int value() { return ++x; } } 

This is better engineering due to some ugliness.

+1
source share

All Articles