Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Wednesday, August 5, 2020

Java Technical interview @ Candela Labs - Round 2

Hi friends,

In this post , I am sharing interview questions answers asked in Candela Labs in round - 2.



Question 1:

Is the DispatcherServlet instantiated via Application context?

Answer:

No,the DispatcherServlet is instantiated by Servlet containers like tomcat or jetty. We must define the Dispatcher Servlet into the web.xml file.

We also include load-on-startup tag = 1, which means DispatcherServlet  is instantiated when you deploy the spring MVC application to Tomcat or any other servlet container.
During instantiation, it looks for a file servlet-name-context.xml and then initializes beans defined in this file. 



Question 2:

Do we need spring-mvc.jar in our classpath or is it part of spring-core?

Answer: 

The spring-mvc.jar is not part of spring-core, which means that if we want to use spring MVC framework in the java project, we must include spring-mvc.jar in the application's classpath.
In a java web application, spring-mvc.jar is usually placed inside the /WEB-INF/lib folder.



Question 3:

How Spring MVC framework works? How HTTP request is processed?

Answer:

  • Client sends a request to a URL.
  • That request hit the web container e.g. Tomcat or Jetty. Then it looks into web.xml and find the servlet or filter which is mapped to that URL.
  • It then delegates the control to servlet or filter to process the request. Web container(Tomcat) is responsible for creating servlet and filter instances and invoking their various lifecycle methods e.g. init(), service() and destroy().  In the case of HTTP request, HTTPServlet handles that and depending upon the HTTP request method, various do...() methods are invoked by container e.g. doGet(), doPost() to process GET request and POST request.
  • To enable spring MVC, we need to declare the DispatcherServlet from spring MVC jar into web.xml. This servlet listens for a URL pattern * as shown below in web.xml, which means all requests are mapped to DispatcherServlet.
  •     Then DispatcherServlet then passes the request to a specific controller depending on the URL requested. It uses handler mapping [@RequestMapping annotation] or spring mvc configuration file to find out the mapping of request URL to difference controllers. Controller classes are also identified using @Controller and @RestController annotations.
  • After processing the request , controller returns a logical view name and model to DispatcherServlet and it consults view resolvers until an actual view is determined to render the output.
  • DispatcherServlet then contacts the chosen view e.g. Freemarker  or JSP with model data and it renders the output.
  • This rendered output is returned to the client as HTTP response. On it's way back, it can pass to any configured filgter as well e.g. Spring security filter chain or filters configured to convert the response to JSON or XML.



Question 4:

Which cache you have used and explain the steps to use that cache?

Answer:

There are multiple types of caches:

  • Caffeine
  • HazelCast
  • Redis
  • EHCache
  • CouchBase
I have used Redis cache.

Redis is an open source in-memory data structure store used as a database, cache and message broker.

It supports data structures such as strings, hashes, lists, set, sorted set and streams.
Redis has built-in replication.

Redis cache limits:

On 32-bit machine,it can store upto 3 GB of data. When cache size reaches the memory limit, old data is removed to make place for new one.

Annotations used:

  • @Cacheable : To cache some values
  • @Cacheput : To update the cache
  • @CacheEvict : To empty the cache

Maven Dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


application properties:

#Redis config:
spring.cache.type=redis
spring.redis.host-localhost
sprint.redis.port=6379


@EnableCaching annotation on SpringBootApplication main class.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository{

}

@RestController
public class UserController{

    private final Logger log = LoggerFactory.getLogger(getClass());

    private final UserRepository userRepository;

    @Autowired
    public UserController(userRepository userRepository){
    
        this.userRepository = userRepository;
    }

    @Cacheable(value="users", key="#userId", unless="#result.followers<12000")
    @RequestMapping(value"/{userId}", method=RequestMethod.GET)
    public user getUser(@PathVariable String userId){

        log.info("Getting user with ID {}", userId);
        return userRepository.findOne(Long.valueOf(userId));
    }
}



Question 5:

What will be the output of below code?

public class StringClass{

    public static void main(int[] args){

        final String str = "First String is computer";
        String str1 = str.replaceAll("First", "Last");

        System.out.println(str);
    }

}

Answer:

It says, main type is not found. Because JVM requires a main method with String[] as arguments.
In the same code, if we try replacing str1 with str, then compiler shows exception that str is declared as final and cannot be changed.



Question 6:

What happens internally when we invoke main method?

Answer:

The purpose of main method in java is to be program execution start point.

When we run java.exe,it makes some JNI calls. These calls load the DLL that is really the JVM.

It will parse the command line arguments , creates a new string array in the JVM to hold these arguments , parses the class name that we specify as containing main() method, uses JNI calls to find the main() method, then invokes the main() method passing the parameters list.



Thanks for reading!!

Saturday, June 20, 2020

Java Interview @ Polaris

Hi friends,

In this post, I'm sharing interview questions asked in Polaris.


Question 1:

public class Quiz23{

    public static void main(String[] args){

        int x = 0;
        int[] nums = {1,2,3,5};

        for(int i : nums){

            switch(i){

                case 1:
                    x += i;
                case 5:
                    x += i;
                default:
                    x += i;
                case 2:
                    x  += i;

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

What will be the output of above code?

Answer:

27

Explanation:

For case i = 1:  All the cases will run.
For case i = 2: only case 2 will run.
For case i = 3: Default and case 2 will run.
For case i = 5: case , default and case 2 will run.



Question 2:

What is the difference between Map and FlatMap?

Answer:

Map: Transforms the elements into something else. It accepts a function to apply to each element and returns a new Stream of values returned by the passed function.

It takes function object as the parameter e.g.: Function, ToIntFunction, ToIntDoubleFunction, ToLongFunction.


FlatMap: Combination of Map and Flat operations.So, we first apply map operation on each element and then flattens the result.

So, if function used by Map is returning a single value, then map is ok. But, if function used by Map operation is returning a stream of list or stream of stream, then we need to use flatmap to get stream of values.

For example:

If we have a stream of String containing {"12", "34"} and a method getPermutations() which returns a list of permutations of given string.

When we apply getPermutation() into each string of Stream using map , we get something like [["12","21"], ["34","43"]], but if we use flatMap, we get a stream of strings e.g.: ["12","21","34","43"].

Another example:

List evens = Arrays.asList(2,4,6);
List odds = Arras.asList(3,5,7);
List primes = Arrays.asList(2,3,5,7,11);

List numbers = Stream.of(evens, odds, primes).flatMap(list -> list.stream()).collect(Collectors.toList());

System.out.println("flattened list : "+numbers);

Output: flattened list : [2,4,6,3,5,7,2,3,5,7,11]


 
Question 3:

What is the difference between passing int array and String array to Stream.of()?

Answer:

Stream.of(int[]) gives Stream<int[]>
Stream.of(String[]) gives Stream<String>

So, when using Stream.of() with int[] , we get Stream<int[]> and then for getting ints from Stream, we use flatMapToInt(i -> Arrays.Stream(i)) to get IntStream and then we can either use map() or forEach().

e.g.:

int[] arr = {1,2,3,4};
Stream<int[]> streamArr = Stream.of(arr);
IntStream intStream = streamArr.flatMapToInt(i -> Arrays.Stream(i));
intStream.forEach(System.out :: println);



Question 4:

What is a Boxed Stream?

Answer:

If we want to convert stream of objects to collection:

List<String> strings = Stream.of("how", "to", "do", "in", "java").collect(Collectors.toList());

The same process doesn't work on streams of primitives, however.

//Compilation Error:
IntStream.of(1,2,3,4,5).collect(Collectors.toList());

To convert a stream of primitives, we must first box the elements in their wrapper class and then collect them. This type of stream is called boxed stream.

Example of IntStream to List of Integers:

List<Integer> ints = IntStream.of(1,2,3,4,5).boxed().collect(Collectors.toList());

System.out.println(ints);

Output: [1,2,3,4,5]

 

Question 5:

List Spring Core and Stereotype annotations.

Answer:

Spring Core Annotations:
  • @Qualifier
  • @Autowired
  • @Configuration
  • @ComponentScan
  • @Required
  • @Bean
  • @Lazy
  • @Value

Spring framework Stereotype annotations:
  • @Component
  • @Controller
  • @Service
  • @Repository


Question 6:

What is difference  between @Controller and @RestController?

Answer:

@Controller creates a Map of model object and finds a view for that.
@RestController simply returns the object and object data is directly written into HTTP response as JSON or XML.

@RestController = @Controller + @ResponseBody
@RestController was added in  Spring 4.



Question 7:

Why Spring introduced @RestController when this job could be done by using @Controller and @ResponseBody?

Answer:

The functioning or output of @Controller and @ResponseBody is the default behavior of RESTFUL web services, that's why Spring introduced @RestController which combined the behavior of @Controller and @ResponseBody.  



Question 8:

Tell something about Swagger tools which you have used.

Answer:

Swagger Editor:  Can edit OpenAPI specifications.

Swagger UI : A collection of HTML/CSS/Javascript assets that dynamically generate beautiful documentation.

Swagger Codegen: Allows generation of API client libraries.

Swagger Parser: Library for parsing OpenAPI definitions from java.

Swagger Core: Java related libraries for creating, consuming and working with OpenAPI definitions.

Swagger Inspector: API testing tool

SwaggerHub : Built for teams working with OpenAPI.








That's all for this post.
Thanks for reading!!

Tuesday, February 4, 2020

Java Interview @ Gemini Solutions

Hi Friends,

In this post, I'm sharing Java Interview questions for the role of Java Technical Lead in Gemini Solutions.


You may also interested in going through my other interview questions in many I.T. companies:




Question 1:

Write algorithm for Infix expression evaluation.

expression is : 3*(5-1)/3 + 1


Answer:

Algorithm:

Approach: Use two Stacks


  • operand stack
  • operator stack
Process:
  1. Pop out two values from operand stack, let's say it is X and Y.
  2. Pop out operator from operator stack. Let's say it is '+'
  3. Do X + Y and push the result on the operand stack.

Iterate through given expression, one character at a time.

  1. If a character is an operand, push it on the operand stack. 
  2. If the character is an operator,
    • If the operator stack is empty, push it onto the operator stack.
    • Else if the operator stack is not empty,
      • If the character's precedence is greater than or equal to the precedence of the stack top of the operator stack, then push the character to the operator stack.
      • If the character's precedence is less than the precedence of the stack top of the operator stack , then do Process [As described above] until character's precedence is less or stack is not empty.
  3. If the character is "(", then push it onto the operator stack.
  4. If the character is ")",  then do Process [As described above]  until the corresponding "(" is encountered in operator stack. Now just pop out the "(".


Question 2:

What is the difference between Lambda and anonymous class?


Answer:

There are multiple differences between lambda and anonymous class:


  • Usage of 'this' keyword: IN anonymous class, this keyword resolves to anonymous class itself. Whereas for Lambda, this keyword resolves to enclosing class where lambda expression is written.
  • Compilation: Java compiler compiles lambda expression and convert them into static private method of the class. It used invokedynamic bytecode instruction that was added in java 7to bind this method dynamically. While anonymous class compiles to a class. The compiler generates a class file for each anonymous inner class.
  • Lambdas implement a functional interface, so implements only 1 method. Anonymous class can extend a class or implement multiple interfaces with any number of methods.



Question 3:

Design Email [Inbox, Outbox, attachment]. Write all technologies that will be used. Create Class diagram.

Answer:

I designed as per experience.



Question 4:

What is the use of volatile keyword? How does it help in synchronization? Does it provide full synchronization?

Answer:

Volatile is used to avoid the local copy of a variable inside  a thread. All threads will access the volatile variable from main memory , updates it and immediately put it back in main memory.
All, reads and writes would be made directly to main memory instead of to registers or local processor cache.

volatile variable is not thread safe. If multiple threads try to write on a volatile variable, then Race condition occurs.

Each thread has a separate memory space known as working memory. This holds the value of different variables for performing operations. After performing an operation, thread copies the updated value of the variable to main memory and from there other threads can read the latest value.

But if the variable is non-volatile, then new value may not be flushed immediately to main memory. And other threads may not read the updated value.



Question 5:

Why to use transient variable? What will be the value of transient variable after deserialization?
Where should we use transient variable?


Answer:

transient variable is used when we don't want value of that variable to be serialized.
So, if a variable is declared as transient, then it's value will not be serialized.

On deserialization, we get the default value of transient variable. e.g. :

transient int i ;

When the instance of this class is serialized, then upon deserialization, we get 0 in i , as 0 is the default value for an int in java.

Even if we declare i as transient int i = 10;
In this case, as well we get value of i as 0 after deserialization.

Use case  [Where should we use it]:

When we have a variable whose value can be calculated from other variables, the we should make it transient, as it should be calculated from other variables every time.



Question 6:

How will you write an immutable class?


Answer:

There are two ways to write an immutable class:


  • Make the class final and all it's instance variables as final, so that they can be initialized in constructor only.
  • Make all instance variable of the class as private and don't modify them inside in method. Means don't provide any setters methods. And also make all getters methods as final so that they can't be overridden and subclasses cannot override them and return some other values from overridden forms.



Question 7:

Write Lambda expression for printing even numbers from a list.

Answer:

Suppose , we have a list of integers.

int[] array = {1,2,3,4,5};

List<Integer> list = Arrays.asList(array);

list.stream().filter(i-> i%2 == 0).collect().forEach(System.out :: println);



Question 8:

Difference between default method and regular method in java 8.


Answer:

Differences between default method and regular method are as follows:


  • default method has default keyword in it's method signature. While regular method has no such keyword.
  • default cannot change the state of the object as it works only inside interface and ca only access it's local variables. While a regular method ca change the state of the object by modifying method arguments as well as fields of the class.




That's all for this interview.

Hope, this interview help everybody in clearing java technical rounds.

Thanks for reading.


Monday, February 3, 2020

Java Interview @ OrangeMantra

Hi Firends,

In this post, I'm sharing interview questions asked in OrangeMantra.

Also read Questions-Answers asked in other interviews:





Question 1:

List all types of HTTP Error code categories

Answer:

There are mainly 5 categories in HTTP Response codes:


  • 1XX : Informational
    • 100 : Continue
  • 2XX : Success
    • 200 : OK
    • 201 : Created
    • 202: Accepted
    • 204: No Content
  • 3XX : Redirection
  • 4XX : Client Side Error
    • 400 : Bad Request
    • 401 : UnAuthorized
    • 402 : Payment Required
    • 403 : Forbidden
    • 404 : Not Found
  • 5XX : Server Side Error 
    • 500 : Internal Server error
    • 501: Not Implemented
    • 502: Bad Gateway
    • 503: Web service not available


Question 2:

List all the features in Java 7

Answer:

There are multiple features which have been added in java 7:

  • String in switch
  • try with resources
  • Binary Literals
  • multiple Exception types in catch block


Question 3 :

Explain about one very typical designing/Coding situation which you have solved.

Answer:

I answered as per my experience.



Question 4:

Explain all differences between Stack and Heap?


Answer:

  • Heap is very large in size while Stack is small in size as compared to Heap.
  • Every thread has it's own Stack while Heap is shared among all threads.
  • When Heap gets full, java.lang.OutOfMemoryException is thrown. While in case of Stack, java.lang.StackOverflowException is thrown.
  • Heap is mainly used to store the objects, while Stack is used for storing local data, method body , method return values etc.
  • Heap is tuned by using -Xmx and -Xms options. While Stack size is tuned by -Xss.
  • In Heap, data is stored in random order. While in  Stack , data is stored in LIFO [Last-In-First-Out] order.


Question 5:

What is the contract between natural ordering and equals() method in java?

Answer:

Contract between natural ordering or ordering provided by comparator interface and equals() method is that the output returned by natural ordering / comparator interface should be consistent with value returned by equals() method.

If these values are not consistent, then it will lead unexpected results in TreeMap and TreeSet Collections.



Question 6:

What is the use case of Marker interface ? How to write custom marker interface?

Answer:

Marker interface is used to indicate something special to JVM/Compiler so that it can perform necessary actions on the class implementing marker interface.

Examples of marker interfaces are : Serializable, Cloneable, Remote

Custom marker interface:

public interface Ingestible{
    //nothing
}

public interface Edible extends Ingestible{


}


public interface Drinkable extends Ingestible{

}


public class Food implements Edible{

}


public class Drink implements Drinkable{

}


public class Person{

    public void ingest(Ingestible something){
        
         if(something instanceof Edible){

              System.out.println("something can be eaten");

         }
    }
}

In above example, we are telling JVM that the class implementing Ingestible interface can be ingested.

Use case:

A marker interface is used for Identification purpose.



Question 7:

Why to use BigDecimal over Float or Double?


Answer:

Float and Double cannot be used for precise values: e.g.:

double d1 = 131.44;
double d2 = 130.34;

System.out.println("d1 - d2 = "+ (d1-d2));

Output:  1.10000000000013

That's why in financial applications, where while doing calculations , scale and rounding mode for the numbers is an important aspect . So it's a better choice to go with BigDecimal.


Using BigDecimal:
BigDecimal bd1 = new BigDecimal("131.44");
BigDecimal bd2 = new BigDecimal("130.44");

System.out.println(bd1-bd2);  gives 1.10







That's all for this interview post.

Hope this post helps everybody in their java interviews.

Thanks for reading !!


Monday, January 27, 2020

Interview @ NexGen Solutions

Hi Friends,

I'm sharing my recent interview @ NexGen Solutions. It was for the  position of Technical Architect and was very simple one.

You can also go through my other real time interviews:

Interview @ Dew Solutions
Interview @ RBS
Interview @ Aricent



Question 1: What is the benefit of Executor framework?


Answer:

Executor Framework provides separation of Command submission from Command execution.
It has several interfaces. Most important ones are:


  • Executor
  • ExecutorService
  • ScheduledExecutorService
Executors is Factory methods class used in this framework.




Question 2: Asked me to write custom ArrayList.

//You can write your own implementation


Question 3: In your Custom ArrayList, there are multiple methods. How will you provide synchronization?

Answer:

We have two ways of providing synchronization in this source code:


  • Make each method synchronized by placing synchronized keyword before return type of method
  • Use synchronized block inside method body.



Question 4:

How did you use Amazon EC2?

Answer:

I installed EC2 instance using Amazon Management console after login into it.
I used General instance for my purpose, as in my application I needed to send multiple emails to client very fast.



Question 5:

What is the benefit of Generics in java?

Answer:

Generics provides Compile-time safety. And it also avoids ClassCastException. It was introduced in Java 5.



Question 6:

How Generic code written in java 5 runs in Java 4 compiler?

Answer:

Java compiler uses type check information at compile time and after all validation it generates type erased byte code which is similar to the byte code generated by Java 4. So, it provides backward compatibility.


Question 7: Asked about my last project.

Answer:

I explained it.


Question 8:

Why we can't pass List<String> to List<Object> in java?

Answer:

String is a subclass of Object, but List<String> is not a subclass of List<Object>.

If it would be allowed, then look at below code:

List<Object> listO = new ArrayList<String>();
listO.add("String");
listO.add(new Object());

Now, in the same List , we have both a String and Object object. Which is wrong.





That's all from this interview.
Hope this post helps everybody in their job interviews.

Thanks for reading.




CAP Theorem and external configuration in microservices

 Hi friends, In this post, I will explain about CAP Theorem and setting external configurations in microservices. Question 1: What is CAP Th...