Can we declare a static variable within a method in java?

A static filed/variable belongs to the class and it will be loaded into the memory at class load time. We can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available entire the class i.e. the value of the static field will be the same in all objects. We can define a static field using the static keyword

 

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

 

Output

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

 

Static variables in methods

The variables within a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. we cannot use a local variable outside the current method which contradicts the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if  we still try to do so, a compile-time error will be generated

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

 

Compile time error

If we run above code it will throw compile time error

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

 


Subscribe For Daily Updates

Flutter Questions
Android Questions