ChandrasekharRao.D

Java Interview Questions

Java questions
Core java:

1.Difference between sleep() and wait()?

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().
The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.
Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
2. Oops Principles?
The four principles of OOP.
   Dimistifying Object Oriented Programming is not easy at first, but re-read this article a few times and you’ll rank up. I’m going to give you some insight into the four principles of Object Oriented Programming:
1. Encapsulation:
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition. Typically, only the object’s own methods can directly inspect or manipulate its fields.Encapsulation is the hiding of data implementation by restricting access to accessors and mutators.

An accessor is a method that is used to ask an object about itself. In OOP, these are usually in the form of properties, which have a get method, which is an accessor method. However, accessor methods are not restricted to properties and can be any public method that gives information about the state of the object.

A is public method that is used to modify the state of an object, while hiding the implementation of exactly how the data gets modified. It’s the set method that lets the caller modify the member data behind the scenes.

Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state. This type of data protection and implementation protection is called Encapsulation.

A benefit of encapsulation is that it can reduce system complexity.

2. Abstraction
Data abstraction and encapsulation are closely tied together, because a simple definition of data abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. Abstraction denotes a model, a view, or some other focused representation for an actual item.

“An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.” — G. Booch

In short, data abstraction is nothing more than the implementation of an object that contains the same essential properties and actions we can find in the original object we are representing.

3. Inheritance
Inheritance is a way to reuse code of existing objects, or to establish a subtype from an existing object, or both, depending upon programming language support. In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes called base classes, superclasses, parent classes or ancestor classes. The resulting classes are known as derived classes, subclasses or child classes. The relationships of classes through inheritance gives rise to a hierarchy.

Subclasses and Superclasses
A subclass is a modular, derivative class that inherits one or more properties from another class (called the superclass). The properties commonly include class data variables, properties, and methods or functions. The superclass establishes a common interface and foundational functionality, which specialized subclasses can inherit, modify, and supplement. The software inherited by a subclass is considered reused in the subclass.
In some cases, a subclass may customize or redefine a method inherited from the superclass. A superclass method which can be redefined in this way is called a virtual method.
4. Polymorphism
Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple methods all with the same name, but slightly different functionality.

There are 2 basic types of polymorphism.
Overridding, also called run-time polymorphism. For method overloading, the compiler determines which method will be executed, and this decision is made when the code gets compiled.
Overloading, which is referred to as compile-time polymorphism. Method will be used for method overriding is determined at runtime based on the dynamic type of an object.
3.Difference Between Abstraction and Encapsulation?
Abstraction hide the things at design level but Encapsulation hide things at  implementation level.
  • Abstraction can be defined as the process of hiding the unwanted details and exposing only the essential features of a particular object or concept, while Encapsulation is a way of wrapping up data and methods into a single unit. Encapsulation puts the data safe from the outside world by binding the data and codes into single unit.
  • Abstraction lets you focus on what the object does instead of how it does, while Encapsulation means hiding the internal details of how an object works. When you keep internal working details private, you can change it later with a better method.
  • Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected.
  • Abstraction means to show What part of functionality while Encapsulation means to hide the How part of the functionality.

4. Java Exception propagation

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.

5. throw and throws in Java

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. The flow of execution of the program stops immediately after the throw statement is executed

throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.

We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.

  • throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
  • throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
  • By the help of throws keyword we can provide information to the caller of the method about the exception.
6. Following are some ways in which you can create objects in Java:
a) Using new Keyword
b) Using New Instance : If we know the name of the class & if it has a public default constructor we can create an object –Class.forName.
c) Using clone() method: Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of the previous object into it.
d) Using deserialization : Whenever we serialize and then deserialize an object, JVM creates a separate object. In deserialization,
e)Using newInstance() method of Constructor class : This is similar to the newInstance() method of a class. There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. It can also call parameterized constructor, and private constructor by using this newInstance() method.
 Constructor<ReflectionExample> constructor
                = ReflectionExample.class.getDeclaredConstructor();
            ReflectionExample r = constructor.newInstance();
7. Fail Fast And Fail Safe Iterators in Java
Iterators in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.
Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.
8.How Fail Fast Iterator works ?
To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified.Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException.


Collections in Java



A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are two main root interfaces of Java collection classes.


collectionjava


Iterators in Java

Iterators are used in Collection framework in Java to retrieve elements one by one. There are three iterators.
Enumeration :
It is a interface used to get elements of legacy collections(Vector, Hashtable). Enumeration is the first iterator present from JDK 1.0, rests are included in JDK 1.2 with more functionality. Enumerations are also used to specify the input streams to a SequenceInputStream. We can create Enumeration object by calling elements() method of vector class on any vector object
  • Enumeration is for legacy classes(Vector, Hashtable) only. Hence it is not a universal iterator.
  • Remove operations can’t be performed using Enumeration.
  • Only forward direction iterating is possible.
Iterator:
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is improved version of Enumeration with additional functionality of remove-ability of a element.
  • Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework.
  • Iterator object can be created by calling iterator() method present in Collection interface.
ListIterator:
It is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides bi-directional iteration.
  • ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator.
Vector vs ArrayList in Java:
ArrayList and Vectors both implements List interface and both use array(dynamically resizeable) as data structure internally very much like using an ordinary array .
Major Differences between ArrayList and Vector:
  1. Synchronization : Vector is synchronized that means at a time only one thread can access the code while arrayList is not synchronized that means multiple threads can work on arrayList at same time. For example, if one thread is performing add operation, then there can be another thread performing remove operation in multithreading environment.
    If multiple threads access arrayList concurrently then we must synchronize the block of the code which modifies the list either structurally or simple modifies element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
  2. Performance: ArrayList is faster as it is non-synchronized while vector operations give slow performance as they are synchronized(thread-safe). If one thread works on vector has acquired lock on it which makes other thread will has to wait till lock is released.
  3. Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage. But the way they resized is different. ArrayList increments 50% of current array size if number of elements exceeds its capacity while vector increments 100% means doubles the current array size.
  4.  Traversal: Vector can use both Enumeration and Iterator for traversing over elements of vector while ArrayList can only use Iterator for traversing.

ArrayList vs LinkedList in Java

ArrayList:-Implemented  with the concept of dynamic array.
LinkedList:-Implemented with the concept of doubly linked list.
Comparision between ArrayList and LinkedList:-
  1. Insertions are easy and fast in LinkedList as compared to ArrayList because there is no
    risk of resizing array and copying content to new array if array gets full which makes
    adding into ArrayList of O(n) in worst case, while adding is O(1) operation in LinkedList
    in Java. ArrayList also needs to be update its index if you insert something anywhere except
    at the end of array.
  2. Removal also better in LinkedList than ArrayList due to same reasons as insertion.
  3. LinkedList has more memory overhead than ArrayList because in ArrayList each index only
    holds actual object (data) but in case of LinkedList each node holds both data and address
    of next and previous node.
  4. Both LinkedList and ArrayList require O(n) time to find if an element is present or not. However we can do Binary Search on ArrayList if it is sorted and therefore can search in O(Log n) time.

Project Related


What is agile?
The main goal of agile methods is minimizing the risk by developing software in short timeboxes, called iterations, which typically last one to four weeks.
Agile is a project management philosophy or orientation, where Scrum is a specific methodology of how someone manages a project.
https://www.quora.com/What-is-Agile-and-Scrum-model
http://syndicode.co/2017/10/05/top-6-software-development-methodologies/
Waterfall (a.k.a. Traditional)
One of the most popular classic methodology, along with new-age Agile. Just like a natural waterfall flowing steadily downwards, waterfall model is ‘cascading’ & ‘sequential’, rigid and linear.
  • Phase-by-phase approach (sequential) wherein next phase starts only when previous phase activities have been completed. For E.g. coding starts only after all the requirements are final, testing commence only after all the coding for all the requirements has been completed.
  • A schedule is typically set with deadlines for each stage
  • Emphasis is on planning, time schedules, target dates, budgets and implementation of an entire system at one time.
  • Since it’s a linear model, it allows for departmentalization and managerial control.
  • Tight control is maintained via extensive written documentation, formal reviews, and approval/sign-off at the end of most phases before beginning the next phase.
  • Preferable for a small project where there are no uncertain requirements.
The major drawback – what if the requirement changes in the middle? Yeah! It does not embrace the inevitable changes and revisions.
Fun fact: Sometimes taught with the mnemonic “A Dance IThe Dark Every Monday”, representing Analysis, Design, Implementation, Testing, Documentation and Execution, and Maintenance.


6 Benefits of Programming with Immutable Objects in Java

Immutability is often presented as a key concept of functional programming. Most functional programming languages like Haskell, OCaml and Scala follow a immutable-by-default approach for variables in their programs. In fact to write code which uses mutation programmers have to go out of the way and do something special - like using monads in Haskell and mutable references in OCaml and Scala. It is of course also possible to create and use immutable objects in other programming languages. In order to get the benefits of immutability in Java we can use the following guidelines while programming -
  • Mark the class final
  • Mark all the fields private and final
  • Force all the callers to construct an object of the class directly, i.e. do not use anysetter methods
  • Do not change the state of the objects in any methods of the class
Doing so will often restrict the way you can call the class and its methods. It will also make you redesign your software and rethink your algorithms. However, there are many benefits of programming with immutable objects.
  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. The internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.
As a good programming practice in Java one should try to use immutable objects as far as possible. Immutability can have a performance cost, since when an object cannot be mutated we need to copy it if we want to write to it. When you care a lot about performance (e.g. programming a game) it may be necessary to use a mutable object. Even then it is often better to try to limit the mutability of objects. This recommendation can be summarized in the following adage by Joshua Bloch (taken from the book Effective Java) -


Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible.