Showing posts with label Basic. Show all posts
Showing posts with label Basic. 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 Multi threading Interview Questions - 1

Multi-threading is a concept that even some of the experience developers also find difficult to understand. If you are appearing for investment bank, insurance or healthcare technology services company, the chances are that you will be tested thoroughly on the multi-threading concepts. Depending upon your experience, the questions may vary from basic to advanced levels. There are generally a set of written questions as well on this topic, which I will try to compile very soon. So, here is the list of basic questions on multi-threading.

Question 1: What is difference between a process and thread?
A process is a single execution of a program whereas a thread is a single execution sequence within a process. A process may contain multiple threads. A thread is sometimes referred to as a lightweight process. Threads in a JVM share the same heap space. Hence, threads can share same object. Threads have their own stack space, this is how one invocation of a method and its local variables are kept thread safe. Heap is not thread safe and hence must be synchronised for thread safety. 

Question 2: What are the different ways of creating Threads?
1) By implementing Runnable
2) By Extending Thread class
3) By using Executor Framework

Question 3: Which of the above method should be use?
Generally we should try to create threads by implementing Runnable as it will come in handy, when we need multiple inheritance.

Question 4: What are Thread states possible?
Thread can have the following states:
1) Runnable - Thread has started and is waiting for the Thread Scheduler to pick and execute.
2) Running - Thread is actively executing the code.
3) Waiting - Waiting for some external event like finish a file I/O to finish.
4) Sleeping - Thread are put to sleep for a certain period of time and will become runnable when it wakes from sleeping duration.
5) Blocked on I/O or Synchronised: Blocked by an external call to I/O or waiting to acquire lock.
6) Dead - Thread has finished executing code.
Question 5: What is difference between sleep and wait method?
Sleep method is used to stop the thread execution for a certain period of time, whereas wait method is used to make the thread wait for some external event or woke up by another thread by calling notify() or notifyAll().

Question 6: What is the difference between notify() and notifyAll()?
notify() and notifyAll() methods are used to pass the control to another thread that might be in the waiting state. When we call notify() it only means that the call will wake up the thread next in line. However, by calling notifyAll() we are actually passing the control to a larger number of threads which in turn may again compete to get control.

Question 7: What is difference between Thread.start() and Thread.run()?
Thread.start() actually does the job of calling Thread.run(). If we call the Thread.run() directly then it would be a simple method call from the main thread. It will not cause the thread to run independently.

Question 8: When is the InvalidMonitorStateException is thrown? why?
This exception is thrown when we try to call wait(), notify() or notifyAll() methods on an object in your program where you do not have the lock on the object. InvalidMonitorStateException extends RuntimeException and hence we do not need to catch it.

Question 9: What happens if the static method is defined as synchronized?
Executing such a method would mean that the thread has acquired a "Class" level lock, which means other threads cannot executed any other "static synchronized" method. This is different then the instance method synchronization in the way that two threads can execute the same synchronized instance method as long as they are executing it on the different instance of the object.

Spring MVC Framework Hibernate Questions -1

Hibernate is an ORM tool that is used by various applications to reduce the effort of writing Database interaction code. It is a kind of becoming de-facto for various database tasks. So it becomes important for most of the organisation in the Java JEE space that there development team is well versed with this technology. Here I would try to list various questions that might be asked on Hibernate technology.


Question 1: What is ORM?
ORM is object relational mapping. It is the automated process for persisting Java objects to relational database.

Question 2: What are the ORM levels?
Main ORM levels are:
  • Pure relational (Stored procedure)
  • Light object mapping  (JDBC)
  • Medium object mapping 
  • Full object mapping (Composition, inheritance, polymorphism)
Question 3: What is Hibernate?
Hibernate is a pure Java ORM tool that maps the POJO's to the relational database tables using (XML) configuration files. It helps in reducing the effort of a Java Developer to produce the code that perfomrs relational database tasks.

Spring MVC Framework Mutli Threading Question Written - 1

Question : There are three threads, which can print an assigned array as below:

            Thread1  - {1,4,5}
            Thread2  - {2,5,7}       
            Thread3  - {3,6,9}

Write a program that print the output so that the output is always 1,2,3,4,5,6,7,8,9? Also, make it extendible so that the same logic can be applied to more number of threads.

Solution:


public class MultipleThreads {
public static void main(String args[]) {
//same instance of printer that is shared among the threads
Printer printer = new Printer(3); // three is the maximum number of threads.

NumberThread thread1 = new NumberThread(new Integer[]{1,4,7}, 1, printer); // First arguement is the array, second is the Thread number, printer is the shared instance
NumberThread thread2 = new NumberThread(new Integer[]{2,5,8}, 2, printer);
NumberThread thread3 = new NumberThread(new Integer[]{3,6,9}, 3, printer);

thread1.start();
thread2.start();
thread3.start();

}
The NumberThread class looks like:
   public class NumberThread extends Thread {

private Integer[] integerArray;
private int threadNumber;
private Printer printer;

//Constructor
public NumberThread(Integer[] array, int thread, Printer printer) {
this.integerArray = array;
this.threadNumber = thread;
this.printer = printer;
}

@Override
public void run() {
int index = 0; // index to keep track that all the elements are traversed
while(index < integerArray.length) {
synchronized(printer) {
while(!printer.myTurn(this.threadNumber)) {
try {
printer.wait();
} catch (InterruptedException ie) {
}
}
printer.print(integerArray[index]);
index++;
printer.notifyAll();
}
}
}

}
The Printer class is as follows:
  public class Printer {
private int maxThreads;
private int currentThread = 1;

public Printer(int numberOfThreads) {
this.maxThreads = numberOfThreads;
}

public void print(int number) {
// print the number
System.out.println(number);
currentThread = (currentThread % maxThreads) + 1;
}

public boolean myTurn(int threadNumber) {
return currentThread == threadNumber;
}
}
In order to extend the above logic, it can be extended for the number of elements in array and the number of threads that needs to be executed in a one-one-by kind of execution.

Please leave a comment if you think there is a problem in the above code or if there is any modification / optimization that can be done.