Java Interview questions

Monday, 20 October 2008, 16:31 | Category : Java
Tags : ,

Here a few Java Interview questions. Divided in three different categories:  Basic, Intermediate,  Advanced.


Q – Can a class have it’s main method declared as private?

A – Yes, the program will compile but fail at runtime.

Q – What if the static modifier is removed from the signature of the main method?

A – Program compiles. But at runtime throws an error “NoSuchMethodError”.

Q – How can I swap two variables without using a third variable?

A – Add two variables and assign the value into First variable. Subtract the Second value with the result  Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:

int a=5,b=10;a=a+b; b=a-b; a=a-b;

Another approach

You use an XOR swap.

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;

Q – When is static variable loaded?

A – Static variable are loaded when classloader loads the class in the JVM. Static variables are allocated memory space when they have been loaded. Object creation is not necessary to load the static vars.

Q – Can an abstract class be declared final?

A – No an abstract class cannot be declared final as it may not have all the implementation.


Q – What is the use of instanceOf ?

A – instanceOf is used to type check an Object to avoid class cast exception mostly.