Showing posts with label java interviews. Show all posts
Showing posts with label java interviews. Show all posts

Tuesday, August 4, 2020

Java Technical Interview @ CandelaLabs

Hi Friends,

In this post, I'm sharing interview questions answers asked in telephonic round of CandelaLabs.

You can also read my other interviews:



Question1: 

What is DispatcherServlet and why it is used for?

Answer:

The DispatcherServlet is the implementation of front controller design pattern that handles all incoming web requests to a spring MVC application.
A front controller pattern is a common pattern in web applications whose job is to receive all requests and route it to different components of application for actual processing.

In Spring MVC, the DispatcherServlet routes web requests to spring MVC controllers.

DispatcherServlet uses handler mapping like @RequestMapping annotation to find correct controller to process a request.

It s also responsible for delegating logical view name to ViewResolver and then sending the rendered response to the client.



Question 2:

What is the root application context in spring MVC? How is it loaded?

Answer:

In Spring MVC, the context loaded using ContextLoaderListener  is called the root application context which belongs to the whole application. While the one initialized using DispatcherServlet is actually specific to that servlet.

Technically, spring MVC allows multiple DispatcherServlet in a spring MVC web application and so are multiple contexts , each specific for the specific servlet. 



Question 3:

How many types of Dependency injection types are there in Spring?
 
Answer:

Spring documentation strictly defines only twp types of injection : constructor and setter injection.

However there are more ways to inject a dependency like a field injection , lookup method injection.

Constructor Injection: Enforcing immutability:

In this, a dependent class has a constructor , where all dependencies are set. These will be provided by spring container according to xml, java or annotation based configuration.

 e.g.:

class Service1{

}

class Service2{

}

class DependentService{
    private Service1 ser1;
    private Service2 ser2;

    public DependentService(Service ser1, Service2 ser2){
        this.ser1 = ser1;
        this.ser2 = ser2;
    }
}


public class Main{

    public static void main(String[] args){

        ApplicationContext container = new ClassPathApplicationContext("spring.xml");

        (DependentService) container.getBean("dependentService");
    }
}


spring.xml is:

<?xml version = "1.0" encoding = "utf-8"?>
    // bean xmlns namespaces goes here.....

    <bean id = "service1" classs ="eample.service1"/>
    <bean id = "service2" class = "example.service2"/>

    <bean id="deoenddentService" class = "example.DepenentService">
        <constructor-arg type = "example.Service1" ref = "service1"/>
        <constructor-arg type = "example.Service2" ref = "service2"/>
    </bean>



Constructor injection using annotation:

@Service
class Service1{

}

@Service
class Service2{

}

@Service
class DependentService{

    private final Service1 ser1;
    private final Service2 ser2;

    @Autowired
    public DependentService(Service1 ser1, Service2 ser2){
        
        this.ser1 = ser1;
        this.ser2 = ser2;
    }

}

public class Main{

    public static void main(String[] args){

        ApplicationContext container = new ClassPathAppplicationContext("spring.xml");
        (DependentService) container.getBean("dependentService");
    
    }
}

Now in spring.xml file:

we do not need to add any <bean>.

Just add <context:component-scan base-package= "example"/>

Drawback of this approach: 

We need to use @Qualifier annotation to tell spring, which implementation of a specific interface to use , in case w e are using two implementations of an interface.

Higher chance to have circular dependencies.


Note: We can have many more constructors in or class, but only one of them should qualify for dependency injection.


Advantage of this approach: Can be combined with setter injection and field injection.


Setter injection:

With XML:

class Service1{

}


class Service2{

}

class DependentService{

    private Service1 ser1;
    private Service2 ser2;

    public DependentService(){

        
    }

    public void setService1(Service1 ser1){

        this.ser1 = ser1;
    }

    public void setService2(Service2 ser2){
    
        this.ser2 = ser2;
    }

}

XML is:

<bean id = "service1" class = "example.Service1"/>
<bean id= "service2" class = "example.Service2"/>

<bean id = "dependentService" class = "example.DependentService">
    <property name="service1" ref="service1"/>
    <property name="service2" ref="service2"/>
</bean>


Setter Injection with annotations:

class Service1{

}


class Service2{

}

class DependentService{

    private Service1 ser1;
    private Service2 ser2;

    public DependentService(){

        
    }

    @Autowired
    public void serService1(Service1 ser1){

        this.ser1 = ser1;
    }

     @Autowired
     public void setService2(Service2 ser2){
    
        this.ser2 = ser2;
    }

}


Note: We can combine setter injection and constructor injection.

  
Field Injection:

@Service
class DependentService{

    @Autowired
    private Service1 ser1;
    
    @Autowired
    private Service2 ser2;
}


Advantages:

  • Easy to use. No constructors or setters required.
  • Can be easily combined with the constructor and /or setter approach.

Disadvantages:

  • A number of dependencies can reach dozens until we notice that something went wrong in the design.



Question 4:

What are java Microservices frameworks?

Answer:

There are multiple java microservices frameworks:

  • Spring and Spring boot
  • DropWizard
  • Eclipse MicroProfile

Spring and Spring Boot:

    The framework propagates building the application into a jar and running it on the embedded Tomcat server , making it a perfect combination with Docker to manage a virtualized  deployment environment.

DropWizard:

Like Spring boot, DropWizard application is packages into jar file with the jetty server embedded.

DropWizard integrates the tried-and-tested java libraries into a fully functional platform: Jersey for REST, Jackson for JSON, Freemarker for template   and Mustache for java based UIs.

DropWizard ships with no built-in dependency injection solution, but integrations exist for Guice and Dagger.




Thanks for reading!!.
 

Friday, July 10, 2020

Mongo DB Replication interview

Hi friends,

In this post, I'm sharing interview questions on Mongo DB replication and configuration.



Question 1:

Why we need replication in Mongo DB?

Answer:

Mongo DB replication has two benefits:

  • If one database node is down, we can get data from other nodes.
  • Replication can also be done for the purpose of load balancing.


Question 2:

How to setup replication in Mongo DB?

Answer:

In Mongo db , replication process can be setup by creating a replica set. In Mongo db, a replica set contains multiple Mongo db servers. In this group of Mongo db servers, one server is known as a primary server and others are known as secondary servers.

Every secondary server always keeps copies of the primary's data. So, if anytime the primary server goes down, then the new primary server is selected from the existing secondary servers and process goes on.
The replication process works as below with the help of a replica set:

Replica set is a group of one or more standalone mongo db servers [Normally, 3 Mongo db servers are required].

In a replica set, one server is marked as primary server and rest are marked as secondary server.

Data writes into the primary server from the application first. Then all the data replicates to the secondary servers from the primary server.

When the primary server is unavailable due to hardware failure or maintenance work, the election process starts to identify the new primary server and select a primary server from the secondary lists.

When the failed server recovered, it will again join the replica set as a secondary server.




  
 

Question 3:

How to configure replication in Mongo DB?

Answer:

I will tell here , how to convert a standalone Mongo db instance into a replica set. This process is not an ideal process for the production environment. Because in production environment, if we need to establish a replica set, then we need to provide three different Mongo db instances for the replica set.

Step 1:

Start a mongo shell with the --nodb options from the command prompt. It will start a shell without any connection with the existing mongodb instance.

Command is : mongo --nodb

Step 2:

Now, create a replica set with the below commands:

replicaSet = new ReplSetTest({name:'rsTest', nodes : 3})

This command instructs the shell to create a replica set with three node servers: one primary and two secondaries.

Step 3:

Now run the below commands one by one to start the mongo db server instances:

1. replicaSet.startSet() - This command starts the three mongo db processes.
2. replicaSet.initiate() - This command configures the replication.

Now, we have three mongo db processes locally on ports port1, port2, port3 [These will be integer values]. 

Step 4:

Now open another command prompt and connect the mongo db running on port port1.

1. conn1 = new Mongo("localhost:port1");
2. connection to localhost:port1
3. rsTest : PRIMARY>

Note that, when we connect a replica set member, the prompt changes to rsTest: PRIMARY. Here PRIMARY is the state of the member and rsTest is the identifier of the replica set.






Question 4:

How to change replication configuration?

Answer:

After defining a replica set, we can change the replica set at any time. We can add new members , remove any existing members.

There is a mongo shell helper method is available to add new replica set members or remove existing replica set members. 

To add a new member into the replica set, we need to run the below command:

rs.add("server-4: 20005")

Similarly, we can remove any members from the existing replica set using the below command:

rs.remove("server-2:20002")

If we need to check the existing configuration of the replication, then we need to run the below command in the shell:

rs.config()  




Question 5:

How does syncing work in Mongo DB?

Answer:

The main objective of the replication process is to keep the same or an identical set of data on multiple servers.  For performing this task, MongoDB always maintains a log of operations or oplog which contains every write information into the primary server. This log is a collection that exists in  the local database on the primary server.
The secondary  servers are queries of this collection for obtaining the operation details so that they can replicate that data.

Every secondary server maintains it's own oplog where Mongo db captures each operation related to the replication process from the primary server.These log files allow any replica set members to use as a sync source for other members.

The secondary server always first fetches the information related to the pending operations from the primary members, then apply that operation to their own data set and then writes down the logs about that operation into the oplog.




That's all for this post.
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!!

Wednesday, May 27, 2020

Java Technical Lead interview @ Accenture

Hi friends,

In this post I'm sharing java interview questions asked in Accenture in Java Technical Lead interview.

You can also go through my other Java Interview posts at multiple levels:


Question 1:

What is the difference between SSL and TLS?


Answer:

There are multiple differences between SSL and TLS:

Alert Messages:

    SSL has "No Certificate" alert message. TLS protocol removes the alert message and replaces it with several other alert messages. 



Record Protocol:

    SSL uses MAC [Message Authentication Code] after encrypting each message while TLS     on the other hand uses HMAC - a hash based message authentication code after each      message encryption. 


Handshake Process:

    In SSL, the hash calculation also comprises the master secret and pad while in TLS, the hashes are calculated over handshake message.



Question 2:

What changes are introduced in Java 10?


Answer:

There are multiple changes that have been done in java 10. Explaining all the changes below:

  • var keyword
  • Unmodifiable Collection enhancements
  • G1GC performance improvement
  • New JIT compiler [Created in pure java]
  • Alternate memory devices for allocating heap
  • Application class data sharing


var keyword:

It improves readability. It is not a reserved word, means it can be used as a class name or variable name. What the var keyword does is , turn local variable assignments:

HashMap<String, String> hm = new HashMap<>();  

into

var hm = new HashMap<String,String>();


Unmodifiable Collection enhancements:

var vegetables = new ArrayList<>(Lists.of("Brocolli", "Celery", "Carrot"));

var unmodifiable = Collections.unmodifiableList(vegetables);
vegetables.set(0, "Radish");
var v = unmodifiable.get(0); //  var v contains Radish.

It is so because, unmodifiableList() returns an unmodifiable view collection.
An unmodifiable view collection is a collection that is unmodifiable and that is also a view onto a backing collection.

Note that changes in the backing collection is still possible , and if they occur, they are visible through the unmodifiable view.  

So, if we need completely unmodifiable collection then, java 10 has added two new API's.

var unmodifiable = List.copyOf(vegetables); 

The second API adds three new methods to the Collector class in the  Stream package. 

We can now stream directly into an unmodifiable collection using toUnmodifiableList, toUnmodifiableSet and toUnmodifiableMap.

  


Question 3:

What is the improvement in G1GC in java 10?

Answer:

Java 9 made the Garbage-First garbage collector (G1GC) by default , replacing the concurrent Mark-sweep garbage collector (CMS).  

Java 10 introduces performance improvements to G1GC.

In java 10, G1GC is getting a performance boost with the introduction of full parallel processing during a full GC.



Question 4:

What is Application class-data sharing?

Answer:

Java 5 introduced Class-Data sharing (CDS) to improve startup times of small java applications.

The general idea was that when the JVM first launched , anything loaded by the bootstrap classloader was serialized and stored in a file on disk that could be reloaded on future launches of the JVM. 
This means that multiple instance of the JVM shared the class metadata so it wouldn't have to load them all every time.


Question 5:

How to write thread safe code in java?

Answer:

Example of Non thread safe code in java:

public class Counter{

    private int count;

// This method is not thread safe because ++ is not an atomic operation. 
    public int getCount(){
        
        return count++;
    }

}

How to make code thread safe in java:

There are multiple ways to make this code thread safe:

1). Use synchronized keyword in java and lock the getCount() method so that only one thread can execute it at a time.

2). Use atomic integer , which makes this ++ operation atomic and since atomic operations are thread-safe and saves cost of external synchronization.

Below is the thread-safe version of Counter class in java:

public class Counter{

    private int count;

    AtomicInteger atomicCount = new AtomicInteger(0);

    //This method is thread safe now because of locking and synchronization

    public synchronized int getCount(){

        return count++;
    }

    //This method is thread safe because count is incremented atomically.

    public int getCountAtomically(){

        return atomicCount.incrementAndGet();
    }
}


Question 6:

How does AtomicInteger work?

Answer:

Java 5 introduced java.util.concurrent.atomic package with a motive to provide a small kit of classes that support lock-free thread-safe programming on single variables. 

AtomicInteger uses combination of volatile and CAS [Compare and Swap] to achieve thread safety for Integer Counter.

It is non blocking in nature.

Compare-and-Swap:

CAS is an atomic instruction used in multi-threading to achieve synchronization.
It compares the contents of a memory location with a given  value and only if they are same, modifies the contents of that memory location to a given new value.  
This is done as a single atomic operation.

The atomicity guarantees that the new value is calculated based on up-to-date information. If the value has been updated by another thread in the meantime, the write would fail.



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.


Java Interview @ OLX

Hi Friends,

I hope you all have read all my previous Java Interviews:




Here in this post, I'm sharing interview questions asked in OLX.



Question 1:

If you have three, you have three. If you have two, you have two, but if you have one, you have none. What is it?

Answer:

Choices


Question 2:

3 bulbs 3 switches problem:

There is a room with a door [Closed] and three light bulbs. Outside the room, there are 3 switches, connected to the bulbs. You may manipulate the switches as you wish, but once you open the door, you can't change them. Identify each switch with it's bulb.

Answer:

Turn on 1 switch and keep it on for 5 minutes. Now turn it off and turn on 2nd button and enter the room. Now the bulb which is ON  maps to ON switch.The hot bulb maps to previous  switch [which was turned on first]  and 3rd bulb maps to 3rd switch.


Question 3:

REST API must use HTTP. Is that true or false?

Answer:

FALSE



Question 4:

A resource in the context of REST is (or may be) which one of these:


  • Thing
  • Object
  • Real World Entity
  • An account
  • An Item
  • A Book
  • All of the above


Answer:

All of the above



Question 5:

Suppose you have a "Worker" table as shown below. You have to write a SQL query to find employees with different salary.

Show only 2 Columns in output: first_name and salary.




Answer:

select distinct w1.salary , w1.first_name
from Worker w1, Worker w2
where w1.salary = w2.salary
AND w1.worker_id = w2.worker_id;



Question 6:

Write SQL query to display first 5 records from the table shown above?

Answer:

select * from worker LIMIT 5;



Question 7:

What is the difference between UNION and UNION ALL?

Answer:

UNION removes duplicate records.  UNION ALL does not.

There is a performance hit when using UNION instead of UNION ALL, since the database server must do additional work to remove the duplicate rows. But usually , we don't want the duplicates especially when developing reports.


Question 8:

What are foreign key and super key?

Answer:

Foreign Key:

Foreign key maintains referential integrity  by enforcing a link between the data in two tables.
Foreign key in child table references the primary key in parent table.
The foreign key constraint prevents actions that would destroy the link between the child and parent table.

Super key : It is a column or a combination of columns which uniquely identifies a record in a table.

e.g.:

Super key stands for superset of a key. e.g. We have a table Book with columns:
Book (BookID, BookName, Author)

So, in this table we can have:


  • (BookID)
  • (BookID, BookName)
  • (BookID, BookName, Author)
  • (BookID, Author)
  • (BookName, Author)
as our super keys.

Each super key is able to uniquely identify each record.





That's all from this Interview.

Hope this post helps everybody in their job interviews.

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 !!


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