Thursday, February 27, 2020

Interview Questions on Java 8 - Part - II

Hi Friends,

In previous post on java 8 interview questions : Java 8 - Part - I , I shared multiple questions and answers.

I'm extending that post here in Part - II.

You can also read my interview questions-answers in I.T. companies from these posts:



Java 8 interview questions:

Question 1:

What are the benefits of using Streams?


Answer:

Streams were added in java 8 as part of java.util.stream package.

There are multiple benefits of using streams in java :

  • Using streams, we can process data in declarative way as we do in SQL.
  • Using parallel streams, we can use all available cores in the processor and process data parallely, which improves performance.
  • Using streams, we can compose functions and data flows through the functions.


Question 2:

Can we use streams with primitives?


Answer:

Yes, there are two ways to use stream on primitives:

  • Use wrapper classes.
  • Use primitive types of streams: IntStream, LongStream and DoubleStream.


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[] array , we get Stream<int[]> and then for getting ints from this stream, we use flatMapToInt(i-> Arrays.stream(i)) to get IntStream and then we can use either map() or forEach().



Question 4:

What is a boxed stream in java 8?

Answer:

If we want to convert stream of objects to collection, we can use:

List<String> list = Stream.of("a","b","c","d","e").collect(Collectors.toList());

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

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

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.

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

System.out.println(list);

O/P: [1,2,3,4,5]


Question 5:

What is the difference between sequential stream and parallel stream? 

Answer:

Parallel stream divides the task into many and run them in different threads, using multiple cores of the computer. It uses main thread along with ForkJoinPool.commonPool worker threads.


Sequential stream uses a single core. So, it uses only 1 thread that is main thread.



Question 6:

What are the characteristics of a stream?

Answer:

Below is the list of characteristics of streams in java 8:

  • Sequence of elements:  A stream provides a set of elements of specific types in a sequential manner. A stream computes elements on demand. It never stores the elements.
  • Source: Stream takes Collections, Arrays or I/O resources as input source.
  • Aggregate Operations: Stream supports aggregate operations  like filter, map, limit, reduce, find, match and so on.
  • Pipelining: Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations.
  • Automatic Iterations: Stream operations do the iterations internally over the source elements provided, in contrast to collections where explicit iteration is required.

Question 7:

Draw Stream lifecycle diagram.

Answer:






Question 8:


What is architecture of Steam?

Answer:







Question 9:

How streams are lazy?

Answer:

Streams are lazy because intermediate operations are not evaluated unless terminal operation is invoked.

Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream. The pipeline accumulates these newly created streams.
 

That's all for this post.

Thanks for reading !!




Monday, February 24, 2020

Interview Questions on Java 8 - Part I

Hi Friends,

In this post, I'm sharing interview questions asked on Java 8.

You  can also read other interview questions-answers from my other interviews:







Java 8 Interview Questions:


Question 1:

How to use Default method in java 8?


Answer:

Java 8 introduced default or "Defender methods" as a new feature which allows developers add new methods definitions in interface without breaking existing functionalities/implementation of these interfaces.

Lets take an example for understanding "How to use it":

public interface OldInterface{

    public void existingMethod();

    default public void newDefaultMethod(){

         System.out.println("Code goes here");
    }

}



public class OldImplementation implements OldInterface{

    public void existingMethod(){

    }

}

Now create instance of OldImplementation instance and call default method as:

OldImplemenattaion olI = new OldImplementation();
olI.newDefaultMethod();

Example of Default method added in Java JDK is forEach() which is added in Iterable and Stream interfaces as:

public interface Iterable<T>{

    default public void forEach(Consumer<? super T> action){
        for(T t : this)
            action.accept(t);
    }
}



Question 2:

Define Multiple inheritance ambiguity problem in Default methods.

Answer:


Since java class can implement multiple interfaces and each interface can define a default method with same method signature , therefore the inherited methods can conflict with each other.

Let's understand it through an example:

public interface InterfaceA{

    public void default method(){

    }

}


public interface InterfaceB{

    public void default method(){

    }
}

public class Implementation implements InterfaceA,  InterfaceB {

 

}

The above code will fail to compile.

In order to fix this, we need to provide default method implementation as:

public class Implementation implements InterfaceA,  InterfaceB {

    public void default method(){

    }

}

If we want to invoke default implementation provided by any of the super Interface, then we can do that as:

public class Implementation implements InterfaceA,  InterfaceB {

    public void default method(){
        Interface.super.method();
    }

}

Note: We can choose any default implementation or both as part of our new method.



Question 3:

What other method has been introduced in interface in Java 8?


Answer:

In java 8 , static method has also been introduced. These are called by interface name.
They are introduced to increase the degree of cohesion of a design by putting together all related methods in one single place without having to create an object.

For example, see below code:

public interface Vehicle{

    static int getPower(){
 
        return 0;
    }

}

Call it as:

Vehicle.getPower();



Question 4:

What is the difference between default method and regular method?

Answer:

Different between default method and regular method are as follows:


  • Default method comes with default keyword by default. Regular method doesn't use any such keyword.
  • Default method is defined in interface and an interface doesn't have any state, so default method cannot change the state of the object. While regular method can  change the state of the object by changing value of it's parameters.



Question 5:

How Lambda is useful in java?

Answer:

Lambda is a type of functional interface. A functional interface is an interface that has exact one abstract method. e.g. : Runnable, Callable, ActionListener, Comparator etc.

Lets' take an example to understand how Lambdas are useful in java:

@FunctionalInterface
public interface ITrade{

    public boolean check(Trade t);
}

So, above interface has only one abstract method that takes a Trade object.

Lets create a Lambda expression for this interface:

ITrade newTradeChecker = (t) -> t.getStatus().equals("new");

The real power of Lambdas come when we start creating a multitude of them representing real world behavioral functions as:


ITrade bigLambda = (t) -> t.getQuantity() > 13000;

ITrade smallLambda = (t) -> t.getStatus() < 10000;

Now, we have a class  filterTrades that will filter trades based on which Lambda we have passed for filetering.


private List<Trade> filterTrades(ITrade trade, List<Trade> trades){

    List<Trade> newTrades = new ArrayList<>();
 
    for(Trade t : trades){

        if(trade.check(t)){

            newTrade.add(t);
        }
    }
}

So, in this way, it will behave differently based on Lambda passed to filterTrades() method.


Question 6:

What are the differences between Lambda and anonymous class?

Answer:

Below is the list of differences between Lambda and anonymous class:


  • Usage of 'this' keyword:  In anonymous class, this keyword refers to anonymous class itself. While in Lambda, this keyword refers to enclosing class of Lambda.
  • Compilation: Anonymous class gets compiled to .class file in java. While Lambdas are compiled to private static methods in enclosing class. It uses invokedynamic bytecode instruction to bind this method dynamically.
  • Lambdas implement a functional interface, so implements only 1 method. Anonymous class can extend a class or implement any number of interfaces.



Question 7:

What are the types of Lambdas?

Answer:

There are two types of Lambdas in Java 8:

Non-capturing Lambdas: These lambdas only use fields inside their bodies, as:
    public class NonCapturingLambda{

        public static void main(String[] args){

           Runnable  nonCapLambda = () -> System.put.println("NonCapturingLambda");
           nonCapLambda.run();
        }
    }

Capturing Lambdas: These lambdas access fields outside their bodies, as:
    public class CapturingLambda{

        public static void main(String[] args){
         
           String str = "CapturingLambda";
           Runnable  capLambda = () -> System.put.println("CapturingLambda = "+str);
           capLambda.run();
        }
    }


That's all for this post. I'll share more questions in Part - II.

Thanks for reading.

Saturday, February 15, 2020

Java Interview @ Orange Mantra - Part 2

Hi Friends,
In this post, I'm sharing interview questions asked in Orange Mantra's 2nd round of interview.


You can also read other Interview questions-answers from my other interviews:




Question 1:

Integer i = 127;
Integer j = 127;

Integer ii = 128;
Integer kk = 128;

if( i == j){
    System.out.println("true");
}
else{
    System.out.println("false");
}

if(ii == kk){
    System.put.println("true");
}
else{
    System.out.println("false");
}

What will be the output?

Answer:

true
false


Question 2:

What is Serverless architecture?

Answer:

Serverless is a cloud computing execution model where the cloud provider dynamically manages the allocation and provisioning of servers.

A serverless application runs in stateless compute containers that are event-triggered , ephemeral(may last for one invocation) and fully managed by the cloud provider.

Pricing is based on the number of executions rather than pre-purchased compute capacity.

Our applications are installed in terms of cloud functions. There are multiple cloud services that act as Functions as a service [FaaS].


  • IBM OpenWhisk
  • AWS Lambda
  • Microsoft Azure Functions
  • Google Cloud Functions
  • Auth0 Webtask

So, serverless computing [or serverless for short] is an execution model where the cloud provider is responsible for executing a piece of code by dynamically allocating the resources and only charging for the amount of resources used to run the code.

The code typically runs inside stateless containers that can be triggered by a variety of events including Http requests, database events, file uploads, monitoring alerts etc. 



Question 3:

What happens when we call SpringApplication.run() method in main class of SpringBootApplication?


Answer:


Syntax of  the class containing main method is:

@SpringBootApplication
public class TestApplication{

    public static void main(String[] args){
   
        SpringApplication.run(TestApplication.class); // returns ConfigurableApplicationContext            instance
    }

}

When we run this class as a java application then our application gets started.

When this method is called, then Spring Container gets started.
Spring container once started is responsible for:


  • Creating all objects: This is done by component scan. As @SpringBootApplication is a combination of @Configuration , @ComponentScan and @EnableAutoConfiguration.
  • Dependency Injection
  • Managing the lifecycle of all beans. 

Steps executed under this method:


  • Application Context is started
  • Using application context , auto discovery occurs: @ComponentScan
  • All default configurations are setup i.e. based on dependencies mentioned, spring boot automatically sets up defaults.
  • An embedded servlet container  is started.[No need to setup a separate web server]. Note: Embedded servlet container is launched only if web is mentioned in a dependency. 



Question 4:

What are Spring Boot Starter projects. Name some of them?


Answer:

Starters are a set of dependency descriptors that we can include in our application. We get one-stop-shop for all required technologies in our application. without having to hunt through sample code and copy paste loads of dependency descriptors.

e.g.:  If we want to get started using Spring and JPA for database access, just include the sprint-boot- starter-data-jpa dependency in the project and we are good to go.

Below is a list of few starter projects provided by Spring Boot:


  • sprint-boot-starter-web
  • spring-boot-starter-data-jpa
  • spring-boot-starter-web-services
  • sprint-boot-starter-test
  • sprint-boot-starter-data-rest
  • spring-boot-starter-jdbc
  • spring-boot-starter-security


Question 5:

How does spring enables creating production ready applications in quick time?

Answer:

Spring Boot enables creating production ready applications by providing a few non-functional features out of the box like caching, monitoring, logging and embedded server.

Spring-boot-starter-actuator: For  monitoring and tracing of application

Spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat: To pick the choice of Embedded Servlet Container.

Spring-boot-starter-logging: For logging using Logback

Spring-boot-starter-cache: Enabling spring framework's caching support



Question 6:

What is the minimum baseline version for spring boot 1.5 and 2.1.0 versions?

Answer:

Java 8



Question 7:

How many ways are there to create ApplicationContext?

Answer:

If we are using xml configuration using application-context.xml then

ApplicationContext context = new ClassPathXmlApplicationContext("Path to xml file");


If we are using Java configuration, then:

ApplicationContext context = new AnnotationConfigApplicationContext(ConfigClass.class);



That's all for this interview post.
Hope this post helps everybody in their java interviews.
Thanks for reading!!

Sunday, February 9, 2020

Java Interview @ Aricent - Part 2

Hi friends,

In this post, I'm sharing interview questions asked in Aricent 2nd interview. This interview was @ an experience of 12 years.

You can also read actual interview questions asked in other companies:






Question 1:

What is the difference between map and flatMap in Java 8?

Answer:

map() method is used to map an object or entry in stream to some other value.
While flatMap() method , first applies map() on the entries and then flatten the result.

e.g.:
Suppose we have a string array with entries :
String[] strArray = {"12" , "46"};

And we have to find all the permutations of these strings.

So output with map() method will be :  [12, 21] , [46, 64].

While output with flatMap() method will be : [12,21,46,64]


Let's take another example:

List<Integer> evens = Arrays.asList(2,4,6,8);
List<Integer> odds = Arrays.asList(1,3,5,7);
List<Integer> primes = Arrays.asList(5,7,11,13,17);

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

System.out.println("List = "+numbers);


O/P: 2,4,6,8,1,3,5,7,5,7,11,13,17


Note: This output is possible only with use of flatMap() method.



Question 2:

What change has been done in HashMap performance in java 8 and how does that change is implemented?

Answer:

In HashMap, a customized LinkedList is used for each entry in underlying bucket. From Java 8, if length of LinkedList gets increased to some threshold, then this LinkedList is converted to Binary Search Tree, which increases performance by reducing search time.

This Binary search tree is constructed using hashcode values of keys. If the hashcode values are different then they are arranged in left or right subtrees. But if the hashcode value is same, in that case there is no such performance improvement.



Question 3:

What is the difference between PUT and PATCH?

Answer:

PUT is used to completely replace a resource at given URI.
While PATCH is used just for partial updation of a given resource at given URI.

Another difference is that while using PUT, we have to send the full payload as the request, while using PATCH , we can only send the parameters which we want to update.



Question 4:

Draw CI/CD pipeline process that you follow in your company.


Answer:




Explanation:

First part is Developer Machine where all the source code and Database scrips are written.
Now all these source code/DB scripts files are pushed to SCM[Source Control Management] like Git/GitHub/GitLab/Azure Repo/Bitbucket etc.

From there it goes to Build pipeline where all this code is compiled and generate a package file for the application [.dll or .jar].

Build Pipeline:

From here CD pipeline starts.

To build the package files, commands like "mvn package install"  or "mvn build" are run .

Also all the unit tests run here.
It also runs static code analyzer tool like Sonarqube.
It also includes configuration for generating scripts.



Release Pipeline:

Here built package files from build pipeline are deployed on multiple servers like QA server, Development server and Production server.
All the Integration tests run here.

QA team takes the build from here and run User Acceptance Testing.
Also deploys SQL scripts on Database server.



Question 5:

What is the upper limit for a payload to pass in the POST method?

Answer:

GET appends data to the service URI. But it's size should not exceed the maximum URL length.
However POST doesn't have any such limit.

So , theoretically , a user can pass unlimited data as the payload to POST method. But, if we consider a real use case, then sending POST with large payload will consume more bandwidth. It will take more time and present performance challenges to the server. Hence, a user should take action accordingly.


Question 6:

Suppose our REST API requires an int value and we send String "abcd" in query parameter , then what response we get?

Answer:

We get error : Not found.

"timestamp": "2019-01-17T18",
"status" : 404,
"error" : "Not found",

"message" : "JSON parse error: Cannot deserialize value of  type int from String \"abcd\": not a valid integer value;
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:


Question 7:

What are Spring Core annotations?

Answer:

Spring core annotations are following:

@Qualifier

@Autowired

@Required

@ComponentScan

@Configuration

@Bean

@Lazy

@Value



Question 8:

Explain Spring Data JPA vs Hibernate

Answer:

JPA: Java Persistence API which provide specification for creating, deleting, persisting and data management from java objects to relations [tables] in database.

Hibernate: There are various providers which implement JPA. Hibernate is one of them . So , we have other provider as well e.g.: Eclipse Link etc.

Spring Data JPA: This is another layer on top of JPA which spring provides to make coding easier.




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

Thanks for reading!!

Wednesday, February 5, 2020

Java Interview @ SAP

Hi Friends,

In this post, I'm sharing Java/REST/SQL interview questions in SAP.

You can also read my other real interview  in the below posts:





Question 1:

Draw REST Architecture


Answer:







Question 2:

Name core components of  HTTP request.


Answer:

Each HTTP request includes five key elements:


  • The verb which indicates HTTP methods such as GET, POST, PUT, DELETE.
  • URI: Stands for Uniform Resource Identifier. It is the identifier for the resource on server.
  • HTTP version which indicates HTTP version , for example -- HTTP v1.1
  • Request Header carries metadata  (as key-value pairs) from the HTTP request message. Metadata could be a client type, the format that client supports, message body format and cache settings.
  • Request Body: It indicates the message content or resource representation.



Question 3:

Explain the term statelessness with respect to RESTFUL Web service.


Answer:

In REST, ST itself defines State Transfer and statelessness means complete isolation. This means, the state of the client's application is never stored on the server.

In this process, the client sends all the information that is required for the server to fulfill the HTTP request that has been sent. Thus every client request and the response is independent of the other with complete assurance of providing required information.



Question 4:

State the core components of an HTTP response.

Answer:

Every HTTP response includes 4 key elements:


  • Status/Response code: Indicates server status for the resource present in HTTP request e.g. 404 means, resource not found and 200 means , response is OK.
  • HTTP Version
  • Response Header: Contains metadata for the HTTP response in the form of key-value pairs. e.g. content length, content type, response date and server type
  • Response Body: Indicates response message content or resource representation.



Question 5:

What is cloud and what are the benefits of Cloud Computing?

Answer:

A cloud is actually a collection of web servers [instead of single server] owned by 3rd party.  Cloud provides inexpensive, efficient and flexible alternative to computers.

Benefits of Cloud are:


  • No need of extra space required to keep all the hardware [Servers, Digital storage]
  • Companies don't need to buy software or software license for all it's employees. They just pay a small fees to the cloud computing company to let their employees access a suite of software online.
  • It also reduces IT problems and costs. 



Question 6:

class A{


}


class B extends A{


}

class C extends B{


}

public class MainClass{

    static void overloadedMethod(A a){
         System.out.println("One");
    }

    static void overloadedMethod(B b){

        System.out.println("Two");
    }


    static void overloadedMethod(Object obj){
     
        System.out.println("Three");
    }

    public static void main(String[] args){

        C c =  new C();
        overloadedMethod(c);

    }

}

Given above code, what will be the output?


Answer:

Output: Two

Explanation:  

In method overloading, more specific method is chosen over generic.



Question 7:

As  a best practice , what should be the maximum nesting level for associations in URI  (e.g. /vacations/{id}/reviews)?

Answer:

3



Question 8:

In a class, one method has two  overloaded forms.One form is defined as static and another form is defined as non-static. Is that method properly overloaded?

Answer:

Yes. That method is properly overloaded. Compiler checks only method signature to verify whether a particular method is properly overloaded or not. It doesn't check static or non-static feature of the method.



Question 9:

Method signature consists of which one out of below:

  1. Method name, return type and number of arguments
  2. Access modifier, method name and types of arguments
  3. Method name, number of arguments, types of arguments and order of arguments
  4. Return type, access modifier and order of arguments


Answer:

3



That's all for this interview post.
Hope this post helps everybody in their java interviews.
Thanks for reading !!


Tuesday, February 4, 2020

Java Interview @ GalaxE India

Hi All,

I hope you all have read my previous Java Interview posts:



Here, I'm sharing java Interview questions-answers asked in GalaxE.


Question 1:

What are Binary Literal?  How to use them in java?

Answer:

Binary Literals were introduced in java 7. Now using them, we don't need to convert binary to decimal or hexadecimal.

Binary Literals must be started with 0b or 0B.

Binary Literals are used in Protocols, Processors and bitmapped hardware devices.

Example showing their usage:

public class BLiterals{

     public int a = 0b0110;
     public byte b  = (byte) 0b0110;
     public long l = (long) 0b0110L;


    System.out.println("a = "+a);
    System.out.println("b = "+b);
    System.out.println("l = "+l);

}

Output:

a = 6
b = 6
l = 6

Question 2:

Which Application server have you used? Where does it occur in multi-tier architecture?
What benefits we get while using an Application server?

Answer:

I have used Weblogic server.








Weblogic server provide support for Network protocols [HTTPS, SOAP etc.]  It also provides data access and persistence from database server. It also supports SQL transactions for data integrity.

Weblogic also provides security.

So means, when we use Weblogic server , we don't have to care about protocol, security, database integrity, transactions etc. All these are handled by Weblogic itself.
We just have to  focus on business logic.



Question 3:

Write algorithm for Level-Order traversal of a Binary tree.

Answer:

Level-Order traversal means moving from root to leaf step-by step horizontally.

Algorithm for Level-Order Traversal:


  1. Check if root node is empty. If yes, then return.
  2. If root not null, create a queue and put root node in the queue.
  3. Take a while loop on if Queue is not empty.
  4. store the size of queue in a variable named size. 
  5. Create another while loop inside outer loop. IN this loop, check the value of size variable. It should be > 0. Use size-- in while loop.
  6. Now print element[node] from queue. And put all child nodes of that node on queue if these are not null. 
  7. Continue from step 5 until it is false and then continue from step 3.


Question 4:

Explain Java Memory Model.

Answer:








Question 5:

Explain JVM memory structure.

Answer:

As per the spec, JVM is divided into 5 virtual memory segments:


  • Heap
  • Method [Non-heap]
  • JVM Stack
  • PC Registers
  • Native Stack


JVM Stack:


  • Has a lot to do with methods in java classes
  • Stores local variables and regulates method invocation, partial result and return values.
  • Each thread in java has it's own copy of stack and is not accessible to other threads.
  • Tuned using -Xss JVM option. 

Native Stack:


  • Used for native methods [Non-java code]


Question 6:

What are the common Java Heap related issues?
Answer:

Below is the list of all java heap related issues which occur in java applications at runtime.

  • 'OutOfMemory' error due to insufficient Heap
    • To identify it, we can use JvisualVM
    • To fix it, we can increase heap size or we can revisit the code to see why the demand is high in first place.
  • Poor application response time due to long garbage collection pauses
    • TO identify it, we can use JvisualVM
    • To fix this, we can tune GC [Garbage Collector].
  • OutOfMemory error due to memory leak
    • To identify it, we can use JvisualVM
    • To fix it, we need to analyse the code and correct it.
  • Heap Fragmentation
    • It is due to when , small and large objects are allocated in a mixed fashion. To some extent, we cannot avoid heap fragmentation -- over time, heap will get fragmented.
    • To identify, we see poor application response times, longer GC pauses and in some cases 'OutOfMemory' errors.
    • To fix it, tuning can help.


Question 7:

What are the ways to capture Java Heap dump?


Answer:

There are great tools like Eclipse MAT and Heap Hero to analyze Heap dumps. However we need to provide these tools with heap dumps captured in the correct format.

Options to capture  heap dump are:


  • Jmap
  • Jcmd
  • JvisualVM
  • JMX


Question 8:

Why reflection is slow? 

Answer:

Reflection needs to inspect metadata in bytecode  instead of just using precompiled addresses and constants.

Everything requires to be searched. That's why reflection is slow.



That's all for this interview post.
Hope this post helps everybody in their java interviews.
Thanks for reading!!




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


Sunday, February 2, 2020

Java Interview in Concirrus

Hi Friends,

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

You can read Questions-Answers asked in other interviews as well here:




Here are the list of questions asked in Concirrus:

Question 1:

How Singleton is handled in Deserialization? What, if we use clone() in singleton?

Answer:

When we serialize Singleton instance and try to deserialize it, then if we call deserialization multiple times, then it can result in more than one instance of singleton class.

To avoid this problem, we can implement readResolve() method. This readResolve() method is called immediately after an object of this class is deserialized, Means when ObjectInputStream has read an object from input stream and is preparing to return it to the caller, then it checks whether the readResolve() method is implemented or not.

Note: Both objects [Read by ObjectInputStream and returned by readResolve() method] should be compatible [Identical] else ClassCastException is thrown.


Implementation of readResolve() method:

protected void readResolve(){
    // Instead of the object we are on, return the class variable singleton.
    return singletonInstance;
}


What if we use clone() method in Singleton?

Answer:

 If we override clone() method in singleton class, then we must throw CloneNotSupportedException from this method.


Question 2:

How HashMap works?

Answer:

HashMap in java contains key-value pairs. It doesn't maintain the insertion order of key-value pairs.

Whenever a key-value pair is required to be stored in HashMap, The overridden hashcode() method [if there is one] is used to calculate the hashcode and then Object's class hash() method is called on that value which provides the index in underlying bucket of HashMap.

HashMap uses array based structure to store each key-value entry. That array is called bucket and each location in bucket maintains a simple optimized LinkedList.

So, after the index in the bucket is found, then if there is no entry matching the key in that bucket indexed LinkedList, then that key-value pair is stored. Else , if there is some key-value pairs already there in the LinkedList, then key is compared to every key in LinkedList using equals() method and if a match found, then the value for that key is replaced with new value.

If there is no match found, then that new key-value pair is stored as a new entry in HashMap.



Question 3:

Create Immutable class?

Answer:

There are 2 ways to create immutable class in java:


  • Make the class final and all it's instance variable as final. So they can be initialized in constructor only. 
  • Make all the instance variables private and don't change them except constructor. Don't provide any setter methods for them. Make the getter methods final so that subclasses don't override these getter methods and return other values.




Question 4:

Detect loop in LinkedList


Answer:

I wrote the entire code for this problem.
It took almost 25-30 minutes.

I'm sharing the source code here :

class LinkedList{

    static Node head;

    static class Node{
        int data;
        Node next;

        Node(int d){
            data = d;
            next = null;
        }
    }

    int detectLoop(Node node){

        Node slow = node, fast = node;
   
        while(slow != null && fast != null && fast.next != null){

            slow = slow.next;
            fast = fast.next.next;

            // If fast node reaches slow node, means there is a loop.
            if(slow == fast){

                return 1;
            }
       }
       return 0;
}


}

Question 5:

Dynamically confiuring a new microservice. Does it require deploying all microservices, if we use static way?

Answer:

No. We can just deploy our microservice to some host and it will register itself with Service Registry. From there it can be discovered by other microservices and also it can discover other required microservices.

And this way, communication can be established among various microservices without any external configuration.


Question 6:

Is there any loophole in using Git-> Jenkins CI/CD way?

Answer:

There is no loophole in Git-> Jenkins CI/CD way. The problems/loopholes  occur in the way these tools are configured by Software Delivery teams [DevOps].

There are multiple things that can cause problems in using Jenkins as CI/CD tool:


  • Jenkins has too many plugins
  • Jenkins was not designed for the Docker age
  • Jenkins doesn't support microservices well

Jenkins has too many plugins:

Plugins are good when they are used properly and efficiently. Plugins give users the choice to add various features  to the tools they use.
But in Jenkins, for achieving every single basic task, you need a separate plugin. 

e.g.: for creating a build for Docker environment, you need a plugin.
To pull code from Github, you need a plugin.



Jenkins was not designed for the Docker age:

CI servers don't match with Docker container infrastructure easily. They require multiple plugins to integrate with Docker. There are more than 14 plugins with Docker in their names. And almost 6 of them are for core Docker platform.


Question 7:

Design TinyURL algorithm.


Answer:

I designed it as per my knowledge.



Question 8:

Which Docker command is used to know the list of running containers?

Answer:

docker ps


Question 9:

Difference between GitHub and GitLab?

Answer:






That's all for this post of interview questions.

Hope this post helps everybody in clearing 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...