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

↘锁芯ラ 提交于 2019-11-27 15:39:08
Roman

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);
  }
}

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.

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!