Core Java Interview Questions

 

Java Class Loaders

  • Class Loaders are hierarchical and use delegation model when loading the class.
  • Class loaders request their parent to load the class first before attempting to load it themselves.
  • When class loader loads the class, child class loader in the hierarchy will never reload the class again.
  • Classes are into the JVM as they are referenced by name in a class that is already running in th JVM.
  • The very first class is loaded by the help of static main method declared in your class.
  • All the subsequently loaded classes are loaded by the classes which are already loaded & running.
  • Class loader creates the name space.
  • All JVMS include one class loader embedded within JVM called primordial bootstrap class loader.
  • Non-primordial class loaders has hooks in JVM to allow user defined class loaders to be used in place of the primordial class loaders
  • Bootstrap (primordial) - loades JDK internal classes
  • Extensions - loads jar files from jdk extensions
  • System - loads classes from the system classpath
  • Classes loaded by parent class loader have no visibility into the classes loaded by its desendents.
  • Classes loaded by desendent class loader have visibility into the classes loaded by its parents.
  • if there are siblings class loaders they can not see classes loaded by each other, they can only see the class loaded by their parent class loader.
  • Two objects loaded by different class loaders are never equal even if they carry the same values.
  • Which means a class is uniquely identified in the context of the associated class loader.
  • This applies to singeltons where each class loader will have its own singelton

Static vs Dynamic Class Loading

  • Classes are Statically loaded with java new operator   Car c = new Car();
  • Dynamic class loading is done programitacally invoking the functions of class loaded at run time.
  • Class.forName(String class name)
  • class.newInstance()
    • Jeep myJeep = null
    • String myClassName = "au.com.Jeep"
    • Class vehicleClass = Class.forName(myClassName);
    • myJeep = (Jeep) vehicleClass,newInstance();
    • myJeep.setFuel(50)

Object Oriented Programming

  • Encapsulation
  • Polymorphiosm:Ability of single variable to be used to reference objects of different types
  • Inheritance
  • Represent real life objects like Car, Account , Customer
  • Reuse of previous work using implementation inheritance and object composition
  • Objects map to real world objects with encapsulations
  • Modular Architecture: Objects , Systems, Frameworks are building block of a larger systems
  • The increased quality and reduced development timeare by products of the OO design
  • if 90% of the new application consist of proven exisiting components then only 10% code need testing

 

Difference b/w Aggregation and Composition 

  • Aggregation is an association in which one class belongs to a collection.
  • Part (product) can exist without a Whole(line-item).
  • if line-item(whole) is deleted  then product(part) need not be deleted.
  • Aggregation has a weaker relationship.
  • Composition is an association in which one class belongs to a collection.
  • Part (line-items) can NOT exist without a Whole(Order).
  • if an order is deleted then all corresponding line items for that order should be deleted.
  • Composition has a stronger relationship.

Code Re-use via Object Composition over Inheritance

  • Class inheritcance is that is done statically at compile time can not be changed at run time.
  • Sub classes become dependent on the parent classe implementation hard to reuse the subclass.
  • A change to a super class ripple down inheritance hierarchy to sub classes by tight coupling to super class
  • Object composition functionality acquired at run time and implementation can be replaced runtime
  • Because objects are accessed only thru their interfaces so one object can be replaced with another
  • As long as they have the same type

What is Overriding Method?

  • Method using the same name, return type, and arguments as a method in its superclass,
  • The method in the class overrides the method in the superclass.
  • When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass.
  • Methods may be overridden to be more public, not more private.

Types of references in Java

  • Garbage collector will not remove a strong reference.
  • Soft reference will only get removed if memory is low implenet cache avoiding memory leaks.
  • weak reference will get removed on the next garbage collection, weakhashmap by weak references.
  • Phantom references will be finalized but the memory will not be reclaimed. notified that an object is about to be collected.

What are non-final methods in java object class

  • equals, hashcode, toString, clone, finalize

What are final methods in java object class

  • wait, notify, notifyall, getClass

 

What is difference between  HttpServlet and GenericServlet

  • GenericServlet has service() method to handle request.
  • GenericServlet  protocol independent is for servlets that might not use HTTP for example FTP
  • HttpServlet entends GenericServlet. adds support for Http protocol based methods like doget, dopost
  • all request are handled through service method, which dispatches the request to doget or dopost.
  • HttpServlet is protocol dependent

 

How you prevent multiple submit due refresh button submits

  • Synchronizer tokeb pattern is to set a use once only token in a session
  • token is stored in the form as hidden field
  • when submit the form, the token in request is compared with the token in the session.
  • if token match then reset the token in the session to null or different value n proceed with update
  • if resubmit then token in request will not match the token in session, since the token was reset in the first submit so proceed fails.

How Connect thru JDBC.

  • Load the driver class.forName("oracle.jdbc.driver.oracledriver");
  • open connection to databse Connection con = DriverManager.getConnection("xxxxxx");
  • create statement object Statement stmt = con.createStatement();
  • create resultset Resultset rs = stmt.executeQuery("select * from employee");
  • use resultset object to read data while(rs.next()) { rs.getString("firstName"));

What are your strengths, weakness

  • taking initiatives and being pro-active
  • design skills
  • problem solving skills
  • communicatin skills
  • ability to work in team environment
  • i am being attentin to detail guy but some times miss small detail. so i am working on applying the 80-20 prnciple to manage time n details, spend 80% of my effort n time on 20% task

 What is the difference between Optimistic and Pessimistic concurrency

  • A pessimistic design assumes conflicts will occur in the database tables and avoids them through exclusive locks
  • Optimistc design assumes conflicts wont occur and deal with them when thay occur.

 

JMS acknowledgement modes

  • AUTO-ACKNOLEDGEMENT
  • DUP-OK-ACKNOWLEDGEMENT
  • CLIENT ACKNOWLEDGEMENT

Web Security from external Attacks

  • cross site scripting, sql injection, hidden field manipulation, cookie poisoning
  • Use Http post as oppoed to Http get
  • Strip any un wanted special characters and tags
  • perform input data validation
  • perform server side validation
  • have a centralised code for input validation
  • Handle your exceptions without revealing any info about datasources n table names
  • Protect web resources like jsp , html files, pdf behind WEB-INF
  • Avoid using hidden fields, cookies to store sesitive state information
  • prefer prepared statement to prevent sql injectin attacks

 

How to Design Java Web Application

  • Before codeing get bussiness requirement down.
  • build a complete list of rquired features
  • sample screen shots , use case diagrams, bussiness rules as functional document
  • prepare a technical document based oon functional specification
  • UML diagrams to show design , class diagrm, sequence diagram
  • Design should be specific to a problem
  • Design also should be general enough to address future reuirements.
  • Decomposing the business use cases into relevant objects.
  • Converting Objects into classes.
  • Create a Tiered architecture: client tier, bussiness tier, and data tier.
  • Use MVC architecture for the J2EE applications
  • Create a DATA Model which is a detailed spec of data structures focuses on data.
    • ​​Conceptual Data Model: explore domain concepts with project stake holders.
    • Logical Data Model: explore domian concepts and their relationships.
    • Physical Data Model: design the internal schema of a database, realtions b/w tables.
    • Data Models are created by performing following tasks.
      • ​Identify entity  types, attributes and relationships.
      • Apply naming conventions for tables 
      • Assign keys surrogate keys
      • Normalize to reduce data redundancy and denormalize to improve performance.
  • ​​Create Design Model: detail spec of the objects & relationships b/w the objects as well as behaviour.
    • ​Class Diagram: contains the view of the entities & relatrionships in the design model.
    • Contains core bussiness classes and non-core bussiness classes
    • Use case are described in sequence and collabration diagrams
  • Create CLASS Model defines both data & behaviour.
    • Granularity of objects fine grained vs coarse grained
    • should we use metod level or code level thread synchronization
    • should we use page level access security or fine grained programatic security
    • Coupling b/w objects: lose coupled vs tightly coupled
    • Network overheads: 
    • define class interfaces: use abstract class vs interface
    • should we use interface inheritance with object composition or class inheritance
  • Apply Polymorphism and Encapsulations.
  • Applying well known design patterns.
  • Scalability of the system:
    • Vertical scalling: multiple servers in single machine basedd on cpu usage & JVM heap memory
    • Horizontal scalling increasing the number of machines in the cluster (reliable)
  • how we replicat session state using http sessions
  • Internationalizations: multi language support
  • System is configuarable thru property files, xml files and annotations
  • Design considerations during design , development, and deployment phases
    • ​Performance issues
    • Concurrency issues
    • Tansactional issues
    • Security issues: sql injections, url injections
    • Memory Issues: memory leaks, JVM heap size , perm space for 3rd party libraries
    • Sacalability issues: vertical vs horizontal if load increases
    • Portability Issues: can i port this applicatin  to a different server 3 years from today
    • Dynamic Redeployment: deploymant while site is running for missin critical apps
    • Resource Pooling
    • Lodging and auditing
    • Maintainable, Reusability, Extensibility: design patterns
    • Design Concepts, Design Patterns, Design Language like UML
    • Apply OO concepts like Inheritance, Polymorphism, & Encapsulation
    • Program to Interfaces and not to Implementations
    • Use of relevant design patterns
    • Use of Java Collections and Java Exceptions correctly
    • Stay away from hard coding values

How improve  performance of Java Application

  • Application Level
    • ​Applicatin design
    • Applicatin server tuning
    • Applicatin coding
    • Drivers
    • Database Partitioning
    • Pool valuable system resources like threads, connections
    • control memory leaks: remove  short lived objects from long lived objects.
    • new code consider performance, maintability, extendibility, ease of use, scalibility.
    • apply multi threading where applicable
    • Managing objects efficiently by caching or recycling them without rely on Garbage collection.
  • ​JAVA Infrastructure Level
    • ​JVM Selection
    • JVM Tuning
  • ​System Level
    • Application server configuration for optimum performance
    • ​Network I/O disk I/O
    • Operatin System
    • Optimize I/O operations: use buffering
    • Minimize network overheads
    • System configuration topology
    • Hardware( CPU, memory, I/O 

 

What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

 

What are wrapper classes?

  • Java provides specialized classes corresponding to each of the primitive data types.
  • These are called wrapper classes. They are e.g. Integer, Character, Double etc.

Why do we need wrapper classes?

  • It is sometimes easier to deal with primitives as objects.

  • Moreover most of the collection classes store objects and not primitive data types.

  • And also the wrapper classes provide many utility methods also.

  • Because of these resons we need wrapper classes.

  • And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection.

  • Also we can pass them around as method parameters where a method expects an object.

 

Why String, Integer and other wrapper classes are considered good keys ?

  • String, Integer and other wrapper classes are natural candidates of HashMap key.
  • String is most frequently used key as well because String is immutable and final.
  • String overrides equals and hashcode() method.
  • Other wrapper class also shares similar property. Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap.
  • Immutability is best as it offers other advantages as well like thread-safety,
  • If you can  keep your hashCode same by only making certain fields final, then you go for that as well.
  • Since equals() and hashCode() method is used during reterival of value object from HashMap,
  • its important that key object correctly override these methods and follow contact.
  • If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.

What is the purpose of garbage collection in Java, and when is it used?

  • purpose of garbage collection is to identify discard objects that are no longer needed by a program
  • so that their resources can be reclaimed and reused.
  • Java object is subject to garbage GC when becomes unreachable to program in which it is used.

 

State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

public : Public class is visible in other packages, field is visible everywhere (class must be public too)

private : Private variables or methods may be used only by an instance of the same class that

declares the variable or method, A private feature may only be accessed by the class that owns the

feature.

protected : Is available to all classes in the same package and also available to all subclasses of the

class that owns the protected feature.This access is provided even to subclasses that reside in a

different package from the class that owns the protected feature.

default :What you get by default ie, without any access modifier (ie, public private or protected).It

means that it is visible to all within a particular package.

 

What are pass by reference and passby value?

  • Pass By Reference means the passing the address itself rather than passing the value.
  • Pass by Value means passing a copy of the value to be passed.

 

Q: How are Observer and Observable used?

A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is

updated it invokes the update() method of each of its observers to notify the observers that it has

changed state. The Observer interface is implemented by objects that observe Observable objects.

 

Describe what happens when an object is created in Java

  • Several things happen in a particular order to ensure the object is constructed properly:
  • Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses.
  • Implemenation-specific data includes pointers to class and method data.
  • The instance variables of the objects are initialized to their default values.
  • The constructor for the most derived class is invoked.
  • The first thing a constructor does is call the consctructor for its superclasses.
  • This process continues until the constrcutor for java.lang.Object is called,
  • as java.lang.Object is the base class for all objects in java.
  • Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed.
  • Then the body of the constructor is executed.
  • constructor for base class completes first and constructor for the most derived class completes last.

 

Question: Can you override a private or static method in Java?

  • you can not override a private or static method in Java,
  • if you create a similar method with same return type and same method arguments in child class
  • then it will hide the superclass method, this is known as method hiding.
  • Similarly, you cannot override a private method in sub class because it's not accessible there,
  • what you do is create another private method with the same name in the child class. 

 

Difference between String, StringBuffer and StringBuilder in Java?

  • String is immutable while both StringBuffer and StringBuilder is mutable,
  • which means any change e.g. converting String to upper case or trimming white space,
  • will produce another instance rather than changing the same instance.
  • StringBuffer is synchronized while StringBuilder is not.

 

 

-------------------------------------------------------------------------------------------------------------------------

 

inner:

What are different types of inner classes?

  • Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes

  • If you declare a class within a class and specify the static modifier,
  • the compiler treats the class just like any other top-level class.
  • Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner.
  • Top-level inner classes implicitly have access only to static variables.
  • There can also be inner interfaces. All of these are of the nested top-level variety

Member classes

  • Member inner classes are just like other member methods and
  • member variables and access to the member class is restricted, just like methods and variables.
  • This means a public member class acts similarly to a nested top-level class.
  • The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class

Local classes

  • Local classes are like local variables, specific to a block of code.
  • Their visibility is only within the block of their declaration.
  • In order for the class to be useful beyond the declaration block,
  • it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes -

  • Anonymous inner classes extend local inner classes one level further.
  • Asanonymous classes have no name, you cannot provide a constructor.

 

Singelton:

 

Singelton Pattern , how to code Singelton Pattern?

public class Singleton {
    private static Singleton instance = new Singleton();
 
    private Singleton() {    }
 
    public static synchronized Singleton getInstance() {
        return instance;
    }
 
    public void doSomething() {
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
        }
    }
 
    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }
}


There are some rules that need to be followed when we want to implement a singleton.

 

  • From the example code above you can see that a singleton has a static variable to keep it sole instance
  • You need to set the class constructor into private access modifier. By this you will not allowed any other class to create an instance of this singleton because they have no access to the constructor.
  • Because no other class can instantiate this singleton how can we use it? the answer is the singleton should provide a service to it users by providing some method that returns the instance, for example getInstance().
  • When we use our singleton in a multi threaded application we need to make sure that instance creation process not resulting more that one instance, so we add a synchronized keywords to protect more than one thread access this method at the same time.
  • It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.


And this is how we use the Service singleton class.
 
public class SingletonDemo {


    public static void main(String[] args) throws Exception {
        // Gets an instance of Service object and calls the doSomething method.  //
        Singleton service = Singleton.getInstance();
        service.doSomething();
    }


}

 

 

personality:

  • Understanding of the bussiness
  • Ability to communicate interact effectively with the customers.
  • Ability to look at things from the users prospective as apposed to only from tecnology prospective
  • Ability to persuade customers with the alternative solutions which can have win for customer and tech
  • Ability to effectibely communicate with your team and senior management
  • Ability to work in a team as well as independently problem solving & organizational skills
  • Ability to cope with difficult situtaions like stress due to work load, dead lines, deal difficult people
  • Ability to being a good listner with the right attitude

 

What are your Strengths

  • Taking initiatives and being pro-activce to fix a transactinal, performance & memory leak issue.
  • Design skills - designed applications using OO concepts
  • Problem Solving Skills - Break a complex problem into managble sub sections
  • and then applying brainstorming and analytical skills to solve the complex problem.
  • Communication skills - can communicate effectively with all the team members , users..etc
  • Ability to work in team environment as well as independently -
  • technically sound to work independently as well as have the skills to fit into any team environment.

Weaknesses:

  • I am being an attention to detail guy but some times miss small details.  applying 80/20  principle to manage time and details spending 80% of my effort and time on 20% of tasks which are critical.
  • Some times when there is a technical issuei tend to work continously until i fix it having a break. thinking outside the square will assist you in finding the root cause of the problem.

Accomkplishments:

  • Re-designed the data packager application to make it more scalable, maintainable and extendable
  • identified and fixed memory leaks and improved performance by 20%
  • further improved performance by introducing multi threading and other performance tuning.
  • identified and fixed transactional issues for the project which is web based e-comm project
  • Pro-active developer understanding of multi-threrading, transactional, performance & memory issues.
  • Designed Transactional and multi-threaded systems
  • Mentored junior developers

 

Interface:

What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

Can we define private and protected modifiers for variables in interfaces?    No

What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

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

Can a abstract class be declared final?
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

What is use of a abstract variable?
Variables can't be declared as abstract. only classes and methods can be declared as abstract.

Can you create an object of an abstract class?
Not possible. Abstract classes can't be instantiated.

Can a abstract class be defined without any abstract methods?
Yes it's possible. This is basically to avoid instance creation of the class.

Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

Can a method inside a Interface be declared as final?
No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

Can an Interface implement another Interface?
Intefaces doesn't provide implementation hence a interface cannot implement another interface.

Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

Can a Class extend more than one Class?
Not possible. A Class can extend only one class but can implement any number of Interfaces.

Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?
Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

Can an Interface be final?     Not possible. Doing so so will result in compilation error.

Can a class be defined inside an Interface?      Yes it's possible.

Can an Interface be defined inside a class?   Yes it's possible.

Q: What is the difference between an Interface and an Abstract class?

  • An abstract class can have instance methods that implement a default behavior.
  • An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
  • An interface has all public members and no implementation.
  • An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

 

What does it mean that a method or class is abstract?
An abstract class cannot be instantiated. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or it also should be declared abstract.

What is an abstract class?

  • Abstract class must be extended/subclassed (to be useful). It serves as a template.
  • A class that is abstract may not be instantiated (ie, you may not call its constructor),
  • abstract class may contain static data.
  • Any class with an abstract method is automatically abstract itself,
  • and must be declared as such.
  • A class may be declared abstract even if it has no abstract methods.
  • This prevents it from beinginstantiated.

What are abstract classes, abstract methods?

  • class or a method qualified with "abstract" keyword is an abstract class or abstract method.
  • abstract class when you want to manipulate a set of classes through a common interface.
  • All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism.
  • An abstract method is an incomplete method.
  • It has only a declaration and no method body.
  • Here is the syntax for an abstract method declaration: abstract void f();

What are interfaces?

  • Interfaces provide more sophisticated ways to organize and control the objects in your system.
  • The interface keyword takes the abstract concept one step further.
  • You could think of it as a “pure” abstract class.
  • It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies.
  • An interface can also contain fields,interface keyword takes the abstract concept one step further.
  • You could think of it as a “pure” abstract class.
  • It allows to establish the method names, argument lists, and return types, but no method bodies.
  • An interface can also contain fields, but An interface says:
  • Thus,any code that uses a particular interface knows what methods might be called for that interface.
  • So the interface is used to establish a “protocol” between classes.
  • When only deal with a type and does not care about the actual implementation use interfaces.
  • If you need to change your design frequently you should prefer using interfaces to abstract,
  • Coding to an interfaces reduces coupling and
  • interfaces inheritance can achieve code reuse with the help of object composition
  • Strategy design pattern swap algorithems into your porogram w/o altering the objects that use them.

 

How can you achieve Multiple Inheritance in Java?

Java's interface mechanism can be used to implement multiple inheritance, with one important difference

from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose

between different implementations, as with interfaces there are no implementations.

 

 

thread:

 

What is daemon thread and which method is used to create the daemon thread?

A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

 

High Level Thread States

  • Runnable, Running, Waiting , Sleeping, Block on IO, dead

Identify potential thread safety issues

  • Multiple thread work in parallel
  • Threads share the same address space means they can read write same variables
  • Care should be taken to avoid one thread disturb the work of another thread

 

Describe synchronization in respect to multithreading.

  • With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
  • Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable.
  • This usually leads to significant errors.

Q: What is the difference between preemptive scheduling and time slicing?

  • Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.
  • Under time slicing, task executes for predefined slice of time then reenters the pool of ready tasks.
  • The scheduler then determines which task should execute next, based on priority and other factors

 

Explain different way of using thread?

  • The thread could be implemented by using runnable interface or by inheriting from the Thread class.
  • The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
  • You can very well throw super class of RuntimeException in overridden method
  • But you can not do same if its checked Exception. 

What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q: What is synchronization and why is it important?

A: With respect to multithreading, synchronization is the capability to control

the access of multiple threads to shared resources. Without synchronization, it is possible for one

thread to modify a shared object while another thread is in the process of using or updating that

object's value. This often leads to significant errors.

 

Q: What are synchronized methods and synchronized statements?

A: Synchronized methods are methods that are used to control access to an object. A thread only

executes a synchronized method after it has acquired the lock for the method's object or class.

Synchronized statements are similar to synchronized methods. A synchronized statement can only be

executed after a thread has acquired the lock for the object or class referenced in the synchronized

statement.

 

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.

Livelock

  • A thread often acts in response to the action of another thread. If the other thread's action
  • is also a response to the action of another thread, then livelock may result. 
  • As with deadlock, livelocked threads are unable to make further progress.However,
  • the threads are not blocked — they are simply too busy responding to each other to resume work. 
  • Livelock is a case of multiple threads reacting to conditions, or events, generated by themselves. 
  • An event occurs in one thread and has to be processed by another thread. 
  • During this processing, a new event occurs which has to be processed in the first thread, 
  • and so on. Such threads are alive and not blocked, but still, do not make any progress because 
  • they overwhelm each other with useless work.Starvation is a case of a thread unable to 
  • acquire resource because other thread (or threads) occupy it for too long or have higher priority. 
  • A thread cannot make progress and thus is unable to fulfill useful work.
  • A livelock is a situation in which two or more threads block each otherby responding to an action
  • that is caused by another thread. In contrast to a deadlock situation, where two or more threads
  • wait in one specific state, the threads that participate in a livelock change their state in a way
  • that prevents progress on their regular work. An example would be a situation in which two threads
  • try to acquire two locks, but release a lock they have acquired when they cannot acquire the
  • second lock. It may now happen that both threads concurrently try to acquire the first thread. 
  • As only one thread succeeds, the second thread may succeed in acquiring the second lock. 
  • Now both threads hold two different locks, but as both want to have both locks, they release
  • their lock and try again from the beginning. This situation may now happen again and again.


Deadlock

  • Deadlock is a condition within a group of threads that cannot make progress because
  • every thread in the group has to acquire some resource that is already acquired by another thread
  • in the group. The most simple case is when two threads need to lock both of two resources
  • to progress, the first resource is already locked by one thread, and the second by another. 
  • These threads will never acquire a lock to both resources and thus will never progress.

 

What do we understand by a deadlock?

  • A deadlock is a situation in which two (or more) threads are each waiting on the other thread
  • to free a resource that it has locked, while the thread itself has locked a resource the other thread is waiting on:
  • Thread 1: locks resource A, waits for resource B
  • Thread 2: locks resource B, waits for resource A

How to avoid deadlock in Java Threads

  • when two or more threads waiting for each other to release lock and get stuck for infinite time ,
  • Above situation is called deadlock .
  • it will only happen in case of multitasking.
How do you ensure that N thread can access N resources without deadlock


How do you detect deadlock in Java ?

  • first I would look the code if I see nested synchronized block or calling one synchronized method
  • from other or trying to get lock on different object then there is good chance of deadlock
  • other way is to find it when you actually get locked while running the application ,
  • try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of
  • all the thread in application log file and you can see which thread is locked on which object.
  • use jconsole , jconsole will showyou exactly which threads are get locked and on which object.
  • Real reason for deadlock is not multiple threads but the way they access lock ,
  • if you provide an ordered access then problem will be resolved.
  • No deadlock because both method is accessing lock on Integer and String object in same order.
  • so if thread A acquires lock on Integer object ,
  • thread B will not proceed until thread A releases Integer lock ,
  • same way thread A will not be blocked even if thread B holds String lock
  • because now thread B will not expect thread A to release Integer lock to proceed further.

 

What should be Strategy for Defining Immutable Objects ?

  • The following rules define a simple strategy for creating immutable objects. 
  • Don't provide "setter" methods — methods that modify fields or objects referred to by fields
  • Make all fields final and private.
  • Don't allow subclasses to override methods.
  • The simplest way to do this is to declare the class as final.
  • make the constructor private and construct instances in factory methods.
  • 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.

 

What is the difference between the Runnable and Callable interfaces?

  • The Runnable interface has a single run method.
  • It represents a unit of computation that has to be run in a separate thread. 
  • Runnable interface does not allow this method to return value or to throw unchecked exceptions.
  • The Callable interface has a single call method and represents a task that has a value. 
  • That’s why the call method returns a value. It can also throw exceptions. 
  • Callable is generally used in ExecutorService instances to start an asynchronous task 
  • and then call the returned Future instance to get its value.

 

What is the difference between start and run method in Java Thread?

  • This thread interview question is also ask as if start() method eventually call run() method
  • start method creates a new thread and call the code written inside the run method on a new
  • thread while calling run method executes that code on the same thread. 

 

How do you share data between two threads in Java?

  • You can share data between thread by using shared object or shared data structures
  • like Queue.Depending upon, what you are using, you need to provide the thread-safetyguarantee, 
  • and one way of providing thread-safety is using synchronized keyword.
  • If you use concurrent collection classes from Java 5 e.g.
  • BlockingQueue,you can easily share data without being bothered about thread safety
  • and inter-thread communication. 

 

What is volatile keyword in Java

  • When we use volatile keyword with a variable,
  • all the threads read it’s value directly from the memory and don’t cache it. 
  • This makes sure that the value read is the same as in the memory.

 

What is ThreadLocal?

  • Java ThreadLocal is used to create thread-local variables. 
  • We know that all threads of an Object share it’s variables, 
  • so if the variable is not thread safe, we can use synchronization 
  • but if we want to avoid synchronization, we can use ThreadLocal variables.
  • Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods
  • to get the default value or change it’s value local to Thread. 
  • ThreadLocal instances are private static fields in classes that wish to associate state with a thread. 

 

What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?

  • java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue
  • to become non-empty when retrieving and removing an element, and wait for space to
  • become available in the queue when adding an element.BlockingQueue doesn’t accept null values
  • and throw NullPointerException if you try to store null value in the queue.
  • BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature
  • and use internal locks or other forms of concurrency control.
  • BlockingQueue interface is part of java collections framework and it’s primarily
  • used for implementing producer consumer problem.

 

What do we understand by the term race condition?

  • A race condition describes constellations in which the outcome of some multi-threaded
  • implementation depends on the exact timing behavior of the participating threads.
  • 'In most cases it is not desirable to have such a kind of behavior, hence the term race condition
  • also means that a bug due to missing thread synchronization leads to the differing outcome. 
  • A simple example for a race condition is the incrementation of an integer variable by two
  • concurrent threads. As the operation consists of more than one single and atomic operation,
  • it may happen that both threads read and increment the same value.
  • After this concurrent incrementation the amount of the integer variable
  • is not increased by two but only by one.

 

Which rules do you have to follow in order to implement an immutable class?

  • All fields should be final and private.
  • There should be not setter methods.
  • class should be declared final to prevent subclasses to violate the principle of immutability.
  • If fields are not of a primitive type but a reference to another object:
  • There should not be a getter method that exposes the reference directly to the caller.
  • Don’t change the referenced objects (changing references is not visible to clients of the object).

 

exception:

What are Checked and UnChecked Exception?

  • A checked exception is some subclass of Exception
  • Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
  • Unchecked exceptions are RuntimeException and any of its subclasses.
  • Class Error and its subclasses also are unchecked.
  • With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause.
  • In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method·
  • Checked exceptions must be caught at compile time Runtime exceptions do not need to be.
  • Errors often cannot be.

What are Checked and UnChecked Exception?

  • A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
  • Making exception checked forces programmers to deal with possibility that exception will be thrown.
  • Example: IOException thrown by java.io.FileInputStream's read() method·
  • Unchecked exceptions are RuntimeException and any of its subclasses.
  • Class Error and its subclasses also are unchecked. With an unchecked exception,
  • however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause.
  • In fact, client programmers may not even know that the exception could be thrown.
  • Example: StringIndexOutOfBoundsException thrown by String's charAt() method·
  • Checked exceptions must be caught at compile time.
  • Runtime exceptions do not need to be. Errors often cannot be.

 

  • hashCode() is a method that we override in our custom classes and its mandatory to override if the "equals" method is overridden.
  • Hashcode is also used in hashing based collection classes such as Hashtable, HashMap, HashSet.
  • Understanding hashCode is very simple.
  • Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.
  • In java you see "static variables", "static methods", "static classes" and "static blocks". Static variables, static methods and static classes are known to everyone but what is this "static block". Lets see what, where and how these static blocks are used.
  • But before going into "static block", lets refresh what other static stuff are. Now "static variables" are class variables i.e., there will be only one copy for each class and not one copy for each object of the class and these variables will be accessed without instantiating the class. Then what are static methods. Again they are class methods i.e., they can be accessed without creating an instance of the class and like static variables, static methods will be accessed without instantiating the class. Note that static methods cannot access instance variables.
  • They can access only static variables. Next what are static classes.
  • You cannot declare a top-level class as a static class.
  • Java will throw a compilation error.
  • Only inner classes that are member classes can be declared as static.
  • If declare member classes as static,we use as a top-level class outside the context of top-level class.
  • One catch here is "The static keyword does not do to a class declaration what it does to a variable or a method declaration." -
  • what it means is say for example you have a static variable, then to access that static variable you will use the notation
  • <<Class Name>>.<<Variable Name>>

 

  • but when you want to use the static inner class, you need to instantiate like
  • <<Top-level class name>>.<<Inner static class name>> newClass = new <<Top-level class name>>.<<Inner static class name>>();
  • Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
  • static {
    
    
    
    •  // whatever code is needed for initialization goes here
      
      
      
    • }
      
      
      
  • A class can have any number of static initialization blocks,
  • they can appear anywhere in the class body.
  • The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
  • And dont forget, this code will be executed when JVM loads the class.
  • JVM combines all these blocks into one single static block and then executes.

What are checked exceptions?

  • Checked exception are those which the Java compiler forces you to catch.
  • e.g. IOException are checked Exceptions. 

What are runtime exceptions?

  • Runtime exceptions are those exceptions that are thrown at runtime
  • Because of either wrong input data or because of wrong business logic etc.
  • These are not checked by the compiler at compile time. 

What is the difference between error and an exception?

  • An error is an irrecoverable condition occurring at runtime.
  • Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.
  • While exceptions are conditions that occur because of bad input
  • etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.
  • Or a NullPointerException will take place if you try using a null reference.
  • In most of the cases it is possible to recover from an exception
  • (probably by giving user a feedback for entering proper values etc.). 

How to create custom exceptions?

  • Your class should extend class Exception, or some more specific type thereof. 

If I want an object of my class to be thrown as an exception object, what should I do?

  • The class should extend from Exception class.
  • Or you can extend your class from some more precise exception type also.

If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

  • One can not do anytihng in this scenarion.
  • Because Java does not allow multiple inheritance
  • and does not provide any exception interface as well.

How does an exception permeate through the code?

  • An unhandled exception moves up the method stack in search of a matching
  • When an exception is thrown from a code which is wrapped in a try block
  • followed by one or more catch blocks, a search is made for matching catch block.
  • If a matching type is found then that block will be invoked.
  • If a matching type is not found then the exception moves up the method stack
  • And reaches the caller method.
  • Same procedure is repeated if the caller method is included in a try catch block.
  • This process continues until a catch block handling the appropriate type of exception is found.
  • If it does not find such a block then finally the program terminates. 

What are the different ways to handle exceptions?

There are two ways to handle exceptions,

  • 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
  • 2. List the desired exceptions in the throws clause of the method the caller of the method hadle those exceptions. 

What is the basic difference between the 2 approaches to exception handling.

  • try catch block and
  • specifying the candidate exceptions in the throws clause?

When should you use which approach?

  • In the first approach as a programmer of the method,
  • you urself are dealing with the exception.
  • This is fine if you are in a best position to decide should be done in case of an exception.
  • Whereas if it is not the responsibility of the method to deal with it's own exceptions,
  • then do not use this approach. In this case use the second approach.
  • In the second approach we are forcing the caller of the method to catch the exceptions,
  • that the method is likely to throw. This is often the approach library creators use.
  • They list the exception in the throws clause and we must catch them.
  • You will find the same approachthroughout the java libraries we use. 

Q: Is it necessary that each try block must be followed by a catch block?

A: It is not necessary that each try block must be followed by a catch block. It should be followed by

either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be

declared in the throws clause of the method.

 

Q: If I write return at the end of the try block, will the finally block still execute?

A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally

block will execute. The finally block will execute and then the control return.

 

Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?

A: No in this case the finally block will not execute because when you say System.exit (0); the control

immediately goes out of the program, and thus finally never executes.

 

 

serialization:

What is serialization?

  • Serialization is mechanism by which you save the state of an object by converting it to a byte stream.

How do I serialize an object to a file?

  • The class whose instances are to be serialized should implement an interface Serializable.
  • Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream.
  • This will save the object to a file. 

Which methods of Serializable interface should I implement?

  • The serializable interface is an empty interface, it does not contain any methods.
  • So we do not implement any methods. 

How can I customize the seralization process? i.e. how can one have a control over the serialization process?

  • Yes it is possible to have control over serialization process.
  • The class should implement Externalizable interface.
  • This interface contains two methods namely readExternal and writeExternal.
  • You should implement these methods and write the logic for customizing the serialization process. 

What is the common usage of serialization?

  • Whenever an object is to be sent over the network, objects need to be serialized.
  • Moreover if the state of an object is to be saved, objects need to be serilazed. 

What is Externalizable interface?

  • Externalizable is an interface which contains two methods readExternal and writeExternal.
  • These methods give you a control over the serialization mechanism.
  • Thus if your class implements this interface, you can customize the serialization process by implementing these methods. 

When you serialize object, what happens to the object references included in the object?

  • The serialization mechanism generates an object graph for serialization.
  • Thus it determines whether the included object references are serializable or not.
  • This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original object.

What one should take care of while serializing the object?

  • One should make sure that all the included objects are also serializable.
  • If any of the objects is not serializable then it throws a NotSerializableException. 

What happens to the static fields of a class during serialization?

  • There are three exceptions in which serialization does not necessarily read and write to the stream.
  • 1-Serialization ignores static fields, because they are not part of any particular state state.
  • 2-Base class fields are only hendled if the base class itself is serializable.
  • 3-Transient fields.

What is a transient variable?
transient variable is a variable that may not be serialized.

What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Static:

 

What is static in java?

  • Static means one per class, not one for each object
  • No matter how many instance of a class might exist
  • This means that you can use them without creating an instance of a class.
  • Static methods are implicitly final, because overriding is done based on the type of the object,
  • Static methods are attached to a class, not an object.
  • A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final.
  • However, you can't override a static method with a nonstatic method.
  • In other words, you can't change a static method into an instance method in a subclass.

 

Static Synchronized and Non-Static synchronized methods in threads

  • static synchronized method and non static synchronized method will not block each other they can run at the same time.
  • The lock objects are different on the static method and non-static method. The static method uses the Class object as the lock (lock obj: MyClass.class), while the non-static method uses the instance object as the lock to which the invocation of the method at that time is bound (lock obj: this).
  • They can both run in different threads at the same time as the lock objects are different. Thread safety is normally ensured by using the same lock object in different threads to make execution of a piece of code between those threads mutually exclusive at any point in time.
  • This means: While static methods lock on the class object of the class, non-static methods lock on the instance on which they're called (by default, synchronized(anyOtherLock) is also possible). Since they lock on different objects, they can run in "parallel".
Can you access non static variable in static context?

So what are the advantages of static blocks?

  • If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.
  • If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded.
  • Security related issues or logging related tasks

 

Can you override static method in Java?

  • No, you cannot override static method in Java because they are resolved at compile time,
  • rather than runtime. Though you can declare and define static method of same name and,
  • signature in child class, this will hide the static method from parent class,
  • that's why it is also known as method hiding in Java.

 

 

Ofcourse there are limitations for static blocks

  • There is a limitation of JVM that a static initializer block should not exceed 64K.
  • You cannot throw Checked Exceptions.
  • You cannot use this keyword since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.
  • LinkedList and ArrayList are two different implementations of the List interface.
  • LinkedList implements it with a doubly-linked list.
  • ArrayList implements it with a dynamically resizing array.
  • Each element of a LinkedList has more overhead since pointers to the next and previous elements
  • are also stored. ArrayLists don't have this overhead.
  • However, ArrayLists take up as much memory as is allocated for the capacity,
  • regardless of whether elements have actually been added.

What is static in java?

  • Static means one per class, not one for each object
  • no matter how many instance of a class might exist.
  • This means that you can use them without creating an instance of a class.
  • Static methods are implicitly final, because overriding is done based on the type of the object,
  • and static methods are attached to a class, not an object.
  • A static method in a superclass can be shadowed by another static method in a subclass,
  • as long as the original method was not declared final.
  • However, you can't override a static method with a nonstatic method. In other words,
  • you can't change a static method into an instance method in a subclass.
  • Static variables and methods are instantiated only once per class.
  • In other words they are class variables, not instance variables.
  • If you change the value of a static variable in a particular object,
  • the value of that variable changes for all instances of that class.
  • Static methods can be referenced with the name of the class rather than
  • the name of a particular object of the class (though that works too).

 

Can you override private or static method in Java ?

 

What is the difference between static and non-static variables?

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

 

Question: Can you override a static method in Java?

  • you can not override a static method in Java, 
  • if you create a similar method with same return type and same method arguments in child class 
  • then it will hide the superclass method, this is known as method hiding.

 

collection:

 

  • Key Interfaces used by collectons framework are LIST , SET nad MAP.
  • The List and Set extends the Collection Interface.
  • Collections Class whcih is a utility class.
  • SET ( HashSet, TreeSet) - SET is a collection of unique elements prevents duplication.
  • HashSet and TreeSet are implementations of a set interface.
  • TreeSet is an ordered HashSet implements SortedSet interface.
  • LIST is a collection with an ordered sequence of elements and may contain duplicates
  • ArrayList , Linked List and vector are implementations of List interface.
  • MAP that maps key to values can contain duplicate values but keys in map must be unique
  • Sorted Map Interface = Tree Map is an ordered HashMap
  • MAP Interface = HashMap, TreeMap & HashTable

How Implement Collection Ordering

  • SortedSet and SortedMap interfaces maintain sorted order.

  • The Classes which implement the COMPARABLE interface impose natural order.

  • Comparable allows itself to compare with another similar object using compareTo() method.

  • Arrays.sort(myArray)    Collections.sort(myCollection)

  • COMPARATOR interface is used when ordering based on multiple attributs

  • Comparator is used to compare 2 different objects --> compare(Object o1, Object o2)

ConcurrentModificatinException

  • When one thread changes a collection while another thread is traversng it through with iterator.
  • iterator,hasNext() or iterator.next() call will throw ConcurrentModificatinException
  • SynchronizedMap & Synchronized List are only conditionally thread safe which means
  • all individual operations are thread safe  but compound operations are not safe
  • solution-1 : convert list to an array with list.toArray()and iterate on that array not goof if list is large
  • Solution-2: lock entire list while iterating by wrapping yor code within synchronized block
  • Solution-3: use ConcurrentHashMap & CopyonWriteArrayList
  • Solution-4: use it.remove() - removes the current object via the iterator "it" --> myCollection
  • avoid myCollection.remove(myObject) - avoid by-passing the iterator, when it.next() throw CME

 

Difference between LinkedList vs ArrayList in Java

 

  • LinkedList and ArrayList both implement List Interface
  • but how they work internally is where the differences lies.
  • Difference between ArrayList and LinkedList is that
    • ArrayList is implemented using re sizable array
    • while LinkedList is implemented usingdoubly LinkedList.
    • ArrayList is more popular among Java programmer than LinkedList
    • few scenarios on which LinkedListis a suitable collection than ArrayList.

 

LinkedList vs ArrayList in Java

 

  • LinkedList and ArrayList has there root on difference between Array and LinkedList data-structure.
  • ArrayList is an index based data-structure searching element from Array with index is pretty fast.
    • Array provides O(1) performance for get(index) method but remove is costly in ArrayList 
    • ArrayList also needs to update its index if you insert something anywhere except at the end of array
    • if array gets full which makes adding into ArrayList of O(n) in worst case,
    • As you need to rearrange all elements
    • ArrayList each index only holds actual object (data)
  • LinkedList doesn't provide Random or index based access
    • LinkedList you need to iterate over linked list to retrieve any element whichis of order O(n).
    • 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  
    • while adding is O(1)operation in LinkedList in Java.
    • Removal is like insertions better in LinkedList than ArrayList.
    • LinkedList has more memory overhead than ArrayList
    • LinkedList each node holds both data and address of next  and previous node.

 

When to use LinkedList and ArrayList in Java

  • LinkedList is not as popular as ArrayList
  • There are situation where a LinkedList is better choice than ArrayList in Java.
  • Use LinkedList in Java if:
    • Your application can live without Random access.
    • Because if you need nth element in LinkedList
    • you need to first traverseup to nth element O(n) and than you get data from that node.
    • Your application is more insertion and deletion driver
    • you insert or remove more than retrieval. 
    • Since insertion or removal doesn't involve resizing its much faster than ArrayList.
  • That’s all on difference between ArrayList and LinkedList in Java.
  • Use ArrayList in Java for all there situation where you need a non-synchronized index based access.
  • ArrayList is fast and easyto use,
  • just try to minimize array resizing by constructing arraylist with proper initial size.

Read more: http://javarevisited.blogspot.com/2012/02/difference-between-linkedlist-vs.html#ixzz2HPUXQ21k

 

Do you Know how HashMap works in Java” or"How does get () method of HashMap works in Java

  • "HashMap works on principle of hashing,
  • we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap.
  • When we pass Key and Value object  to put() method on Java HashMap,
  • HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object,
  • HashMap in Java stores both key and value object as Map.
  • Entry in bucket which is essential to understand the retrieving logic.
  • Next question could be about collision detection and collision resolution in Java HashMap  e.g. 

 

What will happen if two different objects have same hashcode?

How will you retrieve Value object  if two Keys will have same hashcode

  • HashMap uses Key Object's hashcode to find out bucket location and retrieves Value object.
  • There are two Value objects are stored in same bucket ,
  • traversal in LinkedList until we find the value object ,
  • HashMap  stores both Key and Value in LinkedList node
  • Aafter finding bucket location , we will call keys.equals() method to identify correct node in LinkedList
  • Return associated value object for that key in Java HashMap
  • Using immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap  keys and improve performance of Java HashMap  by reducing collision.
  • Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.

 

What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor

  • If the size of the Map exceeds a given threshold defined by load-factor
  • e.g. if load factor is .75 it will act to re-size the map once it filled 75%.
  • Similar to other collection classes like ArrayList,  Java HashMap re-size itself by creating a
  • new bucket array of size twice of previous size of HashMap and then start putting every old
  • element into that new bucket array.
  • This process is called rehashing because it also applies hash function to find new bucket location. 

Do you see any problem with resizing of HashMap  in Java ??

  • Multiple thread accessing the HashMap and potentially looking for race condition on HashMap  in Java. 
  • Yes there is potential race condition exists while resizing HashMap in Java.
  • If two thread at the same time found that now HashMap needs resizing and they both try to resizing.
  • on the process of resizing of HashMap in Java , the element in bucket which is stored in
  • linked list get reversed in order during there migration to new bucket because java HashMap
  •  doesn't append the new element at tail instead it append new element at head to avoid tail traversing.
  • If race condition happens then you will end up with an infinite loop.
  • what the hell makes you think to use HashMap  in multi-threaded environment to interviewer

 

Can we use any custom object as key in HashMap ?

  • you can use any Object as key in Java HashMap provided it follows equals and hashCode contract
  • Its hashCode should not vary once the object is inserted into Map.
  • If custom object is Immutable than this will be already taken care you can not change it once created

Can we use ConcurrentHashMap in place of Hashtable ?

  • This is another question which getting popular due to increasing popularity of ConcurrentHashMap.
  • Since we know Hashtable is synchronized
  • ConcurrentHashMap provides better concurrency by only locking portion of map  by concurrency level.
  • ConcurrentHashMap is certainly introduced as Hashtable and can be used in place of it
  • but Hashtable provide stronger thread-safety than ConcurrentHashMap.
  • See my post difference between Hashtable and ConcurrentHashMap for more details.

 

Personally, I like this question because of its depth and number of concept it touches indirectly, if you look questions asked during interview this HashMap  questions has verified

  • Concept of hashing
  • Collision resolution in HashMap
  • Use of equals () and hashCode () and there importance in HashMap?
  • Benefit of immutable object?
  • Race condition on HashMap  in Java
  • Resizing of Java HashMap

How HashMap  works in Java

  • HashMap  works on principle of hashing, we have put() and get() method for storing and retrieving object form HashMap
  • .When we pass an both key and value to put() method to store on HashMap ,
  • it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.

Also HashMap  stores both key+value tuple in every node of linked list.

 

What will happen if we put a key object in a HashMap which is already there ?
  • If you put same key again than it will replace old mapping because HashMap doesn't allow duplicate keys.

What will happen if two different HashMap  key objects have same hashcode?

  • They will be stored in same bucket but no next node of linked list.
  • keys equals () method will be used to identify correct key value pair in HashMap .
  • In terms of usage Java HashMap is very versatile and I have mostly used HashMap as cache in electronic trading application I have worked .
  • Since finance domain used Java heavily and due to performance reason we need caching HashMap and ConcurrentHashMap comes as very handy there. Y
  • you can also check following articles form Javarevisited to learn more about HashMap and Hashtable in Java :
  • Read more: http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz2HPTpYnt8

What will happen if two different objects have same hashcode?

  • equals and hashCode() contract that two unequal object in Java very much can have equal hashcode.
  • HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.”

How will you retreive if two different objects have same hashcode?

  • HashMap uses keys hashcode to find out bucket location and retreives object
  • but then you need to remind him that there are two objects are stored in same bucket ,
  • so they will say about traversal in linked list until we find the value object ,
  • how do you identify vlaue object because you don’t value object to compare ,
  • HashMap stores both Key and Value in linked list node
  • after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap.
  • using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys
  • improve performance of Java hashMap by reducing collision.
  • Immutablity also allows caching there hashcode of different keys which makes overall retreival process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

 

How HashMAp works in Java

  • HashMap works on principle of hashing
  • we have put () and get () method for storing and retrieving object form hashMap.
  • When we pass an both key and value to put() method to store on HashMap,
  • it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
  • While retrieving it uses key object equals method to find out correct key value pair
  • and return value object associated with that key.
  • HashMap uses linked list in case of collision and object will be stored in next node of linked list.
  • Also hashMap stores both key+value tuple in every node of linked list.

 

What will happen if two different HashMap key objects have same hashcode?

  • They will be stored in same bucket but no next node of linked list.
  • And keys equals () method will be used to identify correct key value pair in HashMap.
  • In terms of usage HashMap is very versatile and I have mostly used hashMap as cache in electronic trading application I have worked .
  • Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap comes as very handy there.

 

When should I use LinkedList?

  • When you need efficient removal in between elements or at the start.
  • When you don't need random access to elements, but can live with iterating over them one by one

When should I use ArrayList?

  • When you need random access to elements ("get the nth. element")
  • When you don't need to remove elements from between others. It's possible but it's slower since the internal backing-up array needs to be reallocated.
  • Adding elements is amortized constant time (meaning every once in a while, you pay some performance, but overall adding is instantly done)
  • Linked Lists are an alternative to ArrayLists that Computer Scientists have come up with.
  • While an ArrayList uses an array internally to store the data,
  • a LinkedList uses nodes to hold the elements.
  • These nodes then point to each other, thus leading to the name "Linked" List.
  • There are three types of Linked Lists: singly-linked lists, doubly-linked lists and circularly-linked lists.
  • Singly-linked lists work by having each node pointing to the next node, with the tail node (or end node) pointing to nothing (or a null reference).
  • Doubly-linked lists expand upon the singly-linked list, with each node pointing to the previous node as well as the next node.
  • In doubly-linked lists, both the head node (first node) and the tail node point to nothing.
  • Circularly-linked lists expand upon the singly-linked list differently than the doubly-linked list; instead of having the tail node pointing to nothing, it "circles" back around, pointing to the head element as the name suggests.

 

When I use an object as a key in a Hashtable, what in the Object class must I override and why?

  • When you create your own key object for use in a Hashtable, you must override the Object.equals() and Object.hashCode() methods
  • since Hashtable uses a combination of the key's hashCode() and equals() methods to store and retrieve its entries quickly.
  • It's also a general rule that when you override equals(), you always override hashCode().
  •  

A slightly more in-depth explanation will help you understand Hashtable's mechanism for storage and retrieval. A Hashtable internally contains buckets in which it stores the key/value pairs. The Hashtable uses the key's hashcode to determine to which bucket the key/value pair should map.

 

A Hashtable and its buckets

  •  When you pass a key/value to the Hashtable, it queries the key's hashcode.
  • The Hashtable uses that code to determine the bucket in which to place the key/value.
  • So, for example, if the hashcode equals zero, the Hashtable places the value into Bucket 0.
  • Likewise, if the hashcode is two, the Hashtable places the value into Bucket 2.
  • (This is a simplistic example; the Hashtable will massage the hashcode first so the Hashtable doesn't try to insert the value outside the bucket.)
  • By using the hashcode this way, the Hashtable can also quickly determine in which bucket it has placed the value when you try to retrieve it.
  • Hashcodes, however, represent only half the picture.
  • The hashcode only tells the Hashtable into which bucket to drop the key/value.
  • Sometimes, however, multiple objects may map to the same bucket, an event known as a collision.
  • In Java, the Hashtable responds to a collision by placing multiple values into the same bucket

 

A Hashtable after a few collisions

  • Now imagine that you call get() with a key that maps to Bucket 0.
  • The Hashtable will now need to peform a sequential search through the key/value pairs in Bucket 0 to find your requested value.
  • To perform this lookup, the Hashtable executes the following steps:
  • Query the key's hashcode
  • Retrieve the list of key/values residing in the bucket given by the hashcode
  • Scan through each entry sequentially until a key that equals the key passed into get() is found
  • The algorithm a Hashset uses to achieve this is to retrieve the hash code for the object and use this to find the correct bucket.
  • Then it iterates over all the items in the bucket until it finds one that is equal. If the number of items in the bucket is greater than O(1) then lookup will take longer than O(1) time.
  • In the worst case - if all items hash to the same bucket - it will take O(n) time to determine if an object is in the set.

 

What should be the ideal object to bucket ratio?

  • There is a space-time tradeoff here.
  • Increasing the number of buckets decreases the chance of collisions.
  • However it also increases memory requirements.
  • The hash set has two parameters initialCapacity and loadFactor that allow you to adjust how many buckets the HashSet should create.
  • The default load factor is 0.75 and this is fine for most purposes,
  • but if you have special requirements you can choose another value.
  • This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
  • Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).
  • Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
  • An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
  • The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.
  • The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
  • When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method.
  • As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs.
  • Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put).
  • The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity,
  • so as to minimize the number of rehash operations.
  • If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

 

What is HashMap and Map?

  • Map is Interface and Hashmap is class that implements that.

 

Difference between HashMap and HashTable?

  • The HashMap class is roughly equivalent to Hashtable,
  • except that it is unsynchronized permits nulls.
  • HashMap allows null values as key and value whereas Hashtable doesnt allow.
  • HashMap does not guarantee that the order of the map will remain constant over time.
  • HashMap is unsynchronized and Hashtable is synchronized.

 

What is difference between synchronize and concurrent Collection in Java? 

  • There was time, before Java 1.5 when you only have synchronized collection,
  • if you need them in a multi-threaded Java program.
  • Those classes were plagued with several issue most importantly performance because,
  • they lock the whole collection or map whenever a thread reads or writes.
  • To address those issue, Java released couple of Concurrent collection classes e.g.
  • ConcurrentHashMap, CopyOnWriteArrayList and BlockingQueue to provide scalability and performance.

 

 

 =======================================================================