Showing posts with label General. Show all posts
Showing posts with label General. Show all posts

Spring MVC Framework Basic Java Questions - 2

This is the second part of Basic Questions asked on Core Java. Please leave a comment if you think there is something wrong with an answer as it will help me greatly.
Question 1: What is data encapsulation in Java?
Data Encapsulation is the process of hiding the internal information from the external world. The information can only be manipulated using a set of operations exposed by the objects known as methods. This is also called as data hiding.

Question 2: What is the difference between Abstract Class and Interface?
Interface is a pure abstract class, means all the methods in interface are abstract whereas in Abstract class we can have non-abstract methods. All the methods in an interface are public by default, whereas Abstract class can have methods with other access modifier. All the method in an interface have only definition and no declaration, whereas an Abstract class can have method with the default implementation. All the member variables in the interface are final, whereas Abstract class can have non-final variables. An interface needs to be implemented using implements whereas an Abstract class needs to be extended using extends. A Java class can implement multiple interfaces but can only extend one Abstract class.

Question 3: Can I have an Abstract Class without any abstract method and vice-versa?
You can have an abstract class without any abstract method, if you don't declare a class as Abstract that have abstract methods, the class will give compilation error.

Question 4: What is the difference between Exception and Error?
Basically a user can recover from an exception at runtime but not from an Error. For example, a user program may recover from an FileNotFoundException, however, it wont be able to recover from an OutOfMemoryError. In other words, Exceptions are programmer generated and should be handled at the application level, whereas Errors are system generated and should be handled at the system level, if possible.

Errors are also a sub class of the Throwable, however we should try to avoid catching errors. If you have a catch Throwable, the block will also catch the Error, which is not a good practice.

Question 5: What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when the class is loaded using one of the following methods:
  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.
Whereas, NoClassDefFoundError is encountered, when the JVM is trying to load the class as part of a normal method call or as part of creating a new instance using the new expression.

Question 6: Under what condition does finally block will not execute?
Finally block is a block in Java program, which gets executed most of the times. There are only few conditions under which the finally clock will not get executed.
1. If the Application executing the try or catch block exits by calling System.exit or by shutting down JVM.
2. If a thread executing the try or catch block is killed or interrupted, the finally block will not execute.

Question 7: Can you have a finally block without catch?
Yes, you can have finally block with the try statement, without a catch statement.

Spring MVC Framework Basic Java Questions - 1

This page contains the list of question that are generally asked in the Java General Questions. They can also be termed as questions asked on Basic Java Language.
Question 1: What is the difference between java.util.Date and java.sql.Date?
The main difference is that java.util.Date represents "date and time" stored upto a milisecond. However, java.sql.Date only stores data value which is required for the SQL DATE type. java.sql.Date has a java.sql.Time counterpart which stores only time.

Question 2: What is the difference between String, StringBuffer and String Builder?
  • String is immutable whereas StringBuffer/StringBuilder are not. It means it gives faster performance while update operations. 
  • StringBuffer is synchronised whereas StringBuilder is not.
  • Use String if you need immutability, use StringBuffer is you need mutability and thread-safety, use StringBuilder if you need mutability but not thread safety. 

Question 3: What are various visibility modifiers in Java and what is the difference between them?
There are four access modifiers : public, private, protected and default. There accessibility is as defined below:

public - Any class can access it directly.
protected - It is available to class, subclasses and package.
default or no-modifier: It has the package accessibility but is not available to subclasses.
private: This is only visible with the class itself.

Question 4: What is difference between .equals and "=="?
"==" checks whether the two references refer to the same instance whereas .equals check if the two different instances are equal.

Question 5: What is the relationship between .equals and hashcode()? or Why is it a good practise to either override both .equals() and hashcode() or none at all?
The relationship can be explained in simple way as, if two objects returns true for .equals() then their .hashcode() method must return the same value. However, if .hashcode() value returns same value .equals() may not return true, provided .hashcode() and .equals() uses the same fields for evaluation.

You should always override both these methods together because they should use the same fields to evaluate hashcode() and compare the two objects in .equals().

Question 6: Why is clone method "protected" in the Object class?
Default method in the Object class does not provide any implementation, so it does not make sense to make it public. Also, the object which needs to be cloned needs to implement Cloneable interface. Any object that wishes to be available for cloning can override this method and make it public.

Question 7: Is Generics a compile-time feature or runtime feature?
Generics are a compile-time feature, they help us to find some of the bugs at compile-time itself. Generics helps in ensuring the strong type checking. This information is not kept along with the compiled version of class.

Question 8: What is the use of serialVersionUId in Serializable class?
serialVersionUId is used in the serialization and de-serialization process. While serialization and de-serialization the serialVersionUId needs to be same. In case, the serialVersionUId is changed in a class the JVM will throw an "InvalidClassException". You should only change the serialVersionUId only,  when your serialization class is updated by some incompatible Java types changes to a serializable class. Please refer this for further explanation on serialVersionUId.

Question 9: What is the difference between Serializable and Externalizable?
When a class implement the serializable interface, the JVM will serialize and de-serialize the class variables by itself, however, if you want to change the way serialization is done you need to implement the Externalizable interface. When you implement the Serializable interface you dont need to implement any method the JVM will use reflection to serialize your class. However, if you implement Externalizable interface, you need to implement two methods readExternal() and writeExternal(). If you have implemented Serializable you can still control the serialization by writing two methods in your class namely, readObject() and writeObject().

Question 10: How can you control which fields should be serialized?
There are three exceptions to the Serialization process. They are:
1) Static fields are not serialized.
2) transient fields are not serialized.
3) Base class variables are only serialized if the Base class itself implement Serializable.

Spring MVC Framework Singleton Design Pattern Questions

Singleton Design Pattern is the basic design pattern that most of the developers seems to learn at the very early stages of their career (including me). So it is natural that there are lot questions that interviewers asked in order to see whether the person has just crammed up the definition or actually knows how to write it as well. Also, the implementation of this pattern has also changed a lot over time and a thorough knowledge of the same would mean that the person is also up to date with the new techniques.
Question 1: Explain Singleton Design Pattern?
Singleton Design Pattern means there is only one instance of an object in the Application / per classloader.

Question 2: What are the things required to implement a Singleton class?
Singleton class should have a private constructor and there is only way to create singleton instance.

Question 3: How do you implement Singleton?
In order to create a Singleton please see below:

     public class SingleTon {
private static SingleTon INSTANCE;

private SingleTon() {
}

public static SingleTon getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingleTon();
}

return INSTANCE;
}
}
Question 4: Is the above class thread-safe?
The problem with the above class is that if two methods execute the getInstance() method, both of them might be able to create an instance and hence violating the Singleton condition. In order to achieve thread-safety, we can make the getInstance() method synchronized. as below:

     public class SingleTon {
private static SingleTon INSTANCE;

private SingleTon() {
}

public synchronized static SingleTon getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingleTon();
}

return INSTANCE;
}
}
Question 5: In the above solution synchronizing the static method will give you a class level lock and hence have performance impact? How can you remove that?
In order to remove the synchronizing we can have a static field instantiating the Singleton as below:

     public class SingleTon {
private static final SingleTon INSTANCE = new SingleTon();

private SingleTon() {
}

public static SingleTon getInstance() {
return INSTANCE;
}
}
The problem with the above class is that if your Singleton class have lot of constructs you might end up creating them even though you may not need them. So above should only be used if the Singleton is not very heavily loaded.This type of initialization is also known as Eagerly Initialization whereas the above initialization is known as Lazy Initialization.

Question 6: How to improve the above solution incase the class is heavily loaded?
In that case we would like to delay the instantiation process as below, by using an inner static class:
public final class SingleTon {
private static class SingleTonHolder {
private static SingleTon INSTANCE = new SingleTon();
}

private SingleTon() {}

public static SingleTon getInstance() {
return SingleTonHolder.INSTANCE;
}
}
Question 7: How do you prevent the Singleton class creation using reflection?
One way to do that is to throw an exception from the Constructor as follows:
public final class SingleTon {
private static class SingleTonHolder {
private static SingleTon INSTANCE = new SingleTon();
}

private SingleTon() {
if(SingleTonHolder.INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
return SingleTonHolder.INSTANCE;
}
}
Question 8: Is there any other method that can be used to create a Singleton class?
Other method that can be used to create a Singleton class is the enum method, this solution is only applicable post Java 1.5. This is possible using Enum as:
public enum SingleTon3 {
INSTANCE;
// Other instance methods.
}
The advantage of using this is that, Java Memory Model guarantees that there will a single instance of the Enum and Enums are thread-safe as well.

Question 9: What do you understand by the double checked locking in Singleton pattern?
Double checked locking means that the INSTANCE is checked for NULL twice, before and after acquiring lock. Remember that it is only possible after Java 5, with the better handling of volatile fields. This may not work before Java 5.
     public final class SingleTon {
private SingleTon INSTANCE;

private SingleTon() {
if(INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
if(INSTANCE == null) {
synchronized(this) {
if(INSTANCE==null) {
INSTANCE = new SingleTon();
}
}
}

return INSTANCE;
}
}
Question 10: How do you avoid a Singleton being created by serialization?
This problem occurs when your Singleton implements Serializable. The readResolve() method will always return a new instance of the class, just like Constructor. In order to avoid this you can override the readResolve() method to return your INSTANCE as:
     public final class SingleTon {
private volatile SingleTon INSTANCE;

private SingleTon() {
if(INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
if(INSTANCE == null) {
synchronized(this) {
if(INSTANCE==null) {
INSTANCE = new SingleTon();
}
}
}

return INSTANCE;
}

private Object readResolve(){
return INSTANCE;
}
}
This can even become more complex if your Singleton starts to manage states, as then the states have to be transient. This problem can also be handled by Enums, as the serialization is handled by the JVM.
Question 10: Why should you avoid Singleton anti-pattern or why is Singleton is an anti-pattern?
  1. In order to use Singleton we need to call getInstance(), which makes them tightly coupled to the calling object and hence makes them hard to mock while testing.
  2. They maintain their state during the lifetime of the application and hence makes unit testing difficult as you may need to execute your Junit in an order. This voids the basic principle of Unit testing that the tests should be independent of each other.
  3. They violate the Single Responsibility Priniciple, as they manage the creation and lifecycle themselves.
  4. They are generally used as a global variable and creating global variable just to avoid passing them around is a code smell.