English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Can we declare static variables in Java methods?

Static files/Variables belong to this class, and they will be loaded into memory along with the class. You can call them without creating an object (use the class name as a reference). There is only one copy of a static field available throughout the class, that is, the value of the static field is the same for all objects. You can define a static field using the static keyword.

Example

public class Sample{
   static int num = 50;
   public void demo(){
      System.out.println("Value of num in the demo method "+ Sample.num);
   }
   public static void main(String args[]){
      System.out.println("Value of num in the main method "+ Sample.num);
      new Sample().demo();
   }
}

Output result

Value of num in the main method 50
Value of num in the demo method 50

Static variables in the method

The variables in the method are local variables, whose scope is within the method and will be destroyed after the method is executed. That is, you cannot use variables with the same name as the class/The definition of the static variable conflicts with a local variable. Therefore, it is meaningless to declare a static variable inside a method, and if you still try to do so, a compilation error will be generated.

Example

In the following Java program, we try to declare a static variable inside a method.

import java.io.IOException;
import java.util.Scanner;
public class Sample {
   static int num;
   public void sampleMethod(Scanner sc){
      static int num = 50;
   }
   public static void main(String args[]) throws IOException {
      static int num = 50;
   }
}

Compilation errors

If you try to execute the above program, the following errors will occur-

Sample.java:6: error: illegal start of expression
   static int num = 50;
  ^
Sample.java:9: error: illegal start of expression
   static int num = 50;
^
2 errors