I am not new to java and C#. I thought I understand the concept of variable scope until recently I was asked this question in an interview:
public class Q{ //starting y scope
static int x = 11;
private int y = 33; // Just added a “private” modifier to make it clearer.
public static void main(String args[]){
Q q = new Q();
q.call(5);
}
public void call(int x){
Q q = new Q();
this.x = 22;
y = 44;
System.out.println("Output: " + Q.x);
System.out.println("Output: " + q.x);
System.out.println("Output: " + q.y);
}
} //ending y scope
Define the output of this program.
I answered the question during the interview that the output would be a runtime exception. To my understanding, y is declared private, and the instance method call() is trying to access the instance private variable y of another instance of class Q. How could that happen at all!? However answering this question wrongly didn't affect my interview too much because this is the kind of "tricky basic" question. But, answering wrongly means my years' Java experience needs rehab, that's terrible!
Could someone help me on this matter? I would be so much appreciated!
Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack. Java programs are organized in the form of classes.
In Java, there are three types of variables based on their scope: Member Variables (Class Level Scope) Local Variables (Method Level Scope)
Variables with limited scope are called local variables.
You can access private
members of your own class, even from a different instance of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With