Showing posts with label Java Interview. Show all posts
Showing posts with label Java Interview. Show all posts

Friday 22 May 2020

Latest Java Interview Questions- Part 3

1.How many objects are create when we use the new keyword with the string


eg: a="syed"

    b=new String("syed")

It will create the different objects moreover both are not same.

2. Difference between the filter and map in java 8.

FIlter will check the condition and inserts in to the List only if it satisfies.

        List<EmployeeClass> empSet1 = new ArrayList<>();

        empSet1=empSet.stream().filter(e->e.getId().equals("1")).collect(Collectors.toList());

Map will insert the boolean of list based on the condition .

        List<Boolean> empSet1 = new ArrayList<>();

        empSet1=empSet.stream().filter(e->e.getId().equals("1")).collect(Collectors.toList());

3. what are Java Executors, Also Explain Important terms in it.

The Java Executor Framework has been introduced in Java 1.5 and it is a part of java concurrency package. The Executor framework is an abstraction layer over the actual implementation of java multithreading. It is the first concurrent utility framework in java and used for standardizing invocation, scheduling, execution and control of asynchronous tasks in parallel thread.

Executor implementation in java uses thread pools which consists of worker threads. The entire management of worker threads is handled by the framework. So the overhead in memory management is much reduced compared to earlier multithreading approaches.

The Java Executor framework provides multi-threading applications an easy abstraction layer. The executor abstraction layer hides the critical parts of concurrent execution and the programmer only concentrates on the business logic implementation.

The Java Executor framework creates tasks by using instances of Runnable or Callable. In case of Runnable, the run () method does not return a value or throw any checked exception. But Callable is a more functional version in that area. It defines a call () method that allows the return of some computed value which can be used in future processing and it also throws an exception if necessary.

The FutureTask class is another important component which is used to get future information about the processing. An instance of this class can wrap either a Callable or a Runnable. You can get an instance of this as the return value of submit () method of an ExecutorService. You can also manually wrap your task in a FutureTask before calling execute () method

4. What are the functional steps to implement the java Thread Pool Executor?

Following are the functional steps to implement the Java ThreadPoolExecutor.

●     A pool of multiple threads is created.

●     A queue is created holding all the tasks but these tasks are not yet assigned to threads from the pool.

●     Rejection handler is used to handle the situation when one or more tasks are not able to assign in the queue. As per the default rejection policy, it will simply throw a RejectedExecutionException runtime exception, and the application can catch it or discard it.

5. What are the types of executors?

SingleThreadExecutor

This thread pool executor has only a single thread. It is used to execute tasks in a sequential manner. If the thread dies due to an exception while executing a task, a new thread is created to replace the old thread and the subsequent tasks are executed in the new one.

ExecutorService executorService = Executors.newSingleThreadExecutor()

FixedThreadPool(n)

As the name indicates, it is a thread pool of a fixed number of threads. The tasks submitted to the executor are executed by the n threads and if there is more task they are stored on a LinkedBlockingQueue. This number is usually the total number of the threads supported by the underlying processor.

ExecutorService executorService = Executors.newFixedThreadPool(4);

CachedThreadPool

This thread pool is mostly used where there are lots of short-lived parallel tasks to be executed. Unlike the fixed thread pool, the number of threads of this executor pool is not bounded. If all the threads are busy executing some tasks and a new task comes, the pool will create and add a new thread to the executor. As soon as one of the threads becomes free, it will take up the execution of the new tasks. If a thread remains idle for sixty seconds, they are terminated and removed from cache.

However, if not managed correctly, or the tasks are not short-lived, the thread pool will have lots of live threads. This may lead to resource thrashing and hence performance drop.

ExecutorService executorService = Executors.newCachedThreadPool();

ScheduledExecutor

This executor is used when we have a task that needs to be run at regular intervals or if we wish to delay a certain task.

ScheduledExecutorService scheduledExecService = Executors.newScheduledThreadPool(1);

The tasks can be scheduled in ScheduledExecutor using either of the two methods scheduleAtFixedRate or scheduleWithFixedDelay.

scheduledExecService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

scheduledExecService.scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)

The main difference between the two methods is their interpretation of the delay between consecutive executions of a scheduled job.

scheduleAtFixedRate executes the task with fixed interval, irrespective of when the previous task ended.

scheduleWithFixedDelay will start the delay countdown only after the currently task completes.

6. Understanding the Future Object,Why the Task submitted to the executor is asynchronous.

The result of the task submitted for execution to an executor can be accessed using the java.util.concurrent.Future object returned by the executor. Future can be thought of as a promise made to the caller by the executor.

Future<String> result = executorService.submit(callableTask);

A task submitted to the executor, like above, is asynchronous i.e. the program execution does not wait for the completion of task execution to proceed to the next step. Instead, whenever the task execution is completed, it is set in this Future object by the executor.

The caller can continue executing the main program and when the result of the submitted task is needed he can call .get() on this Future object. If the task is complete the result is immediately returned to the caller or else the caller is blocked until the execution of this is completed by the executor and the result is computed.

If the caller cannot afford to wait indefinitely before retrieving the result, this wait can be timed as well. This is achieved by the Future.get(long timeout, TimeUnit unit) method which throws a TimeoutException if the result is not returned in the stipulated timeframe. The caller can handle this exception and continue with the further execution of the program.

If there is an exception when executing the task, the call to get method will throw an ExecutionException.

An important thing with respect to result being returned by Future.get() method is that it is returned only if the submitted task implements java.util.concurrent.Callable. If the task implements the Runnable interface, the call to .get() will return null once the task is complete.

Another important method is the Future.cancel(boolean mayInterruptIfRunning) method. This method is used to cancel the execution of a submitted task. If the task is already executing, the executor will attempt to interrupt the task execution if the mayInterruptIfRunning flag is passed as true.



7.Write a Sample program explaining the Executors using the callable and Runnable,Executors.

Sample Program using callable.

package com.sample.executor;

import java.util.concurrent.Callable;

public class HelloWorldTask implements Callable<String> {



 private String message;

 public HelloWorldTask(String message) {

  super();

  this.message = message;

 }

 public String getMessage() {

  return message;

 }

 public void setMessage(String message) {

  this.message = message;

 }

 @Override

 public String call() throws Exception {



  if(getMessage().equals("syed")) {

   throw new NullPointerException();

  }

  return "Hello"+ getMessage();

 }

}



Using Runnable:

package com.sample.executor;

public class HelloWorldRunnable implements Runnable {



 private String message;

 public HelloWorldRunnable(String message) {

  this.message = message;

 }

 public String getMessage() {

  return message;

 }

 public void setMessage(String message) {

  this.message = message;

 }

 @Override

 public void run() {

  if(getMessage().equals("syed")) {

   throw new NullPointerException();

  }

  System.out.println("Hello"+getMessage());

 }

}

Using Executor:

package com.sample.executor;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class HelloWorldExecutor {

 public static void main(String[] args) {

  ExecutorService exec = Executors.newFixedThreadPool(4);

  HelloWorldTask helloTask = new HelloWorldTask(args[0]);

  HelloWorldRunnable helloRunnable = new HelloWorldRunnable(args[0]);

   Future<String> resultCallable = exec.submit(helloTask);

   Future<String> resultRunnable = (Future<String>) exec.submit(helloRunnable);

   try {

   System.out.println(resultCallable.get());

   System.out.println(resultRunnable.get());

   }catch(InterruptedException | ExecutionException e) {

              e.printStackTrace();

   }

   exec.shutdown();

 }

}



8. Difference between callable and runnable interfaces in java.

●        A Callable needs to implement call() method while a Runnable needs to implement run() method.

●        A Callable can return a value but a Runnable cannot.

●        A Callable can throw checked exception but a Runnable cannot.

●        A Callable can be used with ExecutorService#invokeXXX(Collection<? extends Callable<T>> tasks) methods but a Runnable cannot be

Also when we look carefully at the call() method in the CallableThread, the method signatures defines 'throws Exception'. This is not possible in Runnable.run() method. The compiler will give a error on writing throws Exception 'Exception Exception is not compatible with throws clause in Runnable.run()'. What we can write on Runnable.run() is 'throws RuntimeException'. The behind the run() method can throw only a RuntimeException is that the compiler has no bonding on the caller of this method to catch the Exception. Also with Runnable we do not know when calling start() whether the thread has started, completed, or isInProgress




Thursday 21 May 2020

Latest Java Interview Questions- Part 2


1.Explain Serializable and DeSerialization in Java?
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object in a platform and deserialize in different platform.
For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization we call the readObject() method of ObjectInputStream class.

2. Explain the Synchronization in Java?
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.

3. What is Concurrency in Java?
In simple words, concurrency is the ability to run several programs or several parts of a program in parallel. Concurrency enable a program to achieve high performance and throughput by utilizing the untapped capabilities of underlying operating system and machine hardware. e.g. modern computers has several CPU’s or several cores within one CPU, program can utilize all cores for some part of processing; thus completing task much before in time in comparison to sequential processing.
The backbone of java concurrency are threads. A thread is a lightweight process which has its own call stack, but can access shared data of other threads in the same process. A Java application runs by default in one process. Within a Java application you can work with many threads to achieve parallel processing or concurrency.

4. What makes java application concurrent?
The very first class, you will need to make a java class concurrent, is java.lang.Thread class. This class is the basis of all concurrency concepts in java. Then you have java.lang.Runnable interface to abstract the thread behavior out of thread class.
Other classes you will need to build advance applications can be found at java.util.concurrent package added in Java 1.5.

5. What is DeadLock?
The answer is simple when two or more threads are waiting for each other to release the resource they need (lock) and get stuck for infinite time, the situation is called deadlock. It will only happen in the case of multitasking or multi-threading.

6.How to avoid Deadlock?
Deadlock can be avoided by providing the ordered access.
Avoid Nested Locks – You must avoid giving locks to multiple threads, this is the main reason for a deadlock condition. It normally happens when you give locks to multiple threads.
Avoid Unnecessary Locks – The locks should be given to the important threads. Giving locks to the unnecessary threads that cause the deadlock condition.
Using Thread Join – A deadlock usually happens when one thread is waiting for the other to finish. In this case, we can use Thread.join with a maximum time that a thread will take.

7. What is Polymorphism?
Polymorphism means many, we can perform single action in different ways. There are two types of Polymorphism.
Compile Time ploymorphism and RunTime Polymorphism.We can perform polymorphism in java by method overloading and method overriding.

8.What is Compile Time Polymorphism?
If you overload a static method in Java, it is the example of compile time polymorphism.

9.What is Runtime Polymorphism or Dynamic Dispatch with Example?
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
eg:
class Car{ 
  void run(){System.out.println("Hi I am Car");} 
} 
class Suv extends Car{ 
  void run(){System.out.println("Hi I am an SUV Car");} 
 
  public static void main(String args[]){ 
    Car b = new Suv();//upcasting 
    b.run(); 
  } 
}

10. Why String is Immutable?
The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable.

11. In Which Memory String is stored?
In heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called String Constant Pool.

12. How do you write an Immutable class?
·       Declare the class as final so it can’t be extended.
·       Make all fields private so that direct access is not allowed.
·       Don’t provide setter methods for variables
·       Make all mutable fields final so that it’s value can be assigned only once.
·       Initialize all the fields via a constructor performing deep copy.
·       Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

13. What is data abstraction and How will I achieve it?
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details.The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

14. What will happen when two IO Exception and FileNotFoundException is thrown
FileNotFoundException extends IOException
If you look at inheritance FileNotFoundException is a sub-class of IOException. By catching the super class you also catch anything that extends it.

15. What is the return type of the CompareTo Method.
Integer is the return type of the CompareTo Method.

16. What will happen when two employee class objects containing same Id is added to the Set. How many entries will be available? If I want to remove the duplicate what I will do.
There will be two entries available if we do so. To Make it unique we need to create the hashCode and equals method, then only one entry will be avalible.

17. Difference between Set and List in java.
List
Set
The list provides positional access of the elements in the collection.
Set doesn't provide positional access to the elements in the collection
Implementation of List are ArrayList, LinkedList, Vector ,Stack
Implementation of a set interface is HashSet and  LinkedHashSet
We can store the duplicate elements in the list.
We can’t store duplicate elements in Set 
List maintains insertion order of elements in the collection 
Set doesn’t maintain any order 
The list can store multiple null elements 
Set can store only one null element

18. State Some OOPS concepts
1)Class
The class is a group of similar entities. It is only an logical component and not the physical entity. For example, if you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods may be performed with these cars are driving, reverse, braking etc.
2) Object
An object can be defined as an instance of a class, and there can be multiple instances of a class in a program. An Object contains both the data and the function, which operates on the data. For example - chair, bike, marker, pen, table, car, etc.
3) Inheritance
Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the parent object. It’s creating a parent-child relationship between two classes. It offers robust and natural mechanism for organizing and structure of any software.
4) Polymorphism
Polymorphism refers to the ability of a variable, object or function to take on multiple forms. For example, in English, the verb run has a different meaning if you use it with a laptop, a foot race, and business. Here, we understand the meaning of run based on the other words used along with it.The same also applied to Polymorphism.
5) Abstraction
An abstraction is an act of representing essential features without including background details. It is a technique of creating a new data type that is suited for a specific application. For example, while driving a car, you do not have to be concerned with its internal working. Here you just need to concern about parts like steering wheel, Gears, accelerator, etc.
6) Encapsulation
Encapsulation is an OOP technique of wrapping the data and code. In this OOPS concept, the variables of a class are always hidden from other classes. It can only be accessed using the methods of their current class. For example - in school, a student cannot exist without a class.
7) Association
Association is a relationship between two objects. It defines the diversity between objects. In this OOP concept, all object have their separate lifecycle, and there is no owner. For example, many students can associate with one teacher while one student can also associate with multiple teachers.
8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such that child object can’t belong to another parent object. For example consider class/objects department and teacher. Here, a single teacher can’t belong to multiple departments, but even if we delete the department, the teacher object will never be destroyed.
9) Composition
A composition is a specialized form of Aggregation. It is also called "death" relationship. Child objects do not have their lifecycle so when parent object deletes all child object will also delete automatically. For that, let’s take an example of House and rooms. Any house can have several rooms. One room can’t become part of two different houses. So, if you delete the house room will also be deleted.

19. Advantages of OOPS
       OOP offers easy to understand and a clear modular structure for programs.
       Objects created for Object-Oriented Programs can be reused in other programs. Thus it saves significant development cost.
       Large programs are difficult to write, but if the development and designing team follow OOPS concept then they can better design with minimum flaws.
       It also enhances program modularity because every object exists independently.

20. Given the Employee List, sort it using the Id if they are not same and sort it using the name if two employee are having the same Id.
Comparator<EmployeeClass> c = new Comparator<EmployeeClass>() {
            @Override
            public int compare(EmployeeClass e1, EmployeeClass e2) {
                if(e1.getId().equals(e2.getId())) {
                    return e1.getName().compareTo(e2.getName());
                }
                return e1.getId().compareTo(e2.getId());

            }
        };
        empSet.stream().sorted(c).forEachOrdered(System.out::println);


Latest Java Interview Questions- Part 1

Hello Readers, these are the questions from my Interview experience. I have framed these questions in such a way to make yourself prepared for any technical challenging interviews. Continue my other parts of the Interview questions.

All the VeryBest !!!!

1.Can we override static method?
No, you cannot override static method in Java, though you can declare method with same signature in sub class. It won't be overridden in exact sense, instead that is called method hiding.

2.Can you explain why we cannot override the static method?
It may be decided during the time of resolution, static binding, are bonded during compile time using Type of reference variable, and not Object.
 If you declare, another static method with same signature in derived class than static method of super class will be hidden, and any call to that static method in sub class will go to static method declared in that class itself.

3. Explain Method Hiding?
When the Super class and subclass has the same method with same arguments then the super class method is hidden by the subclass method this is called as the method hiding. Usually this happens when the methods are defined as static.

4. Can We Overload the Static method?
Yes, we can overload static methods in Java, there is nothing wrong declaring static methods with same name, but different arguments.

5. can we override final method?
Final methods cannot be overridden because the purpose of the "final" keyword is to prevent overriding.

6. What is this and super key words in Java can we use both same time.
· we use this() keyword in constructor chaining to access the constructor of the same class
· we use super() keyword when we want to access the constructor of immediate parent class in inheritance.
And there is a condition in both that they have to be declared in the first line of the constructor you are using. And that's the reason why we can't use both in a single constructor because you can write only one thing in your first line.

7. what is Static block, what is the use of it and explain with the program.
Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).
Also, static blocks are executed before constructors. For example, check output of following Java program

class Test {
    static int i;
    int j;
    // start of static block
    static {
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
}
class Main {
    public static void main(String args[]) {
        // Although we don't have an object of Test, static block is
        // called because i is being accessed in following statement.
        System.out.println(Test.i);
    }
}

8.Explain Java 7 Features.
Decorate Components with the JLayer Class:
The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.
Strings in switch Statement:
In the JDK 7, we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Type Inference for Generic Instance:
We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> l = new ArrayList<>();
l.add("A");
l.addAll(new ArrayList<>());
In comparison, the following example compiles:
List<? extends String> list2 = new ArrayList<>();
l.addAll(list2);
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:
catch (IOException e) {
  logger.log(e);
  throw e;
}
catch (SQLException e) {
  logger.log(e);
  throw e;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException e) {
  logger.log(e);
  throw e;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).


The java.nio.file package
The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.

9. Explain Java 8 Features.
Lambda Expressions
Lambda expressions gives the ability to pass a functionality as a method argument. Lambda expression help us reduce the code clutter in using a single method class. For example, when we must associate an action button click to a functionality, then lambda expressions will make the code look neat and compact. Refer Java Lambda expression examples to learn more.
Pipelines and Streams
Pipelines and streams enrich the Java collections framework. Sequence of aggregate operations is a pipeline. Stream is used to propagate elements from a source through a pipeline. It is a sequence of elements. Pipeline and streams will make our task easier in accessing the elements from collections and applying operations on it.
Date and Time API
Pre Java 8, date and time related operations are little bit cumbersome. JSR 310: Date and Time API give us a brand new package java.time package. This is a well thought package. It contains a best list of utility methods used for regular operations. This will help in handling date and time operations in an easier way.
Default Methods
Default methods gives the ability to add default implementation for methods in an interface. This is a rocking feature of Java 8. When we implement an interface, if we did not provide implementation for a method, then the default method will be used in that place. This will help in maintaining backward compatibility in applications, we can add a method to an interface without breaking its implementations.
Type Annotations
Before Java 8 Java annotations can be applied to type declarations. From this Java 8 release onwards, annotations can be applied to type use. Annotations can be applied wherever a type is used like in new instance creates, exception throws clause etc. This will help to enforce stronger type checks and using this feature we can come up with a type checking framework itself.
Nashorn JavaScript Engine
Nashorn is a brand new JavaScript engine provided along with the Java 8 release. Using this we can develop standalone JavaScript applications in Java. Pre Java 8, we got JDK with a JavaScript engine based on Rhino. It is a developed from scratch. It will provide better compatibility with ECMA normalized JavaScript specification and better performance than Rhino. Already we have seen a tutorial to run Javascript in Java using the ScriptEngineManager.
Concurrent Accumulators
java.util.concurrent.atomic package is getting additional classes as part of Java 8 release. These will help to sum values from across multiple threads.
Parallel operations
Iterating over a collection can be done in parallel using the aggregate operations easily. Pre Java 8 Iterators are used to parse the elements of a collection one by on explicitly. Now that can be done in parallel internally with the use of streams and aggregate operations. We can create multiple substreams and those substreams can be processed internally in parallel and then the results be combined. For this to be effective, we need to have multiple cores and data volume.
PermGen Space Removed
The PermGen space is removed from Java 8 and instead we have MetaSpace introduced. One of the most dreaded error, “java.lang.OutOfMemoryError: PermGen error” will no longer be seen from Java 8. Nice thing is that the MetaSpace default is unlimited and that the system memory itself becomes the memory.
Metaspace capacity
By default class metadata allocation is limited by the amount of available native memory (capacity will of course depend if you use a 32-bit JVM vs. 64-bit along with OS virtual memory availability).
A new flag is available (MaxMetaspaceSize), allowing you to limit the amount of native memory used for class metadata. If you don’t specify this flag, the Metaspace will dynamically re-size depending of the application demand at runtime.
TLS SNI
Server Name Indentification (SNI) is an extension of the TLS protocol used for identifying the certificate to serve based on the hostname specified by the client. This enables a server to have virtual host over HTTPS. The same IP address can be used for multiple hosts and their respective different security certificates.
The above list of Java 8 features is just a highlight. I will be writing detailed tutorials about each of them in the coming days.
10. What is ConcurrencyHashMap and data structure of it
ConcurrentHashMap: It allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.
The point is to provide an implementation of HashMap that is threadsafe. Multiple threads can read from and write to it without the chance of receiving out-of-date or corrupted data. ConcurrentHashMapprovides its own synchronization, so you do not have to synchronize accesses to it explicitly.
ConcurrentHashMap allow concurrent access to the map. HashTables too offers synchronized access to map, but your entire map is locked to perform any operation.
The logic behind ConcurrentHashMap is that your entire table is not getting locked, but only the portion[segments]. Each segments manages its own HashTable. Locking is applied only for updates. In case of of retrievals, it allows full concurrency.

11.What is CopyOnWriteArrayList?
As the name indicates, CopyOnWriteArrayList creates a Cloned copy of underlying ArrayList, for every update operation at certain point both will be synchronized automatically, which is taken care by JVM. Therefore, there is no effect for threads which are performing read operation.
It is costly to use because for every update operation a cloned copy will be created. Hence CopyOnWriteArrayList is the best choice if our frequent operation is read operation.
It extends object and implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E> and RandomAccess
The underlined data structure is grow-able array.
It is thread-safe version of ArrayList.
Insertion is preserved, duplicates are allowed, and heterogeneous Objects are allowed.
The main important point about CopyOnWriteArrayList is Iterator of CopyOnWriteArrayList cannot perform remove operation otherwise we get Run-time exception saying UnsupportedOperationException.

12. Difference between SYNCHRONIZEDLIST and COPYONWRITEARRAYLIST
SYNCHRONIZEDLIST
COPYONWRITEARRAYLIST
It locks the whole list for thread-safety during both read or write operation.
It locks the list during write operation only, so no lock during read operation therefore, multiple threads executing read operations concurrently.
It is a fail-fast iterator.
It is a fail-safe iterator.
It is Introduced in Java 1.2 version.
It is Introduced in Java 1.5 version.
Iteration of list should be inside synchronized block otherwise it will face non-deterministic behaviour.
It can safely iterate outside the synchronized block.
If any other thread tries to modify the list while one thread iterating that list, then it will throw ConcurrentModificationException.
It doesn’t allow modifying the list while traversing, and it will not throw ConcurrentModificationException if the list is being modified by other thread during the traversal.
It is best to use when arraylist is large and write operation are greater than read operation in list.
It is best to use when ArrayList is small or read operation are greater than write operation.

13.Difference between ArrayList and LinkedList.
ArrayList
LinkedList
1) ArrayList internally uses a dynamic array to store the elements.
LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.

14. Difference between SinglyLinked list and DoublyLinked list, and when to use them.
Singly linked list
Doubly linked list
A singly linked list is a linked list where the node contains some data and a pointer to the next node in the list
A doubly linked list is complex type of linked list where the node contains some data and a pointer to the next as well as the previous node in the list
It allows traversal only in one way
It allows a two way traversal
It uses less memory per node (single pointer)
It uses more memory per node(two pointers)
Complexity of insertion and deletion at a known position is O(n)
Complexity of insertion and deletion at a known position is O(1)
If we need to save memory and searching is not required, we use singly linked list
If we need better performance while searching and memory is not a limitation, we go for doubly linked list
If we know that an element is located towards the end section, eg. ‘zebra’ still we need to begin from start and traverse the whole list
If we know that an element is located towards the end section e.g. ’zebra’ we can start searching from the Back.
Singly linked list can mostly be used for stacks
They can be used to implement stacks, heaps, binary trees.

15. what is equals and hashCode methods in Java and how they are related.
Java equals() and hashCode() methods are present in Object class. So every java class gets the default implementation of equals() and hashCode(). In this post we will look into java equals() and hashCode() methods in detail.
Object class defined equals() method like this:
According to java documentation of equals() method, any implementation should adhere to following principles.
· For any object x, x.equals(x) should return true.
· For any two object x and y, x.equals(y) should return true if and only if y.equals(x)returns true.
· For multiple objects x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
· Multiple invocations of x.equals(y) should return same result, unless any of the object properties is modified that is being used in the equals() method implementation.
· Object class equals() method implementation returns true only when both the references are pointing to same object.
Java hashCode()
Java Object hashCode() is a native method and returns the integer hash code value of the object. The general contract of hashCode() method is:
· Multiple invocations of hashCode() should return the same integer value, unless the object property is modified that is being used in the equals() method.
· An object hash code value can change in multiple executions of the same application.
· If two objects are equal according to equals() method, then their hash code must be same.
· If two objects are unequal according to equals() method, their hash code are not required to be different. Their hash code value may or may-not be equal.
Importance of equals() and hashCode() method
Java hashCode() and equals() method are used in Hash table based implementations in java for storing and retrieving data.
The implementation of equals() and hashCode() should follow these rules.
· If o1.equals(o2), then o1.hashCode() == o2.hashCode() should always be true.
· If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.
1.By implementing the Runnable interface.
class MyThread implements Runnable {
    public void run() {
        System.out.println("concurrent thread started running..");
    }
}

class MyThreadDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        Thread t = new Thread(mt);
        t.start();
    }
}
2.By extending the Thread class.
class MyThread extends Thread {
    public void run() {
        System.out.println("concurrent thread started running..");
    }
}

classMyThreadDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        mt.start();
    }
}

16.what is run () method is used for.
The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.
The run() method can be called using the start() method or by calling the run() method itself. But when you use run() method for calling itself, it creates problems.
If you directly call run() method its body is executed in context of current thread. When you invoke start() method a new thread is created and run() method is executed in this new thread.

17. How HashMap works internally?
HashMap works on the principle of hashing. Hashing can be defined as assigning the code to the object by applying the algorithm.

In Hashmap the objects are stored in the buckets by converting the hashcode for the key and the bucket is found and saved there and again if the object is got using the key, then the hashcode is applied and read from that location. The Hashmap works in this principle of hashing. The hashcode should be same during the saving and retrieving (it's mandatory for it to do so to retrieve the object and that's why HashMap keys are immutable e.g. String) hence we will not lose the objects stored. HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object.

This will go smoother when we have only one object stored for the location, Sometimes the collision may happen. Since the HashMap internally stores in array, this is of fixed size, and if you keep storing objects, at some point of time hash function will return same bucket location for two different keys, this is called collision in HashMap. In this case, a linked list is formed at that bucket location and a new entry is stored as next node.

If we try to retrieve an object from this linked list, we need an extra check to search correct value, this is done by equals() method. Since each node contains an entry, HashMap keeps comparing entry's key object with the passed key using equals() and when it return true, Map returns the corresponding value.


From Java8 the Linkedlist is replaced with the tree for the searching.

18. Which one is used for faster search, HashMap or TreeMap and why.
a HashMap is O(1) average, so it is supposed to be faster, and for large maps will probably have better throughput.
However, a HashMap requires rehashing when Load Balance become too high. rehashing is O(n), so at any time of the program's life, you may suffer unexpectedly performance loss due to rehash, which might be critical in some apps [high latency]. So think twice before using HashMap if
latency is an issue!
However, if you would often need to process your dictionary in alphabetical order, you would be better off with the TreeMap since you would otherwise need to sort all your words every time you need to process them in alphabetical order.
       We should use a TreeMap if we want to keep our entries sorted
       We should use a HashMap if we prioritize performance over memory consumption
       Since a TreeMap has a more significant locality, we might consider it if we want to access objects that are relatively close to each other according to their natural ordering
       HashMap can be tuned using the initialCapacity and loadFactor, which isn’t possible for the TreeMap
       We can use the LinkedHashMap if we want to preserve insertion order while benefiting from constant time access

19. What will happen if i call thread.start()?
No. After starting a thread, it can never be started again. If you do so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception. Running Exception in thread "main" java.lang.IllegalThreadStateException

20.Difference between ArrayList and LinkedList
ArrayList
LinkedList
1) ArrayList internally uses a dynamic array to store the elements.
LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.