Friday, 22 May 2020

Typical MicroServices Interview

1. Explain briefly about your project experience ​ .

2. Explain about oops concept and how you implemented in your project.  

3. I have a class A having main method, also I have another class B extends A when compiling B will it be executed or not?.

Yes, It will get executed. 
public class Test2 {         

public static void main(String[] args) {  
System.out.println("Called Test 2");         }   } 

public class Test4 extends Test2  {  } 

output: Called Test 2 

4. What will happen when a method is called inside the same method. Who Checks and stop the program termination. 

eg:  public class Test2  { 

public void greet(){ 
greet(); 
}         
public static void main(String[] args) {
  Test2 test2 = new Test2();
  test2.greet();  
       } 
  } 

The above Code throws Exception in thread "main" java.lang.StackOverflowError. Which means The StackOverflowError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur. 

When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no 
space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM). 

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided. 

5. If I have a static method in both parent class and extended class and while creating the object reference for the child method which method will be invoked.? 

private, final and static methods and variables use static binding and bonded by the compiler while overridden methods are bonded during runtime based upon the type of runtime object 

Hence the method in the parent class is called also the compiler throws the warnings."The static method greet() from the type Test2 should be accessed in a static way" 

6. How many objects are created when (Parent)Test2 test2 = new (child)Test4(); 

In inheritance, subclass acquires super class properties. An important point to note is, when subclass object is created, a separate object of super class object will not be created. Only a subclass object object is created that has super class variables. 

7. Explain static binding? 

Static Binding: The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time . 

Why binding of static, final and private methods is always a static binding?  Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. 

8. I have two class and methods with different argument how do you call this during the runtime. 

public class ReflectionDemo1 {


    public static void main(String[] args) {

        System.out.println(greet("Syed Ghouse Habib", 1));
    }
    public static String greet(String string, long log) {
        return string + log;
    }
}

public class ReflectionDemo2 {
    public static void main(String[] args) {

        System.out.println(greet("Syed Ghouse Habib"));
    }
    public static String greet(String string) {
        return string;
    }
}

It can be called using the reflection.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class InvokeMain {
    public static void main(String...args) {
        try {
            for (String arg: args) {
                Class << ? > c = Class.forName(arg);
                Class[] argTypes = new Class[1];
                argTypes[0] = String[].class;
                Method main = c.getDeclaredMethod("main", argTypes);
                String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
                System.out.format("invoking %s.main()%n", c.getName());
                main.invoke(null, (Object) mainArgs);
            }

            // production code should handle these exceptions more gracefully } catch (ClassNotFoundException x) {     x.printStackTrace(); } catch (NoSuchMethodException x) {     x.printStackTrace(); } catch (IllegalAccessException x) {     x.printStackTrace(); 
        } catch (InvocationTargetException x) {
            x.printStackTrace();
        }
    }
}

9. What will happen when the Employee object with the same value is added to the set

Having only the equals method. It will have two objects created. When we have only the hashcode method. It will have two objects created. It will have only one entry when both the methods are available. 

10. Write a program to sum the value from the given alphanumeric string. 

sampleString = "pq12s56"

import java.util.stream.Collectors;

public class StringSummer {

    public static void main(String args[]) {
        String sampleString = "pq12s56";
        int sum8 = 0; //using java8 
        sum8 = sampleString.chars().filter(val - > Character.isDigit((char) val)).mapToObj(num - > Character.getNumericValue(num)).collect(Collectors.summingInt(Integer::intValue));
        System.out.println(sum8);

        int sum = 0; //using java 7
        char[] charVal = sampleString.toCharArray();
        for (char c: charVal) {
            if (Character.isDigit(c)) {
                sum = sum + Character.getNumericValue(c);
            }

        }
        System.out.println(sum);
    }
}

11. Explain memory management in java?.

Runtime data area in JVM can be divided as below, 

Method Area: Storage area for compiled class files. (One per JVM instance) 

Heap: Storage area for Objects. (One per JVM instance) 

Java stack: Storage area for local variables, results of intermediate operations. (One per thread) 

PC Register: Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread) 

Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread) 

Following are points you need to consider about memory allocation in java. 

Note: Object and Object references are different things. 

1)There is new keyword in java used very often to create a new objects. But what new does is allocate memory for the object of class you are making and returns a reference. 

That means whenever you create an object as static or local, it gets stored in HEAP. 

2) All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap. 

3) Classes loaded by classloader and static variables and static object references are stored in a special location in heap which permanent generation. 

4) Local primitive variables, local object references and method parameters are stored in Stack. 

5) Local Functions (methods) are stored in stack but Static functions(methods) goes in permanent storage. 

6) All the information related to a class like the name of the class, Object arrays associated with the class, internal objects used by JVM (like java/lang/Object), and optimization information goes into the Permanent Generation area. 

7) To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems. 


12. Explain the initial capacity of ArrayList?. How would you force to create an array of capacity 8? 

In java 8 default capacity of ArrayList is 0 until we add at least one object into the ArrayList object (You can call it lazy initialization). 

Now question is why this change has been done in JAVA 8? 

The answer is to save memory consumption. Millions of array list objects are created in real-time java applications. Default size of 10 objects means that we allocate 10 pointers (40 or 80 bytes) for the underlying array at creation and fill them in with nulls. An empty array (filled with nulls) occupy lot of memory . 

Lazy initialization postpones this memory consumption till moment you will actually use the array list. 

List<String> s = new ArrayList<>(8); 

This statement will create the array of inital capacity 8. 

13. What is the algorithm used in Java GC. 

Mark & sweep algoritm. 

14.what are the different types of method avaliable in  

1. GET Method HTTP GET method used to retrieve information from the REST API.We should not use this method to change any information or the resource.GET should be idempotent, meaning regardless of how many times it repeats with the same parameters, the results are the same. 

2. POST Method This method in the REST API should only be used to create a new resource.In some cases, POST method is used to update entity but this operation is not very frequent.POST API call is not idempotent nor safe and should be used with care. 

3. PUT Method If we want to update an existing resource, PUT method should be used for this operation.PUT method has some features as compare to the POST method and we should keep those in mind · PUT method is idempotent.This means the client can send the same request multiple time and as per HTTP spec, this has exactly the same effect as sending once. (This is for us to make sure PUT behaves correctly every time) 

4. DELETE Method DELETE method should be used to remove a given resource.Similiar to PUT method, DELETE operation is idempotent.If a resource is deleted any later request will change anything in the 
system and it should return 404 response.DELETE can be a long-running or asynchronous request.

 5. PATCH Method Partial update to a resource should happen through PATCH method.To differentiate between PATCH and PUT method, PATCH request used to partially change a given resource while PUT used to replace existing resource.There are few things to keep in mind while using PATCH method. · Support for PATCH in browsers, servers and web applications are not universal, this can post some challenges. · Request payload for Patch is not simple and a client is required to send information to differentiate between the new and original documents. 

15. Difference between put and post method. 

PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)! POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent. 

16. How does the springboot works. 

From the run method, the main application context is kicked off which in turn searches for the classes annotated with @Configuration, initializes all the declared beans in those configuration classes, and based upon the scope of those beans, stores those beans in JVM, specifically in a space inside JVM which is known as IOC container. After the creation of all the beans, automatically configures the dispatcher servlet and registers the default handler mappings, messageConverts, and all other basic things. 

Basically, spring boot supports three embedded servers:- Tomcat (default), Jetty and Undertow. 

You can add cross filters in spring boot in one of the configuration files as 

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/api/**");     } } 

17.What are the Embeded servers in spring boot and which one is default. 

Tomcat (default), Jetty and Undertow. 

18. Difference between spring mvc and spring boot, is dispatcher servlet not used in the springboot? 

Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs. 

Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on). So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer. 


You understood it right. 

@Configuration @Configuration is an analog for xml file. Such classes are sources of bean definitions by defining methods with the @Bean annotation. 

@Configuration is: 

not required, if you already pass the annotated class in the sources parameter when calling the SpringApplication.run() method; required, when you don't pass the annotated class explicitly, but it's in the package that's specified in the @ComponentScan annotation of your main configuration class. For readability, classes that are even explicitly passed as sources may anyway be annotated with @Configuration - just to show the intentions more clearly. 

Your current class is not really source of bean definitions, because it doesn't have any, but if you had @Bean annotated methods, Spring would see them. 

@EnableAutoConfiguration Can be used with or without @Configuration. It tells Spring to setup some basic infrastructure judging by what you have in the classpath. It's done by invoking a so called import class that's 
derived from the value of the @Import annotation that @EnableAutoConfiguration includes. Only one class should be annotated with @EnableAutoConfiguration, duplicating it doesn't do anything. 

19.what is a stream in java 8 and what are its features?. 

Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package. 

Stream provides following features: 

Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations. Stream is functional in nature. Operations performed on a stream does not modify it's source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection. Stream is lazy and evaluates code only when required. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. You can use stream to filter, collect, print, and convert from one data structure to other etc. In the following examples, we have apply various operations with the help of stream. 

20. Draw microservices componets. 


21. How to implement the retry mechanism for the microservices. 

@SpringBootApplication
@EnableRetry
public class So52193237Application {

    public static void main(String[] args) {
        SpringApplication.run(So52193237Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(Foo foo) {
        return args - > {
            try {
                foo.exec();
            } catch (Exception e) {
                try {
                    foo.exec();
                } catch (Exception ee) {
                    Thread.sleep(11000);
                    try {
                        foo.exec();
                    } catch (Exception eee) {

                    }
                }
            }
        };
    }

    @Component
    public static class Foo {

        private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);

        private final Bar bar;

        public Foo(Bar bar) {
            this.bar = bar;
        }

        @CircuitBreaker(maxAttempts = 1, openTimeout = 10000, resetTimeout = 10000)
        public void exec() throws TypeOneException {
            LOGGER.info("Foo.circuit");
            this.bar.retryWhenException();
        }

        @Recover
        public void recover(Throwable t) throws Throwable {
            LOGGER.info("Foo.recover");
            throw t;
        }

    }

    @Component
    public static class Bar {

        private static final Logger LOGGER = LoggerFactory.getLogger(Bar.class);

        @Retryable(value = {
            TypeOneException.class
        }, maxAttempts = 3, backoff = @Backoff(2000)) public void retryWhenException() throws TypeOneException {
            LOGGER.info("Retrying");
            throw new TypeOneException();
        }

        @Recover
        public void recover(Throwable t) throws Throwable {
            LOGGER.info("Bar.recover");
            throw t;
        }

    }

}

22. What are the types of exceptions you have handled in your application? 

23. Do you like to work in a team or an individual contributor? 

24. Do you like to learn about new technologies?. 

25. Have you heard of cucumber?. 

26. What you will do in your free time?. 

27. If you have a conflict with one of your college how you will resolve it?. 

28. If the requirements are not clear what you will do first?. 

29. Any Questions for me? 

x

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);