1 / 9

Variable Scope

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.

ghada
Download Presentation

Variable Scope

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Variable Scope Who can see it and what is its lifetime

  2. 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

  3. Types of Scope • Instance variables • Local variables • Method parameters • For loop variables

  4. 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

  5. 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

  6. 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"); }

  7. Method Parameters • Are created when you call the method • Scope is the entire body of that method • Are destroyed when the method returns

  8. 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

  9. Today’s Paper Practice • Playing with scope • Pay attention to the scope of each of the x and y variables!

More Related