Wednesday, 23 May 2018


                                                             Interview question
1. What is the scope of variables in Java in following cases? 

Member Variables (Class Level Scope) : The member variables must be declared inside class (outside any function). They can be directly accessed anywhere in class
Local Variables (Method Level Scope) : Variables declared inside a method have method level scope and can’t be accessed outside the method.
Loop Variables (Block Scope) : A variable declared inside pair of brackets “{” and “}” in a method has scope withing the brackets only.

2. What happens if you remove static modifier from the main method?
Program compiles successfully . But at runtime throws an error “NoSuchMethodError”.

3.What is “super” keyword in java?
The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Various scenarios of using java super Keyword:

super is used to refer immediate parent instance variable
super is used to call parent class method
super() is used to call immediate parent constructor


4.Differences between HashMap and HashTable in Java.
1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
3. HashMap is generally preferred over HashTable if thread synchronization is not needed

5.Can we Overload or Override static methods in java ?

Overriding : Overriding is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in superclass (or base class) at runtime.
Overloading: Overloading is related to compile time (or static) polymorphism. This feature allows different methods to have same name, but different signatures, especially number of input parameters and type of input paramaters.
Can we overload static methods?   The answer is ‘Yes’. We can have two ore more static methods with same name, but differences in input parameters
Can we Override static methods in java?  We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’. Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).

No comments:

Post a Comment