Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A tricky question of simple Java: variable scope

Tags:

java

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!

like image 237
lixiang Avatar asked Jun 21 '11 13:06

lixiang


People also ask

What is the scope of variable in Java?

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.

How many types of variables scopes are there in Java?

In Java, there are three types of variables based on their scope: Member Variables (Class Level Scope) Local Variables (Method Level Scope)

Which variables have a scope limited?

Variables with limited scope are called local variables.


1 Answers

You can access private members of your own class, even from a different instance of the class.

like image 95
SLaks Avatar answered Sep 21 '22 15:09

SLaks