Why we can't initialize static final variable in try/catch block in java?


In Java you can declare three types of variables namely, instance variables, static variables and, local variables.

  • Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.

Static methods in try-block

In the same way, static variables belong to the class and can be accessed anywhere within the class, which contradicts with the definition of the local variable. Therefore, declaring a static variable inside a method, block or, constructor is not allowed. Still, if you try to declare a static variable within a block a compile time error will be generated.

Example

In the following Java example we are trying to declare a String variable path in the try block.

import java.io.File;
import java.io.FileInputStream;
public class Example {
   public static void main(String args[]){
      System.out.println("Hello");
      try{
         static String path = "my_file";
         File file =new File(path);
         FileInputStream fis = new FileInputStream(file);
      }catch(Exception e){
         System.out.println("Given file path is not found");
      }
   }
}

Compile time error

on compiling, the above program generates the following error.

Example.java:7: error: illegal start of expression
   static String path = "my_file";
   ^
1 error

If you compile the same program in eclipse it generates the following message.

Updated on: 07-Aug-2019

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements