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

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

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


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.


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

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