Continuing our Java/J2EE/JEE interview questions and answers series, today's questions are:

Q What is a final class and a final method ?

A class declared as final, it can never be sub classed. This is usually done for security or performance reasons.


public final class MyTest {
// ...
}




When a method is declared final, it can never be overridden in subclasses.
This is usually done for security or performance reasons, providing additional information to the Just In Time (JIT) compiler or HotSpot.

Note : Declaring methods final restricts later design decisions, so be careful while making this decision

Q Why java.lang package doesn't require import?

The classes in the java.lang package are basic building blocks of Java, that the compiler implicitly imports all the classes there. This ensures classes in the unnamed package are not accidentally used instead of the key classes and interfaces.

Q Can I override a method that doesn't throw exceptions with one that does?

Overriding methods cannot change the signature of the overridden method. All exceptions are included in the signature of the method except for RunTimeException and it's subclasses. So, the only exceptions you may add to an overriding method must be a (sub-class of) RunTimeException.



Q Can I restart a stopped thread and how do I have one thread wait for another thread to finish before continuing?

No you can not restart a thread one it is stopped. Keep in mind though that the use of the stop() method of Thread class is deprecated and should be avoided.

You can wait for a thread to finish by calling its join() method. For instance, in the following code, the current thread will wait until thread2 finishes before printing is finished.


threadTwo.start();
// do more stuff here
threadTwo.join();
System.out.println("ThreadTwo is finished");


Q What is the difference between the & and && operators?

It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguements.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.
For all other argument types and combinations, a compile-time error will occur.

Previous Java J2EE Interview Questions can be read here.
Del.icio.us Digg! My StumbleUpon Page