Java - Interview Questions on Variables and Operators

Q1.  Can static method access instance variables ?

Ans. Though Static methods cannot access the instance variables directly, They can access them using instance handler.  

Q2.  What is a Final Variable ?

Ans. Final variable is a variable constant that cannot be changed after initialization.

Q3.  When are static variables loaded in memory ?

Ans. They are loaded at runtime when the respective Class is loaded. 

Q4.  Can we serialize static variables ?

Ans. No. Only Object and its members are serialized. Static variables are shared variables and doesn't correspond to a specific object. 

Q5. Why do member variables have default values whereas local variables don't have any default value ?

Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

Q6.  What is the advantage of using arrays over variables ?

Ans. Arrays provide a structure wherein multiple values can be accessed using single reference and index. This helps in iterating over the values using loops.

Q7.  Difference between Class#getInstance() and new operator ?

Ans. Class.getInstance doesn't call the constructor whereas if we create an object using new operator , we need to have a matching constructor or copiler should provide a default constructor.

Q8. Are there any global variables in Java, which can be accessed by other part of your program?

Ans. No. Global variables are not allowed as it wont fit good with the concept of encapsulation.

Q9.  What is the difference between >> and >>>?

Ans. Both bitwise right shift operator ( >> ) and bitwise zero fill right shift operator ( >>> ) are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bit.