Java examples for Language Basics:Variable
Scope class demonstrates field and local variable scopes.
public class Main { // field that is accessible to all methods of this class static int x = 1; public static void main(String[] args) { int x = 5; // method's local variable x shadows field x System.out.printf("local x in main is %d%n", x); useLocalVariable(); // useLocalVariable has local x useField(); // useField uses class Scope's field x System.out.printf("%nlocal x in main is %d%n", x); }//w w w . ja v a2 s .c om // create and initialize local variable x during each call public static void useLocalVariable() { int x = 25; // initialized each time useLocalVariable is called System.out.printf("%nlocal x on entering method useLocalVariable is %d%n", x); ++x; // modifies this method's local variable x System.out.printf("local x before exiting method useLocalVariable is %d%n", x); } // modify class Scope's field x during each call public static void useField() { System.out.printf("%nfield x on entering method useField is %d%n", x); x *= 10; // modifies class Scope's field x System.out.printf("field x before exiting method useField is %d%n", x); } }