Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Suppose you have a method that returns an integer value


Download 1.52 Mb.
Pdf ko'rish
bet111/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   107   108   109   110   111   112   113   114   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Suppose you have a method that returns an integer value.
The code is present within a try/catch/finally. There is a
return statement in the try, catch and finally blocks. The
return statement in the try block returns 1, the return
statement in the catch block returns–1 and the return
statement in the finally block returns 0. If an exception
occurs, which value will be returned?


283.
Answer:
In the scenario described above, the return statement within the
finally block will get executed so the value 0 will be returned.
Since an exception occurs in the try block, the rest of the body of
the try block is skipped. So, the return statement within the try
bock is not executed. Since an exception occurs, the code within
the catch block will get executed. However, since a finally block is
present, the return statement within the catch block is also not
executed. The code within the finally block gets executed and the
return statement from the finally block gets executed. If the finally
block was not present, the return statement from the catch block
would have been executed.
Suppose you have a static method in the Base class. And
suppose you have a method with the same name in the
sub–class. And suppose you create a Base class object
and assign it a reference of the sub–class object and
invoke the static method. Is this valid? If so, which
version of the static method gets invoked?
Answer:
The above scenario is perfectly valid and will not cause any error.
When this code is executed, the static method in the base class
gets invoked. Normally, when you define a variable of the super–
class type and assign it a sub–class object and invoke an
overridden method, the method defined in the sub–class gets
invoked. This is because Java uses the object assigned and not
the reference variable to determine the version of an overridden
method to invoke. However, in the scenario described above, the
methods in the super–class and sub–class are static. Static
methods cannot be overridden. So, if you have a static method in
the base class and a method with the same name in the sub–
class, this would not be an example of overriding. Rather, this is



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   107   108   109   110   111   112   113   114   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling