public class Scope { public static double x = 3.14; public static void main(String[] args) { // the variable in scope will be the class member variable System.out.print("On line 7 x = "); System.out.println(x); int x = 7; // the variable in scope will be the local variable System.out.print("On line 12 x = "); System.out.println(x); SillyFunction1(); SillyFunction2(); SillyFunction3(99); System.out.print("On line 19 x = "); System.out.println(x); for(int i = 0; i < 10; ++i) { // other languages allow this but java does not. //boolean x = false; System.out.print("On line 19 x = "); System.out.println(x); } System.out.print("On line 19 x = "); System.out.println(x); } public static void SillyFunction1() { // the variable in scope will be the parameter String x = "Hello"; System.out.print("In SillyFunction1 x = "); System.out.println(x); } public static void SillyFunction2() { // the variable in scope will be the class member variable System.out.print("In SillyFunction2 x = "); System.out.println(x); } public static void SillyFunction3(int x){ // the vairable in scope will be the parameter System.out.print("In SillyFunction3 x = "); System.out.println(x); } }
public class Lifetime { public static String a = "has liftime of the program"; public static void main(String[] args){ String b = "Has lifetime of main"; int h = 0; // i has lifetime for the loop, scope as well. for(int i = 0; i < 5; ++i) { // j has lifetime for a single iteration of the loop. int j = 0; System.out.printf("h = %d, i = %d; j = %d\n",h,i,j); h += 2; j += 5; } Function1(3); } public static void Function1(int param) { int localVar; } }