Thursday, August 29, 2013

this keyword in Java

The this reference always points to an object’s own instance. Any object can use the this reference to refer to its own instance. Think of the words me, myself, and I: anyone using those words is always referring to themselves. In this post, we'll look into the use of 'this' keyword and it uses in java with example.


What is a class instance
Class instance is an object of a class that you create mostly with the help of 'new' keyword. For instance,
MyClass object = new MyClass();


this Keyword
Within an instance method or a constructorthis is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Use of this keyword
  1. It clarify that you are talking about a field, when there is another variable of the same name. Some use this as a means to differentiate instance variables from local variables or method parameters.
  2. Refer to current object as stated above
  3. Invoke other constructor of the current class in your parameterized constructor.
  4. It can be used to return the instance of a class
  5. this can also be used to refer to the outer object
Note: One point to remember is that this is associated with the instance of the class, so it will not work in static methods

USING THIS TO ACCESS VARIABLES AND METHODS
You can use the keyword this to refer to all methods and variables that are accessible to a class. For example, here’s a modified definition of the class Employee: 
The variable name can be accessed in the class Programmer (which extends the class Employee) as follows:
Because there exists an object of class Employee within the class Programmer, the variable name is accessible to an object of Programmer. The variable name can also be accessed in the class Programmer as follows:
The this reference may be used only when code executing within a method block needs to differentiate between an instance variable and its local variable or method parameters. But some developers use the keyword this all over their code, even when it’s not required. Some use this as a means to differentiate instance variables from local variables or method parameters

In the previous example, the class Employee defines an instance variable with the name name. The Employee class constructor also defines a method parameter name, which is effectively a local variable defined within the scope of the method block. Hence, within the scope of the previously defined Employee constructor, there’s a clash of names, and the local variable will take precedence. Using name within the scope of the Employee class constructor block will implicitly refer to that method’s parameter, not the instance variable. In order to refer to the instance variable name from within the scope of the Employee class constructor, you are obliged to use a this reference.

USING THIS TO ACCESS CONSTRUCTORS
You can also differentiate one constructor from another by using the keyword this. Here’s an example in which the class Employee defines two constructors, with the second constructor calling the first one:

To call the default constructor (one that doesn’t accept any method parameters), call this(). Here’s an example:

If present, a call to a constructor from another constructor must be done on the first line of code of the calling constructor.

Above can be seen with the help of following example:

Inside a class method, when a local variable have the same name as one of the instance variable, the local variable shadows the instance variable inside the method block.
Download CodeProgrammer.java

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Tuesday, August 27, 2013

Thread Communication with Wait(), Notify() & NotifyAll() in Java

In multi-threaded programs, often there is a need for one thread to communicate to another thread. The wait/notify mechanism is useful when threads must communicate in order to provide a functionality. The Object class has three methods, wait(), notify(), and notifyAll() that help threads communicate about the status of an event that the threads care about. In this post, we'll try to create a basic understanding of the most confusing concept of thread communication using methods wait(), notify() and notifyAll(). If you want to go through the Thread basic check this post


Classes that provide necessary support for concurrency in Java
  • Object : has methdods wait(), notify(), notifyAll() etc which are useful for multi-threading.
  • Thread Class
  • Runnable interface
As you every class extends Object class, so all object have some basic multi-threading capability.


In multi-threaded programs, often there is a need for one thread to communicate to another thread. The wait/notify mechanism is useful when threads must communicate in order to provide a functionality.
The method wait() allows the calling thread to wait for the wait object (on which wait() is called). In other words, if you want to make a thread wait for another thread, you can ask it to wait for the wait object using the wait() method. A thread remains in the wait state until some another thread calls the notify() or notifyAll() method on the wait object.


**One key point to remember (and keep in mind for the exam) about wait/notify is this:
wait() notify() and notifyAll() must be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock

Note that if the thread calling wait() does not own the lock, it will throw an IllegalMonitorStateException. This exception is not a checked exception,so you don't have to catch it explicitly. You should always be clear whether a thread has the lock of an object in any given block of code.


Let's first go through a basic example
I have on thread ThreadB other than main thread that calculate the sum of number meanwhile main() thread wait for ThreadB to notify when calculation is doneIt may look complex to you first time if you are using notify(), wait() methods first time. So keep patience!


Try to run the code and observe the output:


In the above example, main thread is waiting for threadB to complete. When ThreadB complete the processing it notify the main thread with notifyAll() method.

This how wait() and notify() communicate..!

May be some of you wondering above sceanrio can be implemented with the help of join() method?
Yes, that's true, see the below example



** The wait() and notify() methods are designed to provide a way to allow a thread to block until specific condition is met. For instance, In case of producer consumer problem, there will be a specific condition where producer or consumer wait i.e, when queue is empty consumer will wait and when queue is full producer will wait.
So,the first thing you have to do is to identify the conditions that you want the methods to wait for.

Following thing to remember while using wait and notify or notifyAll method in Java

  • use notifyAll instead of notify if you expect more than one thread is waiting for lock.
  • wait and notify method must be called in synchronized context
  • use same object for calling wait() and notify() method, every object has its own lock so calling wait() on object A and notify() on object B will not make any sense.

Wait() does not block the thread on which it is called; it blocks the current thread until notify() is called on the same object.
For instance, If you have threads A and B and, while in thread A, called B.wait(), this will stop thread A and not thread B - for as long as B.notify() is not called.

If you still having doubt till this line, please go again before going further because if you are clear about the above point then it will be easy to understand.

Now we'll take an example where two thread communicate where these two thread print the integer value from 1,2,3 ...so on turn by turn.
As I said earlier we need specific condition where these thread will wait for other, so in this example we take a Boolean variable as a specific condition where thread will wait. When it's value is true one thread will wait and when it's false other will wait.

Now see the below example that I created


Execute the above code and observe the output and try to add comments to see the flow as per your need to clear doubt.

Coffee Shop Simulation 
To further understand the wait/notify mechanism, you are going to simulate this coffee shop situation in a program. You can implement the coffee machine as one thread and the waiter as another thread in two different classes. The coffee machine can notify the waiter to take the coffee, and it can wait until the waiter has taken the coffee from the tray. Similarly, the waiter can take the coffee if it is available and notify the coffee machine to make another cup.


Producer Consumer problem
Producer Consumer is one of the classical concurrency problem. As there are many way to solve this problem, here I explained with help of wait(),notify() methods.
In the following code, ArrayList is take as source where producer can put the data and from where consumer consume the data. Here I'm adding one 5 values in ArrayList instead of adding infinite value for the demo purpose. If you understand the example, then you can modify and try yourself

Simulation on the basis of Name of player
As we have already seen the example above where thread printing the value turn wise. Now we implement the same in different way.
Now there will be two player, who will increment the value turn wise. Now the specific condition will be player name instead of boolean flag. Instead of creating ThreadFirst and ThreadSecond we'll create only one Thread and two instance of the same thread will be used.

This way you can implement the previous problem also.
I hope so you got the idea how we use notify(), notifyAll() and wait() methods to implement thread communication.
Best of luck!

When to use notify() and notifyAll()?
Let's examine the subtle difference between these two calls. The notify() method wakes up one thread waiting for the lock (the first thread that called wait() on that lock). The notifyAll() method wakes up all the threads waiting for the lock; the JVM selects one of the threads from the list of threads waiting for the lock and wakes that thread up.

In the case of a single thread waiting for a lock, there is no significant difference between notify() and notifyAll(). However, when there is more than one thread waiting for the lock, in both notify() and notifyAll(), the exact thread woken up is under the control of the JVM and you cannot programmatically control waking up a specific thread.


At first glance, it appears that it is a good idea to just call notify() to wake up one thread; it might seem unnecessary to wake up all the threads. However, the problem with notify() is that the thread woken up might not be the suitable one to be woken up (the thread might be waiting for some other condition, or the condition is still not satisfied for that thread etc). 
In that case, the notify() might be lost and no other thread will wake up potentially leading to a type of deadlock (the notification is lost and all other threads are waiting for notification—forever!).


To avoid this problem, it is always better to call notifyAll() when there is more than one thread waiting for a lock (or more than one condition on which waiting is done). the notifyAll() method wakes up all threads, so it is not very efficient. however, this performance loss is negligible in real world applications.

Related Post:
Daemon Thread in Java with Example
Detail info of Garbage Collection in Java
Basic concept of Thread in java
Interview 120+ Core java Question Answers


If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Monday, August 26, 2013

Basic of Thread in Java

Processors these days have multiple cores, which are multiple execution units in the same processor. To make the best use of these multi-cores, we need to run tasks or threads in parallel. In other words, we need to make our programs multi-threaded (or concurrent).
Multiple threads can run in the context of the same process and thus share the same resources. How multiple thread share same resource you check this post Heap and Memory.

Performing activities in parallel enhances the responsiveness of the application, and thus the user experience.Such parallel activities can be implemented as threads: running multiple threads in parallel at the same time is called multi-threading or concurrency.
For instance, MS word office executed many task at the same time - responding to the user, checking spellings, carrying out formatting and certain associated background tasks, etc. That only possible with multiple threading.
thread




Classes that provide necessary support for concurrency in Java

  • Object : has methdods wait(), notify(), notifyAll() etc which are useful for multi-threading.
  • Thread class
  • Runnable interface

As you every class extends Object class, so all object have some basic multi-threading capability.

Methods detail that are helpful in Multi-threading

Method Method Type Short Description
Thread currentThread() Static method Returns reference to the current thread.
String getName() Instance method Returns the name of the current thread.
int getPriority() Instance method Returns the priority value of the current thread.
void join(),                    void join(long),                   void join(long, int) Overloaded
instance methods
The current thread invoking join on another thread waits
until the other thread dies. You can optionally give the
timeout in milliseconds (given in long) or timeout in
milliseconds as well as nanoseconds (given in long and int).
void run() Instance method Once you start a thread (using the start() method), the
run() method will be called when the thread is ready to
execute.
void setName(String) Instance method Changes the name of the thread to the given name in the
argument.
void setPriority(int) Instance method Sets the priority of the thread to the given argument value
void sleep(long),          void sleep(long, int) Overloaded static
methods
Makes the current thread sleep for given milliseconds
(given in long) or for given milliseconds and nanoseconds
(given in long and int).
void start() Instance method Starts the thread; JVM calls the run() method of the
thread.
String toString() Instance method Returns the string representation of the thread; the string
has the thread’s name, priority, and its group.

Method Method Type Short Description
void wait(),
void wait(long),           void wait(long, int)
Overloaded instance
methods
The current thread should have acquired a lock on this
object before calling any of the wait methods.
If wait() is called, the thread waits infinitely until some
other thread notifies (by calling the notify()/notifyAll()
method) for this lock.
The method wait(long) takes milliseconds as an argument.
The thread waits till it is notified or the timeout happens.
The wait(long, int) method is similar to wait(long) and
additionally takes nanoseconds as an argument.
void notify() Instance method The current thread should have acquired a lock on this
object before calling notify(). The JVM chooses a single
thread that is waiting on the lock and wakes it up.
void notifyAll() Instance method The current thread should have acquired a lock before
calling notifyAll(). The JVM wakes up all the threads
waiting on a lock.



Basic ways to create thread?
  • By extending the Thread class
    You need to override the run() method when you want to extend the Thread class. If you don’t override the run() method, the default run() method from the Thread class will be called, which does nothing.
  • By implementing the Runnable interface
    The Thread class itself implements the Runnable interface. Instead of extending the Thread class, you can implement the Runnable interface. The Runnable interface declares a sole method, run()
Note: run() method should be declared as public void run().

Should you extend the Thread or implement the Runnable?
Since Java supports only single inheritance, if you extend from Thread, you cannot extend from any other class. On the other hand, if you implement the Runnable interface, you can still extend some other class. So, many Java experts suggest that it is better to implement the Runnable interface unless there are some strong reasons to extend the Thread class.
Why we call start() methods instead of run() method?
First we see one example:




public class MyFirstThread extends Thread {
  public void run() {
   System.out.println("In run method; thread name is: " +
    Thread.currentThread().getName());
 }
 public static void main(String args[]) throws Exception {
  Thread myThread = new Thread(new MyFirstThread());
  myThread.run(); // note run() instead of start() here
  System.out.println("In main method; thread name is : " +
    Thread.currentThread().getName());
 }
}



Output :

In run method; thread name is: main

In main method; thread name is : main

The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns. On the other hand if you can run() directly, it simply executes as part of the calling thread.It does not execute as a thread: it doesn't get scheduled and get called by the JVM

That is why the getName() method in the run() method returns “main” instead of “Thread-0.” When you call the start() method, the thread gets scheduled and the run() method is invoked by the JVM when it is time to execute that thread.

**Never call the run() method directly for invoking a thread. Use the start() method and leave it to the JVM to implicitly invoke the run() method. Calling the run() method directly instead of calling start() is a mistake and is fairly common bug.


Thread Name, Priority, and Group
Every thread has a name, which you can used to identify the thread. If you do not give a name explicitly, a thread will get a default name. The priority can vary from 1, the lowest, to 10, the highest



class SimpleThread {
public static void main(String []s) {
 Thread t = new Thread();
 System.out.println(t);
 }
}

This program prints the following:
Thread[Thread-0,5,main]

Explanation: default name Thread-0,The default priority is 5,default thread group is main.

You can change the same like this
t.setName("SimpleThread");
t.setPriority(9);


The States of a Thread
A thread has various states during its lifetime.You’ll see three thread states—new, runnable and terminated—which are applicable to almost all threads


How to access thread state in a program?
  • Thread.State enumeration
  • getState() instance method
Two States in “Runnable” State
  • ready state 
  • running state 
A thread is in the ready state when it is waiting for the OS to run it in the processor. When the OS actually runs it in the processor, it is in the running state
Basic Thread state example:

class BasicThreadStates extends Thread {
 public static void main(String []s) throws Exception {
  Thread t=new Thread(new BasicThreadStates()); 
  System.out.println("Just after creating thread; \n" +"The thread state is: " + t.getState());
  t.start();
  System.out.println("Just after calling t.start(); \n" +"The thread state is: " + t.getState());
  t.join();
  System.out.println("Just after main calling t.join(); \n" +"The thread state is: " + t.getState());
 }
}





timed_waiting and blocked States
Example:


class SleepyThread extends Thread {
 public void run() {
  synchronized(SleepyThread.class) {
   try {
    Thread.sleep(1000);
   }
   catch(InterruptedException ie) {
    ie.printStackTrace();
   }
  }
 }
}
class MoreThreadStates {
 public static void main(String []s) {
  Thread t1=new SleepyThread();
  Thread t2 =new SleepyThread();
  t1.start();
  t2.start();
  System.out.println(t1.getName()  +": I'm in state " + t1.getState());
  System.out.println(t2.getName()  +": I'm in state " + t2.getState());

  }
}


Output will look like :
Thread-0: I'm in state TIMED_WAITING
Thread-1: I'm in state BLOCKED


Concurrent Access Problems
Threads share memory, and they can concurrently modify data. Since the modification can be done at the same time without safeguards, this can lead to unintuitive results.

Data Races or Race condition or Race hazard
When two or more threads are trying to access a variable and one of them wants to modify it, you get a problem known as a data race.

Let see with an example:
class Counter {
 public static long count = 0;
}
class UseCounter implements Runnable {
 public void increment() {
  Counter.count++;
  System.out.print(Counter.count + " ");
 }
 public void run() {
  increment();
  increment();
  increment();
 }
}
// This class creates three threads
public class DataRace {
 public static void main(String args[]) {
  UseCounter c = new UseCounter();
  Thread t1 = new Thread(c);
  Thread t2 = new Thread(c);
  Thread t3 = new Thread(c);
  t1.start();
  t2.start();
  t3.start();
 }
}


when you run this program, it does print nine integer values, but the output looks like
3 3 5 6 3 7 8 4 9

The expression Counter.count++ is a write operation, and the next System.out.print statement has a read operation for Counter.count. When the three threads execute, each of them has a local copy of the value Counter.count and when they update the counter with Counter.count++, they need not immediately reflect that value in the main memory .In the next read operation of Counter.count, the local value of Counter.count is printed.

To avoid this problem, you need to ensure that a single thread does the write and read operations together.The section of code that is commonly accessed and modified by more than one thread is known as critical section.

Now Synchronization will come into picture.

Thread Synchronization
Java has a keyword, synchronized, that helps in thread synchronization
Use of synchronized keyword:
  • synchronized blocks
  • synchronized methods


synchronized blocksIn synchronized blocks, you use the synchronized keyword for a reference variable and follow it by a block of code. A thread has to acquire a lock on the synchronized variable to enter the block; when the execution of the block completes, the thread releases the lock. 

synchronized(this) {
// code segment guarded by the mutex lock
}
What if an exception gets thrown inside the synchronized block? Will the lock get released? 

Yes, no matter whether the block is executed fully or an exception is thrown, the lock will be automatically released by the JVM.
With synchronized blocks, you can acquire a lock on a reference variable only. If you use a primitive type, you will get a
compiler error.

int i = 10;
synchronized(i) { /* block of code here*/}



synchronized methodsIn entire method can be declared synchronized. In that case, when the method declared as synchronized is called, a lock is obtained on the object on which the method is called, and it is released when the method returns to the caller.
A synchronized method is equivalent to a synchronized block if you enclose the whole method body in a synchronized(this) block.


Synchronized Blocks vs. Synchronized Methods
If you want to acquire a lock on an object for only a small block of code and not the whole method, then synchronized blocks are sufficient; using synchronized methods is overkill in that case.In general, it is better to acquire locks for small segments of code instead of locking methods unnecessarily, so synchronized blocks are useful there. 

In synchronized blocks, you can explicitly provide the reference object on which you want to acquire a lock. 
However, in the case of a synchronized method, you do not provide any explicit reference to acquire a lock on. A synchronized method acquires an implicit lock on the this reference.


Deadlocks
Obtaining and using locks is tricky, and it can lead to lots of problems. One of the difficult problems is known as a deadlock.

A deadlock arises when locking threads result in a situation where they cannot proceed and thus wait indefinitely for others to terminate.Say, one thread acquires a lock on resource r1 and waits to acquire another on resource r2. At the same time, say there is another thread that has already acquired r2 and is waiting to obtain a lock on r1. Neither of the threads can proceed until the other one releases the lock, which never happens—so they are stuck in a deadlock.




Let's take an example from cricket game. In this, we have two resources one will hold the total numbers of balls thrown so far and other to hold numbers of runs scored so far.






/*
 * Hold number of balls
 */
class Balls{
 public static int balls=0;
}
/*
 * Hold number of runs
 */
class Runs{
 public static int runs=0;
}

class CricketCounter implements Runnable{
 public void run() {
  IncrementRunAfterBall();
  IncrementBallAfterRun();
 }

 public void IncrementRunAfterBall(){
  //since we are updating balls first
  synchronized (Balls.class) {
   System.out.println(Thread.currentThread().getName()+" waiting for run resources");
   synchronized (Runs.class) {
    Balls.balls++;
    Runs.runs++;
   }
  }
 }

 public void IncrementBallAfterRun(){
  //since we are updating Runs first
  synchronized (Runs.class) {
   System.out.println(Thread.currentThread().getName()+" waiting for ball resources");
   synchronized (Balls.class) {
    Runs.runs++;
    Balls.balls++;
   }
  }
 }

}
public class DeadlockDemo {
 public static void main(String[] args) {
  CricketCounter c= new CricketCounter();
  Thread t1=new Thread(c);
  Thread t2=new Thread(c);
  t1.start();
  t2.start();
 }

}

Sample Output

Thread-0 waiting for run resources
Thread-1 waiting for run resources
Thread-0 waiting for ball resources


From the above output, you can easily see that both the thread has already acquired the Balls resources and Thread-0 acquired the Runs resources and Thread-1 waiting for Runs resources that is already acquired by other thread-0.

When the threads t1 and t2 execute, they invoke the methods IncrementBallAfterRun and IncrementRunAfterBall. In these methods, locks are obtained in opposite order. It might happen that t1 acquires a lock on Runs.class and then waits to acquire a lock on Balls.class. Meanwhile, t2 might have acquired the Balls.class and now will be waiting to acquire a lock on the Runs.class. Therefore, this program can lead to a deadlock 




Related Post:
Daemon Thread in Java
Thread communication with wait(), notify(), notifyAll()
Detail concept of class loader in Java
Interview related concept of Garbage Collection in java

If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...

Friday, August 23, 2013

Core Java Interview Questions & Answers

In this post, you'll see basic core java questions from Interview point of view. These list of questions/answers will be updated regularly with new questions and for more detailed concept, see other posts


1 .What are the difference b/w JVM,  JRE,  JDK and OpenJDK?
Java virtual machine (JVM) is a virtual machine that can execute Java bytecode. It is the code execution component of the Java software platform.
The Java Development Kit (JDK) is an Oracle Corporation product aimed at Java developers. Since the introduction of Java, it has been by far the most widely used Java Software Development Kit (SDK).
Java Runtime Environment, is also referred to as the Java Runtime, Runtime Environment
OpenJDK (Open Java Development Kit) is a free and open source implementation of the Java programming language.[2] It is the result of an effort Sun Microsystems began in 2006. The implementation is licensed under the GNU General Public License (GPL) with a linking exception

2.What are different types of memory?

  • Heap Memory
  • Non-Heap Memory : It comprises of ‘Method Area’ and other memory required for internal processing.Method Area : It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.
  • Memory Pool : Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory.
  • Java Stack or FramesJava stacks are created private to a thread.
  • Memory generations

3 .What is class loader in java?
A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.
Different type of class loader:
  • bootstrap class loader : responsible for loading key Java classes like java.lang.Object and other runtime code into memory first
  • extension class loader : responsible for loading all .jar files kept in the java.ext.dirs path
  • application class loader : responsible for loading all of the classes kept in the path corresponding to the java.class.path system property.

4.What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming rest. They are:


  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation

(i.e. easily remembered as A-PIE).

5.What is Abstraction?
Abstraction refers to the act of representing essential features without including the background
details or explanations.
Example :
  • An interface is example of Abstraction : It contains signature of methods to be implemented  but have no code. Similar for Abstract classes.
  • Getter and setter of property : Inside your getter and setter you fetch and change your internal variables but the outer world (developer), only knows that he is provide / getting age or name etc of a customer.
Advantages:
  • Helps to manage the complexity of a large system.
  • Support our quality goals of modifiability and reusability.
  • Most modifications can be localized to just a few modules.
  • Supports the creation of generic modules that can be used in other systems.

6.What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
Another definition
"Its basically about hiding the state of object with the help of modifiers like private,public,protected etc. we expose the state thru public methods only if require."
The insulation of the data from direct access by the program is called data hiding or information hiding.

When we design a class in OOP, the first principle we should have in mind is encapsulation. Group the related data and its behavior in a bucket. Primary benefit of encapsulation is, better maintainability.

Example : Following is an outline example for Java encapsulation. When we talk about an animal, we should have all its attributes listed, similarly its behavior like how it will hunt, run, mate, etc. By bundling all these data and behavior in a single class we are following encapsulation principles.

public class Animal {
  private String animalName;
  private String animalType;
  private int height;
  private String color;
  public Animal(String animalName, String animalType) {
    this.animalName = animalName;
    this.animalType = animalType;
  } 
  public void hunt() {
    // implementation of hunt
  } 
  public void run() {
    // implementation of run
  } 
  public void mate() {
    // implementation of mate
  }
  //encapsulation is not about having getter/setters
  public String getAnimalName() {
    return animalName;
  } 
  public void setAnimalName(String animalName) {
    this.animalName = animalName;
  } 
  public String getAnimalType() {
    return animalType;
  } 
  public void setAnimalType(String animalType) {
    this.animalType = animalType;
  }
}

7.What is the difference between abstraction and encapsulation?
  • Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s). where as Abstraction is providing a generalization (say, over a set of behaviors).
  • Encapsulation means hiding the internal details or mechanics of how an object does something. Where Abstraction lets you focus on what the object does instead of how it does it.
  • Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view,where the behavior of the abstraction is implemented.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
8.What is Inheritance?
  • Inheritance is the process by which objects of one class acquire the properties of objects of another class.
  • A class that is inherited is called a superclass.
  • The class that does the inheriting is called a subclass.
  • Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are:
  •  To promote code reuse
  •  To use polymorphism
  • With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.
Why Java doesn't support multiple inheritance?(check here).


9.What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
Polymorphism can be implemented using the abstract and interface keywords, which enforce to implement the methods in the sub types. 

10.How does Java implement polymorphism?
Inheritance, Overloading and Overriding are used to achieve Polymorphism in java.
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
  • In some cases, multiple methods have the same name, but different formal argument lists(overloaded methods).
  • In other cases, multiple methods have the same name, same return type, and same formalargument list (overridden methods).

11.Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism.
Compile time polymorphism is method overloading. 
Runtime time polymorphism is done using inheritance and interface.
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms
in Java:
  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface
12.What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time. In this process, an overridden
method is called through the reference variable of a superclass. The determination of the method to
be called is based on the object being referred to by the reference variable.

13.What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

14. What is Early or static Binding?
If the compiler can resolve the binding at the compile time only then such a binding is called Static Binding or Early Binding. 
All the instance method calls are always resolved at runtime, but all the static method calls are resolved at compile time itself and hence we have static binding for static method calls. Because static methods are class methods and hence they can be accessed using the class name itself and therefore access to them is required to be resolved during compile time only using the compile time type information. That's the reason why static methods can not actually be overriden.

15. What is Aggregation?
Aggregation is a relationship between two classes that is best described as a “has-a” and “whole/part” relationship where the part can exist without the whole.

final class Car {

  private Engine engine;

  void setEngine(Engine engine) {
    this.engine = engine;
  }

  void move() {
    if (engine != null)
      engine.work();
  }
}
With aggregation, the Car also performs its functions through an Engine, but the Engine is not always an internal part of the Car. Engines may be swapped, or even completely removed. Not only that, but the outside world can still have a reference to the Engine, and tinker with it regardless of whether it's in the Car.

16.What is Composition?
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

final class Car {

  private final Engine engine;

  Car(EngineSpecs specs) {
    engine = new Engine(specs);
  }

  void move() {
    engine.work();
  }
}
In the case of composition, the Engine is completely encapsulated by the Car. There is no way for the outside world to get a reference to the Engine. The Engine lives and dies with the car. 

17. What is Association?
Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. 
In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

18. What is Heap and Stack Memory in Java?

19. What is Instance variable?
Instance variables are defined inside the class, but outside of any method, and
are only initialized when the class is instantiated. Instance variables are the fields
that belong to each unique object.
  • Can use any of the four access levels
  • Can be marked final
  • Can be marked transient
  • Cannot be marked abstract
  • Cannot be marked synchronized
  • Cannot be marked strictfp
  • Cannot be marked native
  • Cannot be marked static, because then they'd become class variables.
20. What is transient variable?
If you mark an instance variable as transient, you're telling the JVM to skip (ignore) this variable when you attempt to serialize the object containing it. Serialization is one of the coolest features of Java; it lets you save (sometimes called "flatten") an object by writing its state (in other words, the value of its instance variables) to a special type of I/O stream. 

21. What is method overloading?
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:
  • Overloaded methods MUST change the argument list
  • Overloaded methods CAN change the return type
  • Overloaded methods CAN change the access modifier
  • Overloaded methods CAN declare new or broader checked exceptions
  • A method can be overloaded in the same class or in a subclass
22. What is method overriding?
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
The rules for overriding a method are as follows:
  • The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method you didn't intend.
  • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass.
  • The access level can't be more restrictive than the overridden method's.
  • The access level CAN be less restrictive than that of the overridden method. Instance methods can be overridden only if they are inherited by the subclass.A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected 
  • The overriding method CAN throw any unchecked (runtime) exception,regardless of whether the overridden method declares the exception
  • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.
  • The overriding method can throw narrower or fewer exceptions.
  • You cannot override a method marked final.
  • You cannot override a method marked static. 
  • If a method can't be inherited, you cannot override it

23. What is upcasting and downcasting ?


24. What are the differences between method overloading and method overriding?
25. Can overloaded methods be override too?
Yes, derived classes still can override the overloaded methods.
Polymorphism can still happen.Compiler will not binding the method calls since it is  overloaded, because it might be overridden now or in the future.

26. Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.

27. How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method. Like this
super.overriddenMethod();

28. What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
  • You can only go back one level.
  • In the constructor, if you use super(), it must be the very first code, and you cannot accessany this.xxx variables or methods to compute its parameters.
29. How do you prevent a method from being overridden?
To prevent a specific method from being overridden in a subclass, use the final modifier on the method
declaration, which means "this is the final implementation of this method", the end of its inheritance
hierarchy.

30. What is an Interface?
An interface is a special form of an abstract class which does not implement any methods. In Java, you create an interface like this:
interface Interface
{
    void interfaceMethod();
}
Since the interface can't implement any methods, it's implied that the entire thing, including all the methods, are both public and abstract 
  • All interface methods are implicitly public and abstract. In other words,you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
  • All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables.
  • Interface methods must not be static.
  • An interface can extend one or more other interfaces.
  • An interface cannot extend anything but another interface
  • An interface cannot implement another interface or class.
  • An interface must be declared with the keyword interface.
  • Interface types can be used polymorphically 

31. Can we instantiate an interface?
You can’t instantiate an interface directly, but you can instantiate a class that implements an
interface.

32. Can we create an object for an interface?
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

33. Do interfaces have member variables?
Interfaces may have member variables, but these are implicitly public, static, and final- in other
words, interfaces can declare only constants, not instance variables that are available to all
implementations and may be used as key references for method arguments for example.

34. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

35. What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. 
The java.io.Serializableinterface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

36. What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
  • If even a single method is abstract, the whole class must be declared abstract.
  • Abstract classes may not be instantiated, and require subclasses to provide implementationsfor the abstract methods.
  • You can’t mark a class as both abstract and final.
37. Can we instantiate an abstract class?
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

38. What are the differences between Interface and Abstract class?


39. When should I use abstract classes and when should I use interfaces?
Use Interfaces when...
  • You see that something in your design will change frequently.
  • If various implementations only share method signatures then it is better to use Interfaces.
  • you need some classes to use some methods which you don't want to be included in the class,then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when...
  • If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
  • When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
  • Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
40. When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.

41. Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.

42. What is Constructor?
  • A constructor is a special method whose task is to initialize the object of its class.
  • It is special because its name is the same as the class name.
  • They do not have return types, not even void and therefore they cannot return values.
  • They cannot be inherited, though a derived class can call the base class constructor.
  • Constructor is invoked whenever an object of its associated class is created.
  • If you don't type a constructor into your class code, a default constructor will be automatically generated by the compiler.
  • The default constructor is ALWAYS a no-arg constructor.
  • Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
  • Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
  • Interfaces do not have constructors. Interfaces are not part of an object's inheritance tree.
43. How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code
The access modifier(public/private/etc.) of the default constructor is the same as the class itself.

44. Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.

45. What are the differences between Contructors and Methods?

46. How are this() and super() used with constructors?
  • Constructors use this to refer to another constructor in the same class with a different parameter list.
  • Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
47. What are the differences between Class Methods and Instance Methods?

48. What is cohesion and coupling?

Coupling refers to the degree to which one class knows about or uses members of another class.

  • Loose coupling is the desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage.
  • Tight coupling is the undesirable state of having classes that break the rules of loose coupling.

Cohesion refers to the degree in which a class has a single, well-defined role
or responsibility.

  • High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility.
  • Low cohesion is the undesirable state of a class whose members support multiple, unfocused roles or responsibilities.


49. What are Access Specifiers?
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data
in a class and making this class available only through methods. Java allows you to control access to
classes, methods, and fields via so-called access specifiers.

50. What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
  • Public- public classes, methods, and fields can be accessed from everywhere.
  • Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
  • Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
  • Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
51. What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore. The actual
meaning depends on whether it is applied to a class, a variable, or a method.
  • final Classes- A final class cannot have subclasses.
  • final Variables- A final variable cannot be changed once it is initialized.
  • final Methods- A final method cannot be overridden by subclasses.
52. What are the uses of final method?
There are two reasons for marking a method as final:
  • The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method.
  • Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
53. What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.

54. What are static variables?
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
Static variables that are not explicitly initialized in the code are automatically initialized with a
default value. The default value depends on the data type of the variables.

Things you can mark as static:

  • Methods
  • Variables
  • A class nested within another class, but not within a method
  • Initialization blocks

Things you can't mark as static:

  • Constructors
  • Classes (unless they are nested)
  • Interfaces
  • Method local inner classes 
  • Inner class methods and instance variables
  • Local variables

55.What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class.
Non-static variables take on unique values with each object instance.

56. What are static methods?
Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
The use of a static method suffers from the following restrictions:
  • A static method can only call other static methods.
  • A static method must only access static data.
  • A static method cannot reference to the current object using keywords super or this.
57. What is Native Methods?The native modifier indicates that a method is implemented in platform-dependent code, often in C. You don't need to know how to use native methods for the exam, other than knowing that native is a modifier (thus a reserved keyword) and that native can be applied only to methods—not classes, not variables, just methods.



58. What is synchronized Methods?The synchronized keyword indicates that a method can be accessed by only one thread at a time.The synchronized modifier can be applied only to methods—not variables, not classes, just methods. 


59. Is there is any way to create instance of Java Object with out using new operator?
 You can use Class.forName to create instance of object.Class.forName("Your Class Name").newInstance();

60. Why String is immutable?


61. How to create immutable objects?

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    Don't provide methods that modify the mutable objects.
    Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
62. What is the difference between creating String using new () and literal?
When we create string using new () instance created on heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.


63. What is Final Keyword?
 Final Keyword comes in three flavor along with variable, method and class. When it comes with variable you can not change the value of final variable. When it comes with method you can not override final method. And when it comes with class you can extend final class i.e. No Subclass (String class).

64. Explain different ways of creating a thread?
 Threads can be used by either

  • Extending the Thread class.
  • Implementing the Runnable interface.
  • Using the Executor framework (this creates a thread pool) 

65. What are the Thread state?

  • Runnable — A thread becomes runnable when you call the start( ), but does  not necessarily start running immediately.  It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities. 
  • Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently
  • Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.
    • Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
    • Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
    • Blocked on synchronization: will move to running when a lock is acquired.
    • Dead: The thread is finished working.


    How to check thread state
    class BasicThreadStates extends Thread {
    public static void main(String []s) throws Exception {
    Thread t = new Thread(new BasicThreadStates());
    System.out.println("Just after creating thread; \n" +"The thread state is: " + t.getState());
    t.start();
    System.out.println("Just after calling t.start(); \n" + "The thread state is: " + t.getState());
    t.join();
    System.out.println("Just after main calling t.join(); \n" + "The thread state is: " + t.getState());
    }
    }

    A word of advice: be careful about accessing the thread states using the getState() method. Why? By the time you acquire information on a thread state and print it, the state could have changed! 


    66. What is the difference between yield and sleeping? What is the difference between the methods sleep( ) and wait( )? 
    When a task invokes yield( ), it changes from running state to runnable state. When a task invokes sleep ( ), it changes from running state to waiting/sleeping state.
    The method wait(1000), causes the current thread to sleep up to one second. A thread could sleep less than 1 second if it receives the notify( ) or notifyAll( ) method call. The call to sleep(1000) causes the current thread to sleep for 1 second.

    67. What is Runnable interface ? Are there any other ways to make a java program as multithred java program?
    There are two ways to create new kinds of threads
    1. Define a new class that extends the Thread class
    2. Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor. 
    An advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class
    68. What is a transient variable?
    If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. 

    69. What methods java providing for Thread communications ?

    • wait()
    • notify()
    • notifyAll()

    70. What is the difference between notify and notify All methods ?
    A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll() causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll() than notify).

    71. What is the difference between a synchronized method and a synchronized block?
    A synchronized method ensures that the whole method is executed completely by one thread before another thread can invoke it. A synchronized block restricts the mutual exclusion to only that block of code. One should try to make the synchronized block as small as possible.

    72. What is a deadlock?
    Deadlock is a condition when multiple threads are stuck because they are waiting for a resource that is owned by another thread and there is a cyclic pattern of this phenomenon. A simple example is thread t1 owns resource A and is waiting for resource B and thread t2 owns resource B and is waiting for resource A. When this happens, none of the threads can proceed and we encounter a deadlock. This scenario can be extended to multiple threads owning one resource and waiting for another resource that forms a circular dependency. This causes a deadlock.

    73. What four things are required for a deadlock to occur?

    1.  Mutual exclusion, which is to say that at least one resource is not shareable, i.e. can only be used by one process at a time.
    2. Hold and wait which is to say that a process holds at least one resource and requests resources held by other processes. 
    3. No preemption which is to say that the resource must be voluntarily surrendered by the process. 
    4. Circular wait which is to say that given a set of processes {P1, P2, P3,...Pn}, P1 has a resource needed by P2, P2 has a resource needed by P3,... Pn has a resource needed by P1.

    74. Why do you need synchronization?
    Synchronization is needed when a shared resource is being accessed and modified by different threads. Without Synchronization, the resource may be found in an inconsistent state if one thread gets pre-empted before it can complete it's action, e.g. a node is being added to a tree and another thread tries to traverse the tree.


    75. Explain how to use the join() method.?
    The method join is a method of the Thread object. It is defined as final void join() throws InterruptedException. When this method is invoked on thread t, the calling thread goes to sleep until thread t terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.

    76. What is a livelock?
    Livelock is when two threads or processes get deadlocked because they try to perform the same action to come out of a potential deadlock. A real-world example of livelock occurs when two people meet in a corridor and each tries to be polite by moving aside. Problem is they move in the same direction and are still in each other's way.

    77. What is a Starvation?
    Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

    78. What are the guidelines for picking up a method to create a thread in Java?
    If a class already extends from a base class, it is not possible to also extend the Thread class because multiple inheritance is not supported in Java classes. In that case, the user has the option of implementing Runnable.

    79. What is difference between CountDownLatch and CyclicBarrier in Java?
    Main difference between CountDownLatch and CyclicBarrier is that, you cannot reuse CountDownLatch but you can reuse CyclicBarrier once its finished and barrier is broken. this is in fact a tricky concurrency question because Java programmer some time confuse between CountDownLatch and CyclicBarrier.

    80. What is difference between fail-fast and fail-safe iterator in Java?
    Fail-fast Iterators are those which fails by throwing ConcurrentModificationException once they detect any structural change in Iterator once iteration begins. while fail-safe Iterator doesn't throw ConcurrentModificationException.


    81. Different meaning of collection?

    collection Represents the data structure in which objects are stored

    Collection java.util interface from which Set and List extend

    Collections A class that holds static collection utility methods

    Four basic flavors of collections 

    • Lists of things Ordered, duplicates allowed, with an index.
    • Sets of things May or may not be ordered and/or sorted; duplicates not allowed.
    • Maps of things with keys May or may not be ordered and/or sorted; duplicate keys are not allowed.
    • Queues of things to process Ordered by FIFO or by priority.

        82. Quick review of Collection?
        • ArrayList: Fast iteration and fast random access.
        • Vector: It's like a slower ArrayList, but it has synchronized methods.
        • LinkedList: Good for adding elements to the ends, i.e., stacks and queues.
        • HashSet: Fast access, assures no duplicates, provides no ordering.
        • LinkedHashSet: No duplicates; iterates by insertion order.
        • TreeSet: No duplicates; iterates in sorted order.
        • HashMap: Fastest updates (key/values); allows one null key, many null values.
        • Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
        • LinkedHashMap: Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.
        • TreeMap: A sorted map.
        • PriorityQueue: A to-do list ordered by the elements' priority.

                          83. What is an Iterator ?
                          • The Iterator interface is used to step through the elements of a Collection.
                          • Iterators let you process each element of a Collection.
                          • Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
                          • Iterator is an Interface implemented a different way for every Collection.
                          84. How do you traverse through a collection using its Iterator?
                          To use an iterator to traverse through the contents of a collection, follow these steps:
                          • Obtain an iterator to the start of the collection by calling the collection iterator() method.
                          • Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
                          • Within the loop, obtain each element by calling next().
                          85. How do you remove elements during Iteration?
                          Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

                          86. What is the difference between Enumeration and Iterator?
                          Iterators differ from enumerations in two ways:
                          • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
                          • Method names have been improved.
                          Here is a side-by-side comparison:
                            Enumeration                     Iterator
                            ----------------                ----------------
                            hasMoreElement()                hasNext()
                            nextElement()                   next()
                            N/A                             remove()

                          87. How is ListIterator?

                          ListIterator is just like Iterator, except it allows us to access the collection in either the forward or

                          backward direction and lets us modify an element



                          88. What is the List interface?

                          • The List interface provides support for ordered collections of objects.
                          • Lists may contain duplicate elements.

                          89. What are the main implementations of the List interface?

                          The main implementations of the List interface are as follows :

                          • ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
                          • Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
                          • LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).

                          90. What are the advantages of ArrayList over arrays?

                          • It can grow dynamically
                          • It provides more powerful insertion and search mechanisms than arrays.

                          91. Difference between ArrayList and Vector?




                          92. How to obtain Array from an ArrayList ?

                          Array can be obtained from an ArrayList using toArray() method on ArrayList.

                          List arrayList = new ArrayList();
                          arrayList.add(a)
                          ObjectA a[] = arrayList.toArray();



                          93. Why insertion and deletion in ArrayList is slow compared to LinkedList ?

                          • ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
                          • During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion.
                            In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node.
                            Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

                          94. Why are Iterators returned by ArrayList called Fail Fast ?

                          Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a  concurrentModificationException.
                          Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.



                          95. How do you decide when to use ArrayList and When to use LinkedList?
                          If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.



                          96. What is the Set interface ?

                          • The Set interface provides methods for accessing the elements of a finite mathematical set
                          • Sets do not allow duplicate elements
                          • Contains no methods other than those inherited from Collection
                          • It adds the restriction that duplicate elements are prohibited
                          • Two Set objects are equal if they contain the same elements

                          97. What are the main Implementations of the Set interface ?

                          The main implementations of the List interface are as follows:

                          • HashSet
                          • TreeSet
                          • LinkedHashSet
                          • EnumSet

                          98. What is a HashSet ?

                          • A HashSet is an unsorted, unordered Set.
                          • It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
                          • Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.

                          99. What is a TreeSet ?

                          TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.



                          100. What is an EnumSet ?

                          An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.



                          101. Difference between HashSet and TreeSet ?

                          HashSet is much faster than TreeSet but offers no ordering guarantees like TreeSet.

                          HashSet

                          • class offers constant time performance for the basic operations (add, remove, contains and size).
                          • it does not guarantee that the order of elements will remain constant over time
                          • iteration performance depends on the initial capacity and the load factor of the HashSet.
                          • It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.
                          TreeSet
                          • guarantees log(n) time cost for the basic operations (add, remove and contains)
                          • guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via it's constructor)
                          • doesn't offer any tuning parameters for iteration performance
                          • offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc

                          102. What is a Map ?

                          • A map is an object that stores associations between keys and values (key/value pairs).
                          • Given a key, you can find its value. Both keys and values are objects.
                          • The keys must be unique, but the values may be duplicated.
                          • Some maps can accept a null key and null values, others cannot.

                          103. What are the main Implementations of the Map interface ?

                          The main implementations of the List interface are as follows:

                          • HashMap
                          • HashTable
                          • TreeMap
                          • EnumMap

                          104. What is a TreeMap ?

                          TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.



                          105. How do you decide when to use HashMap and when to use TreeMap ?

                          For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative.
                          If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.



                          106. Difference between HashMap and Hashtable ?


                          107. How does a Hashtable internally maintain the key-value pairs?

                          TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

                          108. What Are the different Collection Views That Maps Provide?

                          Maps Provide Three Collection Views.

                          • Key Set - allow a map's contents to be viewed as a set of keys.
                          • Values Collection - allow a map's contents to be viewed as a set of values.
                          • Entry Set - allow a map's contents to be viewed as a set of key-value mappings.

                          109. What is a KeySet View ?

                          KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.

                          110. What is a Values Collection View ?

                          Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.

                          111. What is an EntrySet View ?

                          Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value


                          112. How do you sort an ArrayList (or any list) of user-defined objects ?

                          Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

                          113. What is the Comparable interface ?

                          The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered. The Comparable interface in the generic form is written as follows:

                          interface Comparable<T>

                          where T is the name of the type parameter.

                          All classes implementing the Comparable interface must implement the compareTo() method that has
                          the return type as an integer. The signature of thecompareTo() method is as follows:
                          int i = object1.compareTo(object2)
                          • If object1 < object2: The value of i returned will be negative.
                          • If object1 > object2: The value of i returned will be positive.
                          • If object1 = object2: The value of i returned will be zero.
                          114. What are the differences between the Comparable and Comparator interfaces ?

                          More question on Thread
                          115. Why we call start() methods instead of run() method?
                          First see one example:
                          public class MyFirstThread extends Thread {
                          public void run() {
                          System.out.println("In run method; thread name is: " +
                          Thread.currentThread().getName());
                          }
                          public static void main(String args[]) throws Exception {
                          Thread myThread = new Thread(new MyFirstThread());
                          myThread.run(); // note run() instead of start() here
                          System.out.println("In main method; thread name is : " +
                          Thread.currentThread().getName());
                          }

                          }

                          Output :
                          In run method; thread name is: mainIn main method; thread name is : main

                          The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns
                          On the other hand if you can run() directly, it simply executes as part of the calling thread.It does not execute as a thread: it doesn’t get scheduled and get called by the JVM

                          On the other hand if you can run() directly, it simply executes as part of the calling thread.It does not execute as a thread: it doesn’t get scheduled and get called by the JVM


                          116.Should you extend the Thread or implement the Runnable?
                          Since Java supports only single inheritance, if you extend from Thread, you cannot extend from any other class.
                          On the other hand, if you implement the Runnable interface, you can still extend some other class. So, many Java experts suggest that it is better to implement the Runnable interface unless there are some strong reasons to extend the Thread class.


                          117. when to use notify() and notifyAll()?
                          It's depend on the situation, for instance there would be a set of threads waiting for certain task to finish;once the task is finished, all waiting thread can continue with their business. In such case you would use notifAll() to wake up all the thread.
                          On the other hand, there would be mutually exclusive locking, only one of the thread can do useful thing after being notified. In such cases, you would use notify(). You can use notifyAll() in this case, but you would unnecessary waking threads that can't do anything.

                          118. How string concatenation works in java?
                          When you do modification to a string it always create a new string as string are immutable. 
                          For instance, 
                          String str="Java"; 
                          string str=str+"Latte"; 

                          When you modify the string str let's say with concatenation operation, String buffer will be created and new str is copied to new created string buffer. 
                          Then the string buffer is converted back to string object and it reference is made to new string. 
                          The old string "Java" i.e, str referenced made to null means it is unreferenced.


                          119. How to create User defined Exception in java?
                          Simple by extending the Exception class.

                          Skeleton of user defined exception look like :


                          public class MyException extends Exception {

                          public MyException() { super(); }
                          public MyException(String userMessage) { super(userMessage); }
                          public MyException(String userMessage, Throwable cause) { super(userMessage, cause); }
                          public MyException(Throwable cause) { super(cause); }
                          }

                          This class contain 4 constructors:


                          1. MyException() 

                          Constructs a new exception with null as its detail message.

                          2.MyException(String message) 

                          Constructs a new exception with the specified detail message.

                          3,MyException(String message, Throwable cause) 

                          Constructs a new exception with the specified detail message and cause.

                          4.MyException(Throwable cause) 

                          Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

                          How to throw :

                          throw new MyException ("my exception")

                          How to catch:

                          catch (MyException e)
                          {
                          // so something
                          }

                          120. What is CountDownLatch In java and what is the use of this?
                          Check this post.

                          121. What is Cyclic barrier and how to use?
                          Check this post


                          122. What is Semaphore ? 
                          Check this post


                          123. What is Exchanger in java? 
                          Check this post

                          124. What is Factory Pattern in java?
                          Factory design pattern is used for creating an object based on different parameters. The below example is about creating car in factory.
                          If we ask the factory Maruti, the factory produce the Maruti car, if we ask for BMW, the factory will produce BMW. Based on different parameters, the factory produce different things.
                          interface Car {  
                           public void Color();  
                           public void Engine();  
                           }  
                           class Maruti implements Car{  
                           @Override  
                           public void Color() {  
                           System.out.println("Car color is red");   
                           }  
                           @Override  
                           public void Engine() {  
                           System.out.println("800c Engine");  
                           }  
                           }  
                           class BMW implements Car{  
                           @Override  
                           public void Color() {  
                           System.out.println("Car color is red");   
                           }  
                           @Override  
                           public void Engine() {  
                           System.out.println("1200c Engine");  
                           }  
                           }  
                           public class CarFactory {  
                           public static Car createHuman(String m){  
                           Car p = null;  
                           if(m == "maruthi"){  
                           p = new Maruti();  
                           }else if(m == "bmw"){  
                           p = new BMW();  
                           }   
                           return p;  
                           }  
                           }  
                          Factory design pattern used in Java standard library

                          Based on different parameter, getInstance() returns a different instance of Calendar.
                          java.util.Calendar – getInstance()
                          java.util.Calendar – getInstance(TimeZone zone)
                          java.util.Calendar – getInstance(Locale aLocale)
                          java.util.Calendar – getInstance(TimeZone zone, Locale aLocale)

                          125. Difference between synchronization on static and non static method i.e, lock on object lock vs lock on class?
                          Lock on object means: 
                          Threads calling non-static synchronized methods in the same class will only block each other if they're invoked using the same instance. That's because they each lock on this instance, and if they're called using two different instances, they get two locks, which do not interfere with each other. 

                          Lock on class means: 
                          There is only one copy of the static data you're trying to protect, so you only need one lock per class to synchronize static methods—a lock for the whole class. There is such a lock; every class loaded in Java has a corresponding instance of java.lang.Class representing that class. It's that java.lang.Class instance whose lock is used to protect the static methods of the class (if they're synchronized). 


                          Threads calling static synchronized methods in the same class will always block each other—they all lock on the same Class instance.

                          126. Ways to create object in java?
                          1. Using new keyword
                          2. Using newInstance method of Class
                            Class clas = Class.forName("NewClass");
                            Class clas = Class.forName("NewClass");
                          3. Using clone() of java.lang.Object
                            NewClass obj = new NewClass();
                            NewClass obj2 = obj.clone();
                          4. Using Object Deserialization
                            ObjectInputStream objStream = new ObjectInputStream(inputStream );
                            NewClass obj = (NewClass ) inStream.readObject(); 
                          5. Using ClassLoader
                            getClass().getClassLoader().loadClass("NewClass").newInstance();
                          6. Using Reflection
                            constructor.newInstance() and class.newInstance()
                          7. If your class is an Enum, just name it java create it for you.
                          8. Using Factory Method also







                          If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...