What are the modifiers allowed to use along with local variables in Java?

Java 8Object Oriented ProgrammingProgramming

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.
  • Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.

Modifiers allowed with local variables

Since the scope of the local variables belong to the method/block/constructor/ these are not accessed from outside, therefore, having access specifiers like public, private, protected (which allows access outside of the current context) makes no sense.

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 is not allowed too.

The abstract keyword is not allowed with variables in Java. In short, only final is permitted with local variables in Java. If you try to use any other modifiers a compile time error is generated.

Example

public class Sample{
   int num = 50;
   public void demo(){
      int var1 = 20;
      public int var2 = 30;
      final int var3 = 40;
      private int var4 = 260;
      static int var5 = 54;
      protected int var6 = 56;
   }
   public static void main(String args[]){
      System.out.println("Contents of the main method" +new Sample().num);
   }
}

Output

Sample.java:5: error: illegal start of expression
   public int var2 = 30;
   ^
Sample.java:7: error: illegal start of expression
   private int var4 = 260;
   ^
Sample.java:8: error: illegal start of expression
   static int var5 = 54;
   ^
Sample.java:9: error: illegal start of expression
   protected int var6 = 56;
   ^
4 errors

If you use any other modifier before local variable other than final (and default of course), it displays the following message.

raja
Published on 06-Aug-2019 11:35:09
Advertisements