Interview Question – Static variables

Introduction

This question was asked in a recent java interview in Goldman Sachs, this isn’t complicated but candidates might get confused solving it. This is about static blocks and static variables initialization, so I publish this article under the heading Interview Question – Static variables. To get updates on the other articles in the series, please use the Subscribe feature on the right panel.

Problem Statement

What would be the result when the below code is executed?

Solution

What is the approach for solving this question?

If you try to look at the code and find an answer, it might get confusing. Remember how static variables work, lets break down the problem statement as below:

Now as the static variables are initialized with the default values of their respective data type defaults. Hence the static variables are X = 0 and Y = 0.
Now executing the static block will result into assigning the value of X to Y and Y to X once.

After the variable initialization and the static block initialization main method will be executed. Now because X and Y are both zero, it will print
X = 0
Y = 0

Conclusion

This reaches us that we must stick to the basics, if possible break down the problem further, so that we can reduce it to something which we understand and find easy to solve.

Hope this helps, happy reading. Stay connected and stay Subscribed

• anon

won’t x==y and then y===x(==y) –> y=y and thus: x==y, and y==y.
Output will be same as 0,0 but just in case values were assigned, the output should have y in both the cases.