Thursday, May 28, 2020

Interview @ 1mg : Round -1


Hi Friends, In this post, I'm sharing Java interview questions asked in 1mg in round - 1.

You can also go through my other java interview posts:


Interview Questions @ 1mg:

Question 1:

What is System.out, System.in and System.err?


Answer:

out, in and err all are fields in System class.

out: The standard output stream.This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
Basically, it gives PrintStream. And all print() methods belong to class PrintStream.

public static final PrintStream out

in: The standard input Stream. This stream is already open and ready to supply input data. typically this stream corresponds to keyboard input or other input source specified by the host environment or user.

public static final InputStream in

err: The standard error output stream. This stream is already open and ready to accept output data.
By convention, this output stream is used to display error messages.

public static final PrintStream err 




Question 2:

What is the difference between Class.forName() and Class.forName().newInstance() methods?

Answer:

Lets take an example to understand the difference better:

public class Demo{

    public Demo(){

        
    }

    public static void main(String[] args){

        Class clazz = Class.forName("Demo");
        Demo demo = (Demo)clazz.newInstance();
    }

}

Class.forName() returns the Class object associated with the class or interface with the given string name.

Then, calling clazz.newInstance() creates a new instance of the class represented by this Class object.
This class is instantiated as if by a new expression with an empty argument list.
 



Question 3:

Why non-static variables are not allowed in static methods?

Answer:


non-static variables means instance variables and they are only initialized when an instance is created. As static methods can be called without creating an instance , so accessing non-initialized instance variable is wrong as instance doesn't exist.

So, only way to access non-static variable in static method is that , just create instance of class in static method and access that variable.

public class StaticTest{

    private int count = 0;
   
    public static void main(String[] args){

        StaticTest test = new StaticTest();

        test.count++;

    }

}




Question 4:

What is the difference between HTTP HEAD and GET verbs?

Answer:

HTTP HEAD is almost identical to GET, but without the response body. Means in HTTP HEAD, we don't get any response body.

In other words, if GET /users returns a list of users, then HEAD /users will make the same request , but will not return the list of users.

HEAD requests are useful for checking what a GET request will return before actually making a GET request - like before downloading a large file or response body. 




Question 5:

What is the difference between HTTP GET and POST methods?

Answer:

There are multiple differences between GET and POST methods:

  • GET is used to request data from a specified resource. POST is used to send data to server to create a resource.
  • GET requests can be cached. POST requests cannot be cached.
  • GET requests remain in the browser history. POST requests do not remain in the browser history.
  • GET requests can be bookmarked. POST requests cannot be bookmarked.
  • GET requests have length restrictions. POST requests have no restrictions on data length. 




Question 6:

Is there any speed increase while indexing a table?  And will indexing every column defeat the purpose of indexing?

Answer:

Indexing any table, either memory or file system based, will speed up queries that select or sort results based on that column. 
This is because the index works like a tree structure and the search distance depends upon the depth of the tree, which increases a lot slower than the row count of the column.

Indexing every column doesn't defeat the purpose of the index, but it will slow up inserts and updates because those changes will cause an update of every index of that table.
Also, the indexes take up space on the database server.  




Question 7:

What is covariant return  type?

Answer:

In covariant return type, parent's instances can be replaced with child's instances.

e.g.:


class WildAnimal{

    public String willYouBite(){
        return "Yes";
    }

}

class Lion extends WildAnimal{

    public String whoAreYou(){

        return "Lion";
    }

}


class BengalTiger extends WildAnimal{

    public String whoAreYou(){

       return "Tiger";
    }
}


class Zoo{

    public WildAnimal getWildAnimal(){

        return new WildAnimal();
    }

}


class AfricaZoo extends Zoo{

    @Override
    public Lion getWildAnimal(){

        return new Lion();
    }

}

class IndiaZoo extends Zoo{

    @Override
    public BengalTiger getWildAnimal(){

        return new BengalTiger();
    }
}


public class Covariant{

    public static void main(String[] args){

        AfricaZoo africaZoo = new AfricaZoo();
        System.out.println(africaZoo.getWildAnimal().whoAreYou());
    }

}

So, in class AfricaZoo, parent class WildAnimal is replaced by child class Lion while overriding method.




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

Sunday, May 24, 2020

Java Interview @ Altran

Hi friends,

In this post I'm sharing Java interview questions asked in Altran.
You may also find my other interview posts very useful.



Java Interview Questions asked in Altran:

Question 1:

How does HTTPS work?


Answer:

In HTTPS, every message is encrypted or decrypted by use of public/private keys.

So, we need to trust that public key cryptography and signature works.

  • Any message encrypted with Google's public key can only be decrypted with Google's private key.
  • Anyone with access to Google's public key can verify that a message (signature) could only have been created by someone with access to Google's private key.









Question 2:

What is a Certificate Authority? How is a certificate signed?


Answer:

Suppose youtube.com web server uses HTTP currently. And now youtube wants to secure communication using HTTPS.

Also there is Google CA which is considered as a trusted certificate authority.

As any party envolved in public key cryptography , the google certificate authority has a private key and a public key.

As youtube.com wants to communicate using HTTPS, they also need to create a new pair: public key and private key.

Now youtube.com web server creates a Certificate signing request with this key pair.





 

So most of the browsers [when they are delivered] has a list of these certificates issued by known Certificate Authorities [Google, Symantec, Thwate].

So, when we try to open youtube.com, then as youtube.com uses HTTPS, it sends certificate to the browser. As browser knows the Google's public key [as it is having that certificate with Google's public key], so it can use that key to know that this certificate is actually signed by trusted certificate authority [Google].

Means. now that public key can be used to create and encrypt a secret key which will then be used in symmetric encryption.




Question 3:

Explain the difference between HTTP, HTTPS, SSL and TLS?

Answer:

HTTP: Hyper Text Transfer Protocol

Using this protocol, data is transferred in clear text.

HTTPS:  Secure Hypertext Transfer Protocol
 
Means, HTTP with a security feature.

Encrypts the data that is being retrieved by HTTP.  So, it uses encryption algorithms to encrypt the data. 

HTTPS uses SSL [Secure Socket Layer] protocol to protect the data.


SSL: This protocol is used to ensure security on the internet. Uses public key encryption to secure data.


TLS: Transport Layer Security

It is the latest industry standard cryptographic protocol. It is a successor to SSL. 
And it is based on same specifications. 
And like SSL, it also authenticates the server, client and encrypts the data.




Question 4:

What are the collection types in hibernate?


Answer:

Below is the list of collection types in hibernate:

  • Bag
  • List
  • Map
  • Array
  • Set


Question 5:

What is hibernate proxy?

Answer:

Mapping of classes can be made into a proxy instead of a table.
A proxy is returned when actually a load() is called on a session. The proxy contains actual method to load the data.

The proxy is created by default by hibernate for mapping a class to a file.



Question 6:

What is the difference between load() and get() methods in hibernate?

Answer:

Hibernate's session interface provides several overloaded load() [It will not hit database] methods for loading entities. Each load() method requires the object's primary key as an identifier and it is mandatory to provide it.

In addition to the ID, hibernate also needs to know which class or entity name to use to find the object with that ID.

In case of get() method, we will get return value as NULL if identifier is absent.
But in case of load() method, we will get a runtime exception [ObjectNotFoundException].

When we call load() on hibernate's session object, then hibernate doesn't make a call to database. It creates and returns a proxy object. Now, when some state is fetched from the proxy object, then hibernate issues the appropriate SQL statement to database and builds the real persistent object.

So, when actual data is requested using proxy object  and if no data exist for the identifier [id], then ObjectNotFoundException is thrown.


On the other hand, when we call get() method on hibernate's session object, then hibernate immediately issues a SQL statement to the database to fetch associated data  [usually a row in database] to rebuild the requested persistent object.
So, if no data is found for the requested identifier [id], the method will return null.
 



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





Saturday, May 23, 2020

Multithreading Interview in Ericsson

Hi Friends, 
In this post I'm sharing multithreading interview questions asked in Ericsson.

My other interview posts also help in clearing the java interview rounds.
You may find below links very helpful in any java interview.

Java Interview Questions and Answers:



Question 1:

Can a thread acquire multiple locks at the same time and how?

Answer:

Yes, a thread can acquire locks on multiple objects at the same time.
Also, a thread can acquire lock on the same object multiple times.

Locks obtained using synchronized are implicitly reentrant. 

Whenever we use nested synchronized blocks with 2 different objects, then the same thread can acquire lock on both of these objects. But care needs to be taken in this case, as if we take two pairs of synchronized blocks with different order of similar objects, then it may cause deadlock.




Question 2:

What are the steps to avoid deadlock in java programs?

Answer:

There are multiple ways in which we can avoid deadlocks:

  • Avoid using nested synchronized blocks
  • Always request and release locks in the same order.
  • Use synchronization only whenever required.
  • If two threads are waiting for each other to release shared resources, then this issue can be resolved by letting each waiting thread retry the operation at random interval until they successfully acquire the resource.  
  • Do not perform operations that can block while holding a lock. e.g. Do not perform file I/O over the network while holding a lock.



Question 3:

When we call Thread object's run() method, then in which thread that run() method gets executed?

Answer:

Calling run() method on Thread's object will cause execution of that method in current thread.

If a thread object was constructed by instantiating the subclass of Thread and fails to override run() method, then any calls to the run() method will invoke Thread.run(), which does nothing.

So, we should never call run() method on thread object.  




Question 4:

When we can and should use ThreadGroup?

Answer:

Each thread in java is assigned to one ThreadGroup upon it's creation. These groups are implemented by java.lang.ThreadGroup class.

When thread group name is not specified, the main default thread group is assigned by JVM.

ThreadGroups are useful for keeping threads organized.

There are few useful methods which can be used for specific use cases.


ThreadGroup.activeCount():

  •     Returns an estimated number of active threads in the current thread's thread group and it's subgroups.


ThreadGroup.enumerate():

  • It copies into the specified array every active thread in this thread group and it's subgroups. 




Question 5:

How to decide which method to call : notify() or notifyAll() ?

Answer:

Whenever we call notify() or notifyAll() methods, it is guaranteed that only one thread will get the lock and resume execution.

Calling notify() is permitted under following conditions:

  • All waiting threads have identical condition predicates.
  • All threads perform the same set of operations after waking up. That is, any one thread can be selected  to wake up and resume for a single invocation of notify.
  • Only one thread is required to wake upon the notification.




Question 6:

Why to use Thread pool for handling multiple tasks?


Answer:

Thread Pools allows a system to limit the number of simultaneous requests that it process to a number that it can comfortable serve.

If we don't use Thread Pool then, for every request, creating a new thread consumes a lot of time and resources and for task processing.

Describing here some of the benefits of using Thread Pool:

  • Thread pool minimizes the overhead of thread lifecycle management because the threads in a thread pool can be reused and can be efficiently added or removed.
  •  It also reduces the time and resources required for thread creation.
  • It also ensure graceful degradation of service when traffic bursts.  



Question 7:

What is bounded thread pool and what happens when we execute interdependent tasks in bounded thread pool?

Answer:

A bounded thread pool is a pool in which we specify an upper limit on the number of threads that can currently execute in a thread pool.

We should not use bounded thread pool to execute tasks that depend on the completion of other tasks in the pool.

A form of deadlock called thread-starvation deadlock arises when all the threads executing in the pool are blocked on tasks that are waiting on an internal queue for an available thread in which to execute.




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


Sunday, May 17, 2020

Code Review Practices

Code Review Practices:

Hi Friends, In this post I'm sharing the Java Code Review Checklist which should be performed while doing code review.

While doing the code review, multiple factors are taken into account : Clean code, Security, performance, General points etc. 

I'm explaining each one of them below:

Java Code Review Checklist:

Clean Code:

  • Use intention-revealing names
    •  Names should be such that, they reveal the purpose.

  • Use solution-problem domain names
    • Names should be such that they tell about the actual solution or problem.

  • Classes should be small
    • Keep the code in a class as less as possible and create other classes or subclasses for specific purpose.

  • Functions should be small
    • Always break the functions in small. 

  • Functions should do one thing
    • Keep one separate function for each action.

  • Don't repeat yourself (Avoid duplication)
    • Don't write duplicate codes. Check the entire code before writing the same code twice in the project.

  • Explain yourself in code : 
    • Write proper Class level and method level Comments.

  • Use exceptions rather than return codes 

  • Don't return null
    • Never return null values from a function.


Security:

  • Make class final if not being used for inheritance
  • Avoid duplication of code
  • Minimize the accessibility of classes and members
  • Document security related information
  • Input into a system should be checked for valid data size and range
  • Release resources[Streams , Connections] in all cases.
  • Purge sensitive information from exceptions
  • Don't log highly sensitive information
  • Avoid dynamic SQL, use prepared statement
  • Limit the accessibility of packages, classes interfaces, methods and fields.
  • Avoid exposing constructors of sensitive classes.
  • Avoid serialization of sensitive classes
  • Only use JNI when necessary 

Performance:

  • Avoid excessive synchronization
    • Don't use synchronize constructs unneccessarily
  • Keep synchronized sections small
  • Beware the performance of String concatenations
    • Avoid joining strings as much as possible.
  • Avoid creating unnecessary objects.
    • Try to create only local objects and also create them based on actual need.

General:

  • Don't ignore exceptions
  • Return empty Arrays or Collections , not nulls
  • In public classes, use accessor methods not public methods
  • Avoid finalizers
  • Refer to objects by their interfaces
  • Always override toString()
  • Document thread safety
  • Use marker interfaces to define types

Static Code Analysis:

  • Check static code analyzer report for the classes added/modified



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






Monday, May 4, 2020

Java Technical Architect interview : Round - 2

Hi Friends,

In this post, I'm sharing Java Technical Architect interview questions asked in 2nd round.

You can also go through my other interview posts:





Question 1:

What is the difference in using Eureka and spring cloud consul?

Answer:

Eureka and Spring cloud Consul are both Service Discovery tools.
Difference between them lie in multiple factors.

The architecture of Eureka is primarily client/server with a set of eureka servers per datacentre , usually one per availability zone.
Typically clients of eureka use an embedded SDK to register and discover services.

Eureka provides a weak consistent view of services using best effort replication. When a client registers with a server , that server will make an attempt to replicate to the other servers but provides no guarantee.
Service registrations have a short Time-To-Live, requiring clients to heartbeat with the servers. Unhealthy services or nodes will stop heartbeating, causing them to timeout and be removed from the registry.


Consul provides a super set of features, including richer health checking, key/value store and multi datacentre awareness. Consul requires a set of servers in each datacentre , along with an agent on each client, similar to using a sidecar like Ribbon. The Consul agent allows most applications to be consul unaware, performing the service registration via configuration files and discovery via DNS or load balancer sidecars.

Consul provides a strong consistency guarantee since servers replicate state using the Raft protocol. Consul supports a rich set of health checks.
Client nodes in Consul participate in a gossip based health check , which distributes the work of health checking, unlike centralized heartbeating which becomes a scalability challenge.

In Consul, discovery requests are directed to the elected consul leader which allows them to be strongly consistent by default.

The strongly consistent nature of Consul means it can be used as a locking service for cluster coordination.  Eureka does not provide similar guarantee  and typically requires running ZooKeeper for services that need to perform coordination or have stronger consistency needs.



Question 2:

How many types of containers are there in spring framework?


Answer:

There are two types of  Spring IOC containers:


  • BeanFactory Container
  • ApplicationContext Container







Spring BeanFactory container is the simplest container which provides basic support for DI.
It is defined by org.springframeworkbeans.factory.BeanFactory interface. XMLBeanFactory is the main implementation of this interface. It reads configuration metadata from xml files for creating a fully configured application.

BeanFactory container is preferred where resources are limited to mobile devices or applet based applications.

Spring ApplicationContext Container:

It is defined by org.springframework.context.ApplicationContext interface.
The ApplicationContext container has all the functionalities of BeanFactory container. It is generally recommended over BeanFactory container.

The most common implementations are :


  • FileSystemXmlApplicationContext
  • ClassPathXmlApplicationContext
  • WebXmlApplicationContext







Question 3:

What is the difference between @Controller and @RestController?


Answer:

@RestController = @Controller + @ResponseBody

@RestController was added in Spring 4.

@Controller : The job of @Controller is to create a map of model object and find a view.

@ResponseBody: It will just append the result object as JSON or XML in Http response.

@RestController : It simply return the object and object data is directly written into HTTP response as JSON or XML.



Question 4:

What is the difference between @RequestParam and @RequestAttribute?

Answer:

@RequestParam:

This annotation is used to access the query parameters from the HTTP request URL. e.g.:

http://example.com?param1=1&param2=2

In this URL, param1 and param2 are query parameters and they are accessed in methods like:

@RequestMapping("/")
public void method(@RequestParam("param1") String par){

}


@RequestAttribute:

It is used to access objects which have been populated on the server-side  but during the same HTTP request.
 e.g.:

We want to maintain a counter to know the number of visits to that page or number of requests made to a specific URL. So, in this case , we take an interceptor with AtomicInteger to increment the counter on every request.

e.g.:

The Interceptor:

public class Counter  extends HandlerInterceptorAdapter{

    private AtomicInteger counter = new AtomicInteger(0);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{

        request.setAttribute("visitorCounter", counter.incrementAndGet());
    }
 
}

The Controller class:

public class CounterController{

    @RequestMapping("/")
    @ResponseBody
    public String handle(@RequestAttribute("visitorCounter") Integer counter){

        // code here.......
    }
}



That's all for this post.
Hope this post helps everyone in their interview rounds.

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