// Basic concepts of scope // Dealing mostly with variables; will eventually expand to methods // Author: David Schwartz, dis@cs.cornell.edu // Modified by: Kiri Wagstaff, wkiri@cs.cornell.edu public class scope { public static void main(String[] args) { // Define x local to scope of main: int x = 1; System.out.println("x (1): " + x); // Variables declared inside block {} are visible only inside // that block: { int y = 1; System.out.println("y (1): " + y); // Is x visible? Yes, because it is declared outside the block, // and in the same method: System.out.println("x (2): " + x); } // You cannot compile the following, because y is not visible: // (Try uncommenting it to see what the compiler says) // System.out.println("y (2): " + y); // for statements have the same effect -- variables are local inside, // as if a for were a block: for (int z = 0; z <= 1; z++) { System.out.println("z (1): " + z); } // Try printing z from "outside": //System.out.println("z (1): " + z); // you can't! // To do so, declare z outside of the for loop. } }