What is the scope of local variables in Java?

Java 8Object Oriented ProgrammingProgramming

Scope of a variable denotes span of a variable.

The scope of a local variable is within that method i.e. when we create a variable with in a method, it cannot be accessed outside that method.

Example

If you observe the following example here, we have created a variable named num in the main method and, trying to access it in another method (demo).

public class SampleTest {
   String str = "sampleString";
   
   public static void main(String args[]){
      int num = 334;
   }
   public void demo(){
      System.out.println(num);
   }
}

Error

Since we cannot access a local variable (variable of a method) outside it, the compiler generates an error as −

C:\Sample>javac SampleTest.java
SampleTest.java:7: error: cannot find symbol
System.out.println(num);
                   ^
symbol: variable num
location: class SampleTest
1 error
raja
Published on 10-Jan-2018 06:14:17
Advertisements