Tutorials

Java Variables


Java Local Variable


Any variable declared inside method in java is known as local variable.

 

Important points related to local variable

  • Scope of the local variable is restricted to the method/constructor in which it is created. They are not accessible outside the method.
  • Local variables are not assigned any default value. If you fail to assign it a value then while using it compiler will give error. Say for example, int x; Then if you write System.out.println(x); you will get compiler error at x in print statement - "local variable x may not have been initialized".
  • static keyword cannot be used with any local variable. If you write static int x = 10; then compile-time error will occur.

 

Example of Local variable


package variables;

public class LocalVariable {

            public static void main(String[] args) {

                        int a = 10;    //var a local to main method
                        int res = a+1;  //var res local to main method

                        System.out.println(b);

            }

}

OUTPUT:

11

 

Example 2: Trying to access local variable outside the method


package variables;



public class LocalVariable {

            public static void main(String[] args) {

                        int a = 10;    //var a local to main method
                        int res = a+1;  //var res local to main method

                        System.out.println(b);

            }

           
            int b =20;
            int add = a + b;   //compilation error

}

OUTPUT:

Compilation error

 

Local variable cannot be accessed or used outside the method in which it is declared. This is why we were not able to use value of variable 'a' outside main() method and got compile time error.



Please Share this page
Views : 115
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!