Preview

09 - Scope and Access

 1. The scope of a variable is defined as where a variable is accessible or can be used.
scopeandaccess_java_AP.png

  TRUE

  FALSE

 2. The scope is determined by where you __________________when you write your programs.

  create the method

  create the object

  declare the variable

  declare the class

 3. Local variables are variables that are declared inside a method, usually __________________.

  at the top of the entire program before any import statements

  at the bottom of the method

  at the top of the method.

  at the very bottom of the class

 4. Parameter variables are also considered local variables that only exist for that method.

  TRUE

  FALSE

 5. It?s good practice to keep any variables that are used by just one method as local variables in that method.

  TRUE

  FALSE

 6. When you declare a variable, look for the closest enclosing curly brackets { } ? this is its ______.

  stopping condition

  variable length

  security key

  scope

 7. Read the excerpt below regarding Java's 3 levels of scope. Fill in the blanks for no. 1
Java has 3 levels of scope that correspond to 
different types of variables:

1. ____________ for instance variables
inside a class.

2. Method Level Scope for local variables 
(including parameter variables) inside a method.

3. Block Level Scope for loop variables and
other local variables defined inside of blocks
of code with { }.

  First Level Scope

  Class Level Scope

  Variable level Scope

  Instance Level Scope

 8. In the following code, lines 5 and 6 refer to variables with Block Level Scope.
public class Name {
    private String first;
    public String last;

    public Name(String theFirst, String theLast) {
        String firstName = theFirst;
        first = firstName;
        last = theLast;
     }
}

  FALSE

  TRUE

 9. In the following code, lines 2 and 3 refer to variables with Method Level Scope.
public class Name {
    private String first;
    public String last;

    public Name(String theFirst, String theLast) {
        String firstName = theFirst;
        first = firstName;
        last = theLast;
     }
}

  FALSE

  TRUE

 10. Analyse the following code and scroll down to the comments. Is the comment true or false in terms of what variable name will be used?
public class Person
{
   private String name;
   private String email;

   public Person(String initName, String initEmail)
   {
      name = initName;
      email = initEmail;
   }

   public String toString()
   {
     String name = "unknown";
     // The instance variable name here will be used,
     //  not the local variable name.
     return  name + ": " + email;
   }

  
   public static void main(String[] args)
   {
      
      Person p1 = new Person("Sana", "[email protected]");
      System.out.println(p1);
   }
}

  FALSE

  TRUE