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.


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(){


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
symbol: variable num
location: class SampleTest
1 error
Updated on 30-Jul-2019 22:30:20