100 likes | 215 Views
Variable Scope. Who can see it and what is its lifetime. Definitions. Scope – the portion of the code that knows the variable exists and can see/modify its value Lifetime – when the variable is created and destroyed B lock – a section of code surrounded by curly brackets. Types of Scope.
E N D
Variable Scope Who can see it and what is its lifetime
Definitions • Scope – the portion of the code that knows the variable exists and can see/modify its value • Lifetime – when the variable is created and destroyed • Block – a section of code surrounded by curly brackets
Types of Scope • Instance variables • Local variables • Method parameters • For loop variables
Instance Variables • Lifetime: Are created when the instance is created and survive until the instance is no longer used • Scope • if private, the scope is the declaring class • if public, the scope is the entire system
Local Variables • Declared within a method • Created when their declaration statement (or first assignment) is executed • Scope is from the point of declaration to the end of the smallest block containing that declaration • Destroyed when the code exits their scope
Local Variable Example private void silly() { booleanfinished = false; while (!finished) { System.out.println("Nox here "); intx = 0; System.out.println(" x has been created"); while (x < 3) { x++; System.out.println("x is still visible here "+ x); } finished = true; System.out.println("we can still see x here " + x); } System.out.println("Nowx is gone"); }
Method Parameters • Are created when you call the method • Scope is the entire body of that method • Are destroyed when the method returns
For Loop Variables • Sometimes, we declare a variable as part of the for statement • Variable is created when the for statement begins • Variable’s scope is the entire for statement (but nothing after that) • Variable is destroyed when the for statement finishes
Today’s Paper Practice • Playing with scope • Pay attention to the scope of each of the x and y variables!