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!...

                          3 comments:

                          1. Really Appreciate the thought to share such knowledge.Feel good to share link,which I recently found on web to practice java interview questions @ http://skillgun.com/java/interview-questions-and-answers

                            ReplyDelete