You are here

Local Variables

Get the entire book!
Java for the Beginning Programmer

Local variables are declared inside of a method. These local variables can only be accessed from within the method. Unless the local variable is declared static, the local variable will lose its value when the method returns. When programming Java, most of the time you will create nonstatic local variables, like I am about to show you. Listing 6.4 shows local variables.

Listing 6.4: Using an Instance Variable (MyClassLocal.java)

public class MyClassLocal
{
  public static void myMethod()
  {
    int x = 0;
    System.out.println( "Value of x:" + x );
    x++;
  }

  public static void main(String args[])
  {
    myMethod();
    myMethod();
    myMethod();
  }
}

This program would display the number 0 three times. The variable x is local. Each time the method is called x is reset to zero. As you can see this is very different from the static local variable used earlier in this section.

Technology: 

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer