What does 'scope' refer to in Java?
B
The lifetime and visibility of a variable
D
The return type of a method
Analysis & Theory
Scope defines where a variable can be accessed within a program.
Where is a local variable declared?
A
Inside a method or block
D
At the top of the program
Analysis & Theory
Local variables are declared inside methods or blocks and are only accessible there.
What is the output?
```java
public class ScopeTest {
public static void main(String[] args) {
int x = 5;
if (x > 0) {
int y = 10;
System.out.println(y);
}
// System.out.println(y); ← this line would cause
}
}```
Analysis & Theory
Variable `y` is declared inside the `if` block and cannot be accessed outside of it.
Which of the following variables has class-wide scope?
Analysis & Theory
Instance variables are declared inside the class but outside methods and are accessible throughout the class.
What is the output?
```java
public class Test {
int a = 10;
public void print() {
int a = 20;
System.out.println(a);
}
}```
Analysis & Theory
The local variable `a = 20` shadows the instance variable `a = 10` inside the method.
Which keyword makes a variable accessible without creating an object?
Analysis & Theory
`static` variables belong to the class and can be accessed without creating an object.
What is the lifetime of a local variable?
A
As long as the program runs
B
Until the method or block finishes executing
C
Until the class is garbage collected
Analysis & Theory
Local variables exist only while the block or method in which they are declared is executing.
Can a method parameter shadow a class variable?
B
Yes, and you can access the class variable with `this`
Analysis & Theory
Method parameters can shadow instance variables; use `this.variableName` to access the class variable.
What happens if two variables with the same name are declared in the same scope?
B
The program chooses randomly
C
It causes a compile-time error
Analysis & Theory
You cannot declare two variables with the same name in the same scope; it causes a compile-time error.
What is the output?
```java
public class ScopeDemo {
static int a = 100;
public static void main(String[] args) {
int a = 50;
System.out.println(a);
}
}```
Analysis & Theory
The local variable `a = 50` shadows the static variable `a = 100` inside `main()`.