Introduction: 5.8.0

  • variable scope is defined as where the variable is accessible from
    • Determined by where you declare your variable from
      • look at the nearest curly brackets!
    • A variable doesn’t exist outside of it’s scope!

  • Class level scope for instance variables
  • Method level scope for local variables
    • this includes parameter variables
  • block level scope
    • for loop variables and variables defined inside of blocks of code

Local Variables

  • Local variables are declared inside a method
  • These variables can only be used within the method
    • they do not exist outside!
  • Parameter variables are also local variables
  • Use local variables for anything used in just one method

Instance variables

  • Instance variables are declared at class scope
  • these are shared with all methods
    • can be public or private
      • determine accessibility outside of the class
  • They have class scope regardless of being public or private

Scope problems

  • If a local variable has the same name as an instance variable, the local variable takes prescidense
    • you can use this to refer to the instance variable!

Summary: 5.8.2

  • Scope is where a variable is accessible/can be used
  • Local variables can only be declared in the body of methods & constructors
    • cannot use modifiers like public or private
    • When a local variable has the same name as an instance variable, the name will refer to the local variable
  • formal parameters and variables declared in a method/constructor can only be used in that method/constructor