Scope of Local Variables

public class RectangleTester
{
   public static double area(Rectangle rect)
   {
     
double r = rect.getWidth() * rect.getHeight();
      return r;
   }
   public static void main(String[] args)
   {
     
Rectangle r = new Rectangle(5, 10, 20, 30);
      double a = area(r);
      System.out.println(r);
   }
}

Rectangle r = new Rectangle(5, 10, 20, 30);
if (x >= 0)
{
  
double r = Math.sqrt(x);
   //
Error - can't declare another variable called r
      here
   . . .
}

if (x >= 0)
{
  
double r = Math.sqrt(x);
   . . .
   } // Scope of r ends here
else
{
  
Rectangle r = new Rectangle(5, 10, 20, 30);
   //
OK - it is legal to declare another r here
   . . .
}

Scope of Class Members

Overlapping Scope


Consider the deposit method of the BankAccount class. What is the scope of the variables amount and newBalance?

   Answer: The scope of amount is the entire deposit method. The
   scope of
newBalance starts at the point at which the variable is
   defined and extends to the end of the method.

 


What is the scope of the balance field of the BankAccount class?

Answer: It starts at the beginning of the class and ends at the end of the class.