How do I declare a static variable inside the Main method?

后端 未结 6 1924
予麋鹿
予麋鹿 2020-12-03 22:42

Can we declare Static Variables inside Main method? Because I am getting an error message:

Illegal Start of Expression
相关标签:
6条回答
  • 2020-12-03 23:23

    You cannot, why would you want to do that? You can always declare it on the class level where it belongs.

    0 讨论(0)
  • 2020-12-03 23:25

    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.

    0 讨论(0)
  • 2020-12-03 23:26

    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.

    0 讨论(0)
  • 2020-12-03 23:41

    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.

    0 讨论(0)
  • 2020-12-03 23:43

    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.

    0 讨论(0)
  • 2020-12-03 23:43

    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题