Monday, January 27, 2020

Interview @ NexGen Solutions

Hi Friends,

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

You can also go through my other real time interviews:

Interview @ Dew Solutions
Interview @ RBS
Interview @ Aricent



Question 1: What is the benefit of Executor framework?


Answer:

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


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




Question 2: Asked me to write custom ArrayList.

//You can write your own implementation


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

Answer:

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


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



Question 4:

How did you use Amazon EC2?

Answer:

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



Question 5:

What is the benefit of Generics in java?

Answer:

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



Question 6:

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

Answer:

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


Question 7: Asked about my last project.

Answer:

I explained it.


Question 8:

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

Answer:

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

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

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

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





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

Thanks for reading.




Tuesday, January 21, 2020

Java Interview @ CapGemini

Hi Friends,

I hope you have read my previous posts on Java interviews:


In this post, I'm sharing java questions asked in Aricent @ experience of 11 years.




Question 1:

How to handle transaction in Spring?

Answer:

In Spring, there are two ways of managing transactions:


  • Programmatically manage by writing custom code
  • Using Spring to manage transaction
    • Programmatic Transaction management
    • Declarative Transaction management


Programmatically manage by writing custom code:

EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistance_unit_name");
EntityManager entityManager = factory.createEntityManager();
Transaction transaction = entityManager.getTransaction();

try{
    transaction.begin();
    //..........Business logic
    transaction.commit();
}
catch(Exception e){
    transaction.rollback();
    throw e;
}

Pros:

  • The scope of the transaction is very clear in the code
Cons:
  • It's repetitive and error prone
  • Any error can have a very high impact
  • A lot of boilerplate code needs to be written and if you want to call any another method from this method, then again you need to manage it in the code.


Using Spring to manage transaction:

1. Programmatic Transaction Management:
  • Using the transaction template
  • Using a PlatformTransactionManager implementation directly
2. Declarative Transaction




Question 2:

What is ORM and how to use it?

Answer:

ORM means Object Relational Mapping. It is a tool that helps in interacting with the database.

for example JPA is an ORM  which specifies some specifications which needs to be implemented.
In Spring, Hibernate is the implementation of JPA specifications.




So using ORM, Java object is mapped to relational table in database.




Question 3:

What is Heap dump?

Answer:

Heap Dump:  It is a snapshot of the memory of a java process.
This snapshot contains information about java objects and classes in the heap at the moment the snapshot is triggered.

Typically , a full GC is triggered before the heap dump is written, so the heap dump contains information about the remaining objects in the heap.

Typical information in a heap dump are:

  • All objects: Class, fields, primitive values and references
  • All Classes: Class Loader, name, super class and static fields
  • Garbage collection roots: It is an object that is accessible from outside the heap.




Question 4:

Memory management in Java 8?

Answer:





Perm Gen in java 7 and earlier version has a default maximum size of 64 MB for 32-bit machine and 84 MB for 64-bit machine.
While default maximum size for metaspace is unlimited.

In java 8 ,we can set the initial and maximum size of metaspace using:

-XX:MetaspaceSize = N : Sets the initial and minimum size of metaspace
-XX:MaxMetaspaceSize=N : Sets the maximum size of the metaspace



Question 5:

Difference between Serial and Parallel streams.


Answer:

Parallel streams divide 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:

How to find OutOfMemoryError in production app? And how to avoid this error immediately for long time?


Answer:

If we face OutOfMemoryError in production and we cannot really reason about it from stacktraces or logs, we need to analyze what was in there.

Get the VM Heap dump on OOM:


  • -XX:+HeapDumpOnOutOfMemoryError
  • -XX:HeapDumpPath="/tmp"
And use that for analysis. We can use memory analyzer tool for this.

How to avoid this error immediately for long time?

We can increase Heap space using -XX argument  for a while and it will work fine.


Question 7:

What is internal structure of heap memory?


Answer:






Question 8:

How to configure GC in Java application?

Answer:

GC tuning is only required when we have not set memory size in the application and too many Timeout logs are printed.






Question 9:

What are Serial and Parallel GC's?


Answer:

Serial Collector:

  • Used for single threaded environments [32-bit Windows] and apps that use small heap
  • It stops all threads when it is running. Means it is not suitable for server environment.
  • We can use it by turning on the -XX:+UseSerialGC JVM argument.

Parallel Collector:
  • This is JVM's default garbage collector
  • It uses multiple threads to scan through and compact the heap and speeds up garbage collection.
  • The downside is that it will stop application threads when performing either a minor GC or full GC.
  • It is best suited for apps that can tolerate application pauses.
  • Although it is default collector, but it can be configured using -XX:UseParallelGC JVM argument



Question 10:


What is Java Memory model?


Answer:






That's all for this interview.

Thanks for reading.

Thursday, January 16, 2020

Java Interview @ Dew Solutions

Hi  Friends,

In this post , I'm sharing the Java interview questions asked in Dew Solutions recently.


Question 1:

Java is pass by value or reference.


Answer:

Everything in java is pass-by-value.
When we pass object reference to some method, we actually pass address of that reference which in turn contains memory address of actual object.
And as  we know, memory address is a value, so means, we always use pass-by-value in java.

e.g.:

public static void main(String[] args){

    Book book = new Book("Java");
    Book newBook = book;

    change(book);
    book.getName();// Prints Java
 
}

public void change(Book book){
    book.getName(); //Prints Java

    book = new Book("Angular");
    book.getName();// Prints Angular
}
So here, what we see Book name doesn't change after change() method, because passed book reference in change() method now points to new Book Object with value "Angular".


Now, lets look at another example:

public static void main(String[] args){

    Book book = new Book("Java");
    Book newBook = book;

    change(book);
    book.getName();//Prints .Net
}

public void change(Book book){
    book.getName();//Prints Java

    book.setName(".Net");
}

Here, what we see, value of book object after change() method call has been changed to .Net. It is because book reference in change() method still contains memory address of Book object with java as value.



Question 2:

We have multiple Employee objects and we need to store these objects in TreeMap. What problems we can face while storing Employee objects?

Answer:

We will get error at runtime : "No suitable method found for sort(List<Employee>)".
It is because Employee class doesn't implement the Comparable interface so the sort() method cannot compare the objects.

As TreeMap stores object in Ascending order by default using natural ordering. So, each object which needs to be stored in TreeMap should implement Comparable interface or  Comparator interface.



Question 3:

What is Callable interface and how it is similar/different to/from Runnable?

Answer:

Callable interface is just like Runnable interface.

Difference between Callable and Runnable is given below:


  • Runnable is defined in Java 1.0  . While Callable was introduced in Java 5.
  • Callable includes call() method which returns object and also throws Checked exception. On the other hand , Runnable's run() method neither return any value nor throws any Checked exception. 
  • Runnable instance can be passed to a thread. While Callable instance can't be passed to a thread.

Similarities between Runnable and Callable:

  • Both are used to encapsulate code which needs to be executed parallely in separate thread.
  • Both interfaces can be used with Executor framework introduced in java 5.
  • Both includes single abstract method. Means , both can be used in Lambda expressions in java 8.



Question 4:

Can HashSet store duplicate objects?


Answer:

No, HashSet cannot store duplicate objects. As HashSet is implementation of Set interface and Set interface is meant to store unique elements. That's why HashSet doesn't store duplicate objects.


Question 5:

SQL query to find employee with highest salary and corresponding department.


Answer:

select department , max(salary) from employee
                               group by department;


Question 6:

Design the architecture of Vending machine?

Answer:







Question 7:

Describe one problem that you have solved in production build?

Answer:

In my previous company, client complained about slowness in the system performance.
We tracked the logs and found there was problem with some memory leaks happening.

We just immediately asked client to increase the JVM heap size for the moment so that it worked  and later on we corrected the problem by removing all the memory leaks in the code.



Question 8: Why to use Lock in multithreading? What are the locking mechanisms available in java?


Answer:

Lock is required in multithreading to properly distribute access of Monitor associated with an object among multiple threads.
If we don't use Locks, then multiple threads will try to acquire shared resources and we will get corrupted outputs from threads.


Locking mechanisms available in java are:


  • synchronized block
  • synchronized methods
  • Read/Write lock
  • Atomic classes
  • final classes


That's all about this interview.

Hope this post helps everybody in interviews.

Thanks for reading.

Friday, January 10, 2020

Java/Android Interview @ BirdEye

Hi Friends,

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



Question 1:

Print all unique permutations on a String?


Answer:







Question 2:

Write Algorithm for custom BlockingQueue.

Answer:

Algorithm steps:


  • Define an array to store elements for queue. Specify the initial size for that array.
  • Use Lock and conditions objects to create custom blocking queue.
  • Define two methods , put() and take().
  • While putting the elements in queue, check the size of array. If it is full, then the producer will wait for the queue to have some space.
  • While consuming element from queue, if the queue is empty, then consumer will wait for the queue to have some objects in it. 

Packages to be included:

java.util.concurrent.locks.Condition;
java.util.concurrent.locks.Lock;
java.util.concurrent.locks.ReentrantLock;


Question 3:

Singleton and Synchronization question:

If Thread1 calls synchronized method in Singleton class, then can another thread call getInstance() method [If synchronize(Singleton.class) is 1st statement in getInstance() method] of singleton class?


Answer 3:

Yes, another thread can call getInstance() method of singleton class. It is because, this time thread will acquire lock on Class object [Singleton.class].

So first thread acquired lock on Singleton instance and this another thread will acquire lock on Singleton Class's object.



Question 4:

Print all edge/corner nodes of a binary tree.

Answer:



Follow Level order traversal of binary tree. So , while doing level order traversal, if the current node happens to be the first node or last node in current level, print it.

void print(Node *root){

    //return if tree is empty.
    if(root == null)
        return;

    // Create an empty queue to store tree nodes.

    Queue<Node*> q;

    //enqueue root node
    q.push(root);

    // run till queue is not empty

    while(!q.empty()){

        //get size of current level
        int size = q.size();
        int n = size;

        //Process all noes present in current level
        while(n--){
         
             Node* node = q.front();
             q.pop();

              // If corner node found, print it.
              if(n == size-1 || n == 0)
                  println(node);

              //enqueue left and right child of current node
              if(node-> left != null)
                  q.push(node->left);

              if(node -> right != null)
                  q.push(node->right);
        }
        //terminate level by printing newline
        println();

    }
}




Question 5:

How locking mechanism is implemented by JVM?


Answer:

The implementation of locking mechanism in java is specific to the instruction set of the java platform.
For example with x86, it might use the CMPXCHG instruction - atomic compare and exchange  - at the lowest level to implement the fast path of the lock.

The CMPXCHG instruction is a compare-and-swap instruction that guarantees atomic memory access at the hardware level.

If the thread cannot acquire the lock immediately , then it could "spinlock" or it could perform a syscall to schedule a different thread. Different strategies are used depending on the platform , JVM Switches.


Question 6:

Is Java pass-by-value or pass-by-reference?


Answer:


Java is always pass-by-value.  Whenever we pass an object to some method, then we actually send a reference variable that points to the actual object. Means that reference variable will be containing the memory address as value. That's why Java is called as pass-by-value.

Let's take an example:

public static void main(String[] args){

    Book book = new Book("Java");
    Book bookNew = book;

    change(book);
    book.getName(); //Prints Java
}

public void change(Book book){
    book.getName() // Prints Java
 
    book = new Book("Angular");
    book.getName(); // Prints Anguar
}

So, here what we see, book name doesn't change after change() call , because passed book reference value points to new Book object [Angular].

Now, lets look at another example:

public static void main(String[] args){
    Book book = new Book("Java");
    Book bookNew = book;

    change(book);
    book.getName(); //Prints .Net

}

public void change(Book book){

    book.getName(); //Prints Java
    book.setName(".Net");
}

Here, what we see, value of book object gets changed after change() method call. Because book reference value in change() method still contains the address of actual Book object and it will act upon it only.




That's all for this post.

Hope these interview questions help everybody.

Thanks for reading.


Wednesday, January 8, 2020

Java Interview @ RBS

Hi Friends,
In this post, I'm sharing interview questions asked in R.B.S.

You can also read my other Interview posts:





There were total 10 questions asked in R.B.S.:


Question 1:

What is the difference between PUT and POST? Which request you will use to recharge a mobile phone?

Answer:

PUT vs POST:


  • PUT is used for update operation. While POST is mainly used for Create operation.
  • PUT is idempotent. So if we retry a request multiple times, that should be equivalent to single request modification.  While POST is not idempotent. So, if we retry a request N times , you will end up having N resources with N different URI's created on server. 

Generally, in practice, always use PUT for Update operations  and always use POST for create operations.


We will use POST request to recharge a mobile , because we need to create an entry for that mobile number on the server side. And we know, for creation purpose, we use POST.



Question 2:

Difference between Collections API and Stream API.

Answer:

Collection API was introduced in Java 5. While Stream API was introduced in Java 8.
Collection API is used to persist the elements. While Stream API doesn't persist the elements. It just performs operations on elements.

In Collection API, Iterator is used to iterate the collection elements. While in Streams , Spliterator is used to iterate over elements.




Question 3:

Is Stream API faster than collection?

Answer:

Yes, if we are using parallel streams, then performance of streams is better than collections.
As parallel streams use multi cores available in today's hardware, and it uses Fork Join pool and gives better performance.



Question 4:

What are the changes in Collections API in Java 8?

Answer:

Java 8 has made various changes in Collection API:


  • Sorting map directly with Comparators
  • Iterate over Map easily with forEach.
  • Get rid of if-else condition, use getOrDefault method
  • Replace and Remove utilities
  • Operate directly on values
  • Merge maps with merge method
  • Performance improvement in HashMap, LinkedHashMap, ConcurrentHashMap




Question 5:

Have you used JProfiler? How does it works and why you will use it?

Answer:

Yes, I have used JProfiler. It is a code profiling tool.
We have to install it and then integrate with any IDE, Eclipse or IntelliJ.

It provides all the information we need with proper views and filters.
It displays the information while the program is running.

It is used to analyze performance bottlenecks like memory leaks, CPU load etc. and is also used to resolve threading issues.  

In Eclipse, we use the Profile command to profile the code using JProfiler.
JProfiler is very easy to use and finds problems in the code.


Question 6:

What are Microservices?

Answer:

The main principle behind microservices is to break a single large monolithic system into multiple independent components/processes.

 Microservices architecture allows decoupled components to be built and deployed independently to integrate into a single larger system.

These components interact with each other through a standard XML/JSON interface, irrespective of the technologies used to create the component.




Question 7:

What is REST API?

Answer:

REST stands for Representational State Transfer
REST is an architectural style for designing networked applications and developing web services.
REST API uses HTTP protocol methods/verbs for all it's operations.

It resolves around resources where every component is a resource which can be accessed by a common interface using HTTP methods.


Question 8:

Have you worked with Spring Boot? Which version?

Answer:

Yes, I've worked with Spring Boot. And version used is Spring Boot 2.



Question 9:

What are the features added in Java 8?

Answer:

Below are all the features added in java 8:


  • Functional interfaces, Lambda Expressions
  • New Date and Time API
  • Streams
  • default methods in Interfaces
  • static methods in interfaces
  • Collection API improvements
  • forEach() method in Iterable interface.



Question 10:

What are Stream Lifecycle methods?


Answer:

Stream lifecycle is divided into three types of operations:


  • Stream Source : Array, Collection, IO Channel
  • Intermediate operations:  filter, sort, map, flatMap
  • Operation result: List, count, sum









That's all friends.

Hope this post help everybody in clearing java/android interviews.

Thanks for reading.


Tuesday, January 7, 2020

Java Interview @ Virtusa Polaris

Hi Friends,

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


Question 1:

Find frequency of a character and if more than one characters have same frequency then find character with more ASCII value.

Answer:

Algorithm to solve this problem:


  • Convert String into char array and take a HashMap, count variable and a char variable.
  • Iterate this array.
  • for every character, store it inside HashMap as key and with it's frequency as value. Also increase it's frequency value by 1. Along with that compare this frequency with count variable and if it is > count , then update count with frequency and also update char variable with that specific character for which we have updated count variable.
  • If frequency = count, then check if new character's ASCII code is > ASCII of char. If it is, the update char with  new character.
  • At last, we will have the required character in char variable with more frequency or with more ASCII value, in case some other char has same frequency.


Question 2:

Implement spiral movement in 2D array.

Answer:








Left to Right:

Move variable i from rowStart till colLength. Print data from first row till last column.

Top to Bottom:

Move variable i from (rowStart+1) till rowLength. Print data in last column.
We need to start from rowStart+1, because we already printed corner element in Left to Right printing and no need to include it again. Same treatment for corner elements in other directions.

Right to Left:

Move variable i from colLength - 1 till colStart.  Print data in last row.

Bottom to Up:

Move variable i from rowLength - 1 till rowStart.  Print data in first column.

After printing all 4 directions , in next iteration, we need to start from second row and second column , so increment  rowStart++  and colStart++.
We need to print till second last column and till second last row , so decrement  (colLength--) and (rowLength--).




Question 3:

What are the approaches for REST API versioning ?


Answer:

There are multiple approaches for doing versioning in REST API.

Important ones are described below:

URI Versioning:

Using the URI is the most straight forward approach[and also most commonly used]. Though it does violate the principle that URL should refer to a unique resource.

http://api.example.com/v1
http://apiv1.example.com


Versioning using custom Request Header:

e.g.:

Accept-version : v1
Accept-version : v2


Versioning using Accept Header:

e.g.:

Accept : application/vnd.example.v1+json
Accept : application/vnd.example+json;version=1.0


Question 4:

Explain Builder Design pattern and in which scenario it is used?

Answer:

What problem does it solve?:


  • Class constructor requires a lot of information.
So, whenever we have an immutable class, then we need to pass all the information/parameters inside the constructor of the class.

When to use Builder Pattern:

  • When we have a complex process to construct an object involving multiple steps, then builder design pattern can help us.
  • In builder, we remove the logic related to object construction from "client" code and abstract it in separate classes.




Question 5:

Difference between split() and StringTokenizer class?

Answer:

split() vs StringTokenizer:

Using StringTokenizer class, we have the option to use multiple delimiters with the same StringTokenizer object. But that's not possible with split() method.

split() method in String class is more flexible and easy to use. But StringTokenizer class is faster than split() method.

e.g.:

StringTokenizer st = new StringTokenizer("a:b:c" , ":");

while(st.hasMoreTokens()){

    System.out.println(st.nextToken());

}


StringTokenizer with multiple identifiers:

StringTokenizer st = new StringTokenizer("http://100.90.80.3/", "://.");

while(st.hasMoreTokens()){

    System.out.println(st.nextToken());
}

Output:
100
90
80
3


Using split() method:

for(String token : "a:b:c".split(":")){

    System.out.println(token);
}



Question 6:

Why String is immutable in java?

Answer:

String is immutable due to multiple reasons:


  • Due to String Pool facility. The String Pool is managed by String class internally.
  • Due to Network Security, as URL is sent in String format.
  • Due to thread security. Strings can be shared among multiple threads.
  • Class  loading mechanism
  • Immutability allows string to store it's hashcode and we don't need to calculate hashcode  every time  we call hashcode() method, which makes it very fast as hashmap keys to be used in HashMap in java. 


Question 7:

Why the variables defined in try block cannot be used in catch or finally?

Answer:

When we define any variable in try block and also use that variable in catch or finally, then suppose some exception occurs in try block before the line where that variable is defined. In that case, control goes to catch or finally and we will be using undefined variable in these blocks, because exception occured before the declaration.

That's why variables defined in try block cannot be used in catch or finally.



That's all from this interview.

Hope this post help everybody clearing java interviews.

Thanks for reading.

Sunday, January 5, 2020

Android/Java Interview @ Rocketalk

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


Question 1:

What are the data storage options on android platform?

Answer:

Android platform provides a list of data storage options. These options must be used based on the need such as data is secured and used with permission only or can be accessed publicly.

List of Data storage options in android platform:


  • SharedPreferences : It stores data in XML files.
  • SQLite : It stores structured data in the private database.
  • Internal Storage : It stores data in device file system.
  • External Storage : Data is stored in device's file system but is accessible to all apps on the device. 


Question 2:

Which method is called only once in Fragment lifecycle?

Answer:

In fragment lifecycle method calls, onAttached() is the method which is called only once.


Question 3:

Can we use String in switch case?

Answer:

We can use String in switch case from java 7.

Note: switch uses string.equals() method to compare the passed value with case values, so make sure to add a NULL check to avoid NullPointerException on the string passed.

According to java 7 documentation , java compiler generates more efficient bytecode for String in switch statement than chained if-else-if statements.


Question 4:

Why char array is preferred over String for storing password?

Answer:

String is immutable and final and it's value cannot be changed. So it's a security risk, as it takes time to garbage collect that string value and it resides in memory.

So, always use char array so that it's value can be changed to null.

Also , if string object is printed by mistake in some logs statement, then it prints the actual value, while char array prints memory location.

Question 5:

Why String is popular HashMap key?

Answer:

String is immutable and it's hashcode is calculated once and doesn't need to calculate again. It makes it a good candidate as HashMap key.


Question 6:

Find maximum repetitions of a number in integer array.

Answer:

First create a HashMap, a int variable max and an int variable temp.

HashMap: Stores key-value pairs
max : maximum count of occurences of a number
temp: number with maximum occurences  till time

Steps to solve this problem are:

  • Check whether a key exists in HashMap or not. If it exists , then get its count value, increment it by 1 and put it back and if this new incremented value is > max, then update max with this new value. And also put this new key in temp variable.
  • This way, keep iterating and follow step 1 and atlast value stored in temp variable will be the key with max occurences and integer max will give total maximum count of that key.



Question 7:

What are the technologies required in Web application development?

Answer:

In Web application development, technologies are required on client side and server side.

Below is the list of technologies required:

Client side development: HTML, CSS, JavaScript, Angular, Ajax

Server side development: PHP, Java , .NET, Perl,  Python


Question 8:

What is the difference between Web server and Application server?

Answer:

Web server is basically used to provide static content. While Application server contain the main business logic.

The clients for Web server are Web Browsers, Mobile app etc.
The clients for Application server are Web Server, Application servers, Mobile devices etc.

Most of the application servers also contain Web server as integral part of the system.

Examples of Web servers are : Tomcat, JBoss
Examples of Application servers are : Weblogic, WebSphere etc.



That's all friends.

Hope this post help everybody in clearing java/android interviews.

Thanks for reading. 

Java Interview @ Aricent

Hi Friends,

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

Also read my other interviews:




Question 1:

When does deadlock occur?

Answer:
  • Due to nested synchronized block
  • Due to calling of synchronized method from another synchronized method
  • Trying to get lock on two different objects
Code that causes Deadlock:

public class DeadlockDemo{

    public void method1(){

        synchronized(String.class){

            synchronized(Integer.class){

            }
       }
    }

    public void method2(){

        synchronized(Integer.class){

            synchronized(String.class){

            }
        }

    }

}



Question 2:

What is LiveLock?

Answer:

When all the threads are blocked or unable to proceed due to unavailability of required resources, then it is known as LiveLock.

  1. It occurs when all threads call Object.wait(0) on an object with 0 as parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects.
  2. When all the threads are stuck in infinite loops.


Question 3:

Is there any way to find a deadlock has occured in java?


Answer:

Yes. There is a way to find it.
From JDK 1.5, we have java.lang.management package to diagnose and detect deadlocks.
java.lang.management.ThreadBean interface is management interface for the thread system of JVM.

It has methods like findMonitorDeadlockedThreads() and findDeadlockedThreads().


Question 4:

Sort list of Employee objects using Designation, then age and then salary [nth level sorting]

Answer:

public class ComparatorChain implements Comparator<Employee>{

    private List<Comparator<Employee>> listComparators;

    public ComparatorChain(Comparator<Employee>... comparators){
        this.listComparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(Employee emp1, Employee emp2){
 
        for(Comparator<Employee> comparator : listComparators){
             int finalResult = comparator.compare(emp1, emp2);
             if(finalResult !=0){

                 return finalResult;
             }

        }
        return 0;
    }

}

DesignationComparator.java:

public class DesginationComparator implements Comparator<Employee>{

    @Override
     public int compare(Employee emp1, Employee emp2){

         return emp1.getDesignation().compareTo(emp2.getDesignation());
    }

}

AgeComparator.java

public class AgeComparator implements Comparator<Employee>{

    @Override
     public int compare(Employee emp1, Employee emp2){

        return emp1.getAge() - emp2.getAge();
    }

}


SalaryComparator.java:

public class SalaryComparator implements Comparator<Employee>{

    @Override
    public int compare(Employee emp1, Employee emp2){

        returm emp1.getSalary() - emp2.getSalary();
    }
}


public class ListObjectsComparisonAndSortingExample{

    public static void main(String[] args){

        List<Employee> employees = new ArrayList<Employee>();

       employees.add(new Employee("Mittal", "Developer", 35, 100000));
       // Add more Employee objects

      Collections.sort(employees, new ComparatorChain(
          new DesignationComparator(),
          new AgeComparator(),
          new SalaryComparator())
       );

    }

}

Question 5:

How to change logs from Info to Debug using log4j?

Answer:

In Log4j, we have multiple methods like debug(), info() , error() which can be called based on some condition and after that this Log API will print only that types of logs.

So, whenever we need to change logs from Info level to Debug level, we can easily do that by switching the call from info() to debug() as shown in example below:

static Logger logger = Logger.getLogger(MyClass.class.getName()); // Creating logger instance

logger.info("info"); // Suppose , initially it was printing info logs

logger.setLevel(Level.DEBUG); From now on, only debug, info, warn, error and fatal logs will be printed. But trace logs will not get printed.
logger.debug("debug"); 
logger.error("error");
logger.trace("trace");//it will not get printed.



Question 6:

What is the Log4j log level hierarchy order?

Answer:



From above diagram, we can see that for WARN, FATAL, ERROR and WARN are visible.
And for OFF, nothing will be visible.



Question 7:

What is a Daemon thread? How it works?

Answer:

Daemon thread acts like service providers for other threads running in the same process.
Daemon threads will be terminated by JVM when there are no other threads running, it includes main thread of execution as well.

To specify that a thread is a Daemon thread, call the setDaemon() method with the argument true.

To determine if a thread is a daemon thread, use the accessor method isDaemon().
Daemon threads are used to provide background support to the user threads.

Example of a daemon thread is Garbage Collection thread. gc() method is defined in System class that is used to send request to JVM to perform garbage collection.

public class DaemonThread extends Thread{

    public DaemonThread(){
        setDaemon(true);
    }

    public void run(){

        System.out.println("Is this thread Daemon? - "+isDaemon());
    }

    public static void main(String[] args){

        DaemonThread dt = new DaemonThread();
        dt.start();
    }
}




Question 8:

Describe two code cases where Race condition occur in java?

Answer:

Two code scenarios where race condition occur are:


  • Check and Act race condition
  • Read. Modify, Update race condition

Check and Act race condition: 

In this, we take example of creating Singleton instance.

if(instance == null){

    return class.getInstance();
}


Here, in this code, Suppose we have two threads T1 and T2. When T1 crosses if check, then it goes inside and CPU switches to T2. Now, it T1 is taking more time to create instance, then T2 also checks if statement and find instance as null. It also goes inside if() check and creates another instance.

So 2 instances will be created for Singleton instance.


Question 9:

How does Time complexity for get() and put() methods in HashMap is O(1)?

Answer:

Whenever we search for a key in HashMap or HashSet, it follows these steps:


  • Calculate hashcode for the key using their own hash() method.
  • This key acts as a m/m address and it is used to find array index/bucket location.
  • Then entries in LinkedList are compared.

As, m/m address from array can be get in one step, that's why it is O(1).

But in case, there are 1000 entries in LinkedList in a bucket, then it is not O(1). Then it is based on number of entries in LinkedList. So, in worse case, it is O(n).


Hope these interview questions help everybody.

Thanks for reading.

Saturday, January 4, 2020

Java Interview @ WDTS [Walker Digital Table Systems]

Hi Friends, 
In this post I'm sharing the questions asked in Walker Digital Table Systems for Java Tech Lead position.

Also read my other interviews:




Question 1:

What is Reentrant Lock?

Answer:

ReentrantLock is a mutually exclusive lock with the same behavior as the intrinsic/implicit lock accessed via synchronization.

ReentrantLock, as the name suggests , possesses reentrant characteristics. That means , a thread that currently owns the lock can acquire it more than once without any problem.

ReentrantLock forces one thread to enter critical section and queues all other threads to wait for it to complete.

Basically, java 5 introduces the concept of a lock. Lock and ReadWriteLock are interfaces in java 5.

And their implementations are ReentrantLock and ReentrantReadWriteLock.



Question 2:

How to handle service fallback in MicroServices?

Answer:

We can use Circuit breaker pattern implementation Netflix Hystrix for handling fallback in microservices.

Actually, in Microservices based arhitecture, there are many applications running in different processes on different machines. And any of these service may be down at some point of time. So to avoid sending all requests to this misroservice, Circuit breaker pattern can be used.


Question 3:

What are REST Call End Points?

Answer:

e.g.:  https://api.github.com/users/zellwk/repos?sort=pushed

In above URL, https://api.github.com  is root endpoint

/users/zellwk/repos is path which determines the resource we request for.

The last part of an endpoint is query parameters. Query parameters give us the option of modifying the request with key-value pairs. They always begin with a  question mark [?]. Each parameter pair is then separated with an ampersand [&] , like this:

?query1=value1&query2=value2



Question 4:

Explain Lifecycle of Spring Bean.

Answer:






Question 5:

Explain the steps of sending a request from browser and handling it at server side?

Answer:

Steps :


  • First request from browser [client side] will be received by DispatcherServlet
  • DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name associated with the given request.
  • So now, request transfers to the Controller and then controller will process the request by executing appropriate methods and returns ModelAndView object back to the DispatcherServlet.
  • Now DisptacherServlet send the view name to the ViewResolver to get the actual view page.
  • Finally DispatcherServlet will pass the Model object to the view page to display the result.



Question 6:

Name all the HTTP verbs?

Answer:

HTTP verbs are:


  • GET
  • PUT
  • POST
  • DELETE
  • HEAD
  • PATCH



Question 7:

What is a DispatcherServlet?

Answer:

DispatcherServlet handles all HTTP requests and responses.

It is front controller in Spring MVC based applications. DisptacherServlet uses it's own WebApplicationContext which is a child of ApplicationContext created by ContextLoaderListener.



Question 8:

When we override hashcode() method, then how to retrieve the actual default hash code value for that object?

Answer:

Just use System.identityHashCode(object);
The value returned by default implementation of hashcode() is called identity hash code.

Identity hashcode is usually the integer representation of the memory  address.

Hashcode of an object is a 32-bit signed int that allows an object  to be managed by hash-based data structure.


Question 9:

Write a logic of two threads printing question and answer one-by-one.

Answer:

class Chat{

    boolean flag = false;

    public synchronized void Question(String message){
        if(flag){
            try{
                wait();
            }
            catch(InterruptedException ie){
                 ie.printStackTrace();
            }
        }
       
        System.out.println(message);
        flag = true;
        notify();
    }

    public synchronized void Answer(String message){
        if(!flag){
            try{
                wait();
            }
            catch(InterruptedException ie){
                ie.printStackTrace();
            }
        }

        System.out.println(message);
        flag = false;
        notify();
    }
}


class Question implements Runnable{

    Chat chat;
    String[] str = {"Hi", "How are you?", "I'm also doing fine"};

    public Question(Chat c1){
        this.chat = c1;
        new Thread(this, "Question").start();
    }


   public void run(){

       for(int i = 0; i< str.length; i++){
           c1.question(str[i]);
        }
    }

}


class Answer implements Runnable{

    Chat chat;
    String[] str = {"Hi", "I'm good", "Great"};

    public Answer(Chat c1){
        this.chat = c1;
        new Thread(this, "Answer").start();

    }

    public void run(){

        for(int i=0; i<str.length; i++){
            c1.answer(str[i]);
        }
    }

}


public class Test{

    Chat chat =  new Chat();
    new Question(chat);
    new Answer(chat);
}

That's all.

Hope this post help every reader in java interview preparation.

Thanks for reading.

Friday, January 3, 2020

Java-Android interview @ handygo

Hi Friends,

Just willing to share my interview questions in company Handygo.

Hope, it will help prepare everybody for the java/android interview.

I'll also put correct answers of these questions.

Also read my other interviews:




Interview @ Handygo:


Question 1:

    What are the features of Java 8 version?

Answer:

 Java 8 Features:

  • Functional Interfaces
  • Lambda Expressions
  • Streams
  • New Date and Time API
  • Changes in Collections API
  • Changes in Map classs, HashMap, LinkedHashMap, ConcurrentHashMap 
  • Added StampedLock


Question 2:

    How Java Streams are lazy? Explain.

Answer:

Streams in java contain ternary operations. Like count(), collect(), list() etc. So, intermediary operations on streams are not executed until ternary operation is not called. That's why streams are lazy in nature.



Question 3:

    Tricky One: I have a functional interface with 3 abstract methods in it. How I'll write lambda expression for it?

Answer:

This is a tricky question. Actually interviewer wants to see the presence of mind.
Functional interfaces in Java 8 can contain only 1 abstract method. So, lambda expression will not operate on that interface, as it is not functional interface.


Question 4:

    I want to send a collection to some method as parameter and want to make sure that this collection cannot be updated. How I'll do that?


Answer:

In this case, we can send unmodifiable collection as the method parameter. In Collections class, we have methods like unModifiableCollection(), unModifiableMap() , unModifiableList() etc.
Using these, we can create and send unModifiable collection as method parameter.


Question 5:

    Why sewer [severage] covers are made round?

Answer:

Answer to this question is that round covers are easy to carry.
Along with that, it is very easy to put them on sewer, as no need to match the sides and corners.


Question 6:

    If you need to buy BMW, how much time you require to buy it?

Answer:

My answer to this question was: It will take me entire life with extreme hardwork to buy BMW.
As buying entire BMW company is not a little task.
Interviewer was checking the thought process.



Question 7:

    What is lifecycle of a thread?

Answer:


I had drawn this diagram and the answer was complete here.



Question 8:

    Difference between Android 5 & 6 version?

Answer:

  • Android 5 is called Lollipop while Android 6 is called Marshmallow.
  • In Android 5, Material Design was introduced while in Android 6 MIDI support and Android Pay was added.
  • Multiple SIM cards support in Android 5.  Permissions Dashboard in Android 6




Question 9:

    Is there any fee from play store to deploy the android app/game?

Answer:

Yes, Play store charges annual fee for deploying Android apps/games.


Question 10:

    Why to choose fragments over activity?

Answer:

Fragments are reusable components. And also they have better lifecycle methods to control them.
It is very easy to write fragment and use them everywhere.


Hope these interview questions help everybody.

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