Capgemini java interview questions for experienced

Capgemini java interview questions for experienced

1.  Create Employee Object which is having empId, empName, empSal.

import java.util.*;
class Employee{
    int empId;
    String name;
    int empSalary;
    public Employee(int empId, String empName, int empSalary){
        this.empId = empId;
        this.name = empName;
        this.empSalary = empSalary;
    }
}

Output

Abhay
Bikash
Mayank
Nishant
Subhesh
Vivek

2.  Iterate list using java8, sort based on empName.

import java.util.*;
class Employee{
    int empId;
    String name;
    int empSalary;
    public String getName(){
        return this.name;
    }
    public void setName(String name){
        this.name = name;
    }
    public Employee(int empId, String empName, int empSalary){
        this.empId = empId;
        this.name = empName;
        this.empSalary = empSalary;
    }
}
public class Main {  
    public static void main(String[] args) {  
        List<Employee> employee = new ArrayList<Employee>();  
        employee.add(new Employee(1,"Mayank",2));  
        employee.add(new Employee(2,"Nishant",1));  
        employee.add(new Employee(3,"Subhesh",3));
        employee.add(new Employee(1,"Abhay",2));  
        employee.add(new Employee(2,"Bikash",1));  
        employee.add(new Employee(3,"Vivek",3)); 
        employee.sort((Employee e1, Employee e2) -> e1.getName().compareTo(e2.getName()));
        employee.forEach(item -> System.out.println(item.getName()));
    }  
} 

Output

Abhay
Bikash
Mayank
Nishant
Subhesh
Vivek

3.  List convert into Map<empId, empName> using java8.

import java.util.*;
import java.util.stream.Collectors;
class Employee{
    int empId;
    String name;
    int empSalary;
    public String getName(){
        return this.name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int getEmpId(){
        return this.empId;
    }
    public void setEmpId(int empId){
        this.empId = empId;
    }
    public Employee(int empId, String empName, int empSalary){
        this.empId = empId;
        this.name = empName;
        this.empSalary = empSalary;
    }
}
public class Main {  
    public static void main(String[] args) {  
        List<Employee> employee = new ArrayList<Employee>();  
        employee.add(new Employee(1,"Mayank",2));  
        employee.add(new Employee(2,"Nishant",1));  
        employee.add(new Employee(3,"Subhesh",3));
        Map<Integer, String> result = employee.stream().collect(Collectors.toMap(Employee::getEmpId, Employee::getName));

        System.out.println(result);
        
    }  
} 

Output

{1=Mayank, 2=Nishant, 3=Subhesh}

4.  Sort map based on map value using java8.

import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
    public static void main(String[] argv) {
        Map<String, Integer> map = new HashMap<>();
        map.put("z", 10);
        map.put("b", 5);
        map.put("a", 6);
        map.put("c", 20);
        map.put("d", 1);
        map.put("e", 7);
        map.put("y", 8);
        map.put("n", 99);
        map.put("g", 50);
        map.put("m", 2);
        map.put("f", 9);
        
        Map<String, Integer> result1 = map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        Map<String, Integer> result2 = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
                
        final Map<String, Integer> result3 = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        
        System.out.println("Sorted by value in descending order : ");
        System.out.println(result1);
        System.out.println(result2);
        System.out.println("Sorted by value in Ascending order : ");
        System.out.println(result3);
    }
}

Output

Sorted by value in descending order : 
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
Sorted by value in Ascending order : 
{d=1, m=2, b=5, a=6, e=7, y=8, f=9, z=10, c=20, g=50, n=99}

5.  Sort map based on map key using java8.

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] argv) {
        Map<String, Integer> map = new HashMap<>();
        map.put("z", 10);
        map.put("b", 5);
        map.put("a", 6);
        map.put("c", 20);
        map.put("d", 1);
        map.put("e", 7);
        map.put("y", 8);
        map.put("n", 99);
        map.put("g", 50);
        map.put("m", 2);
        map.put("f", 9);
        System.out.println("Original HashMap");
        System.out.println(map);
        Map<String, Integer> result = map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        Map<String, Integer> result2 = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
                
        System.out.println("HashMap Sorted by Key : ");
        System.out.println(result);
        System.out.println(result2);
    }

}

Output

Original HashMap
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
HashMap Sorted by Key : 
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}

6.  Advantages and Disadvantages of Microservices over Monolithic.

Some Advantages of Microservices are :

  • Microservices are self-contained and independent modules.
  • It follows the single responsibility principle.
  • Microservices are Easier to Maintain and Update.
  • Microservices are very easy to scale as compared to Monolithic.
  • A single service can be deployed on multiple servers to enhance performance.
  • Microservices are less independent so it is easy to test and maintain.
  • A single microservice can be upgraded, we don’t have to upgrade the whole application which is not possible in the monolith.

Some Disadvantages of Microservices are :

  • In microservices, different services are communicating with each other. So there are some chances of failure of this communication.
  • If there are a large number of services then it will be a little bit hectic to manage all services.
  • There might be some network issues like load balancing or latency issue.
  • It requires more development time in comparison to monolith architecture.
  • Testing and debugging might be difficult here because services are distributed

7. Configure Environment based configurations in Application. How?

8. Difference in Collections.sort and Streams.sort.

  • Collections.sort(...) sorts a collection in place, while
  • collection.stream().sorted() returns a sorted stream that you need to collect into a new variable 
  • collection.stream().sorted(new CustomComparator()) doesn’t sort the collection, only makes the stream sorted.

To achieve a similar result with Stream API, you should use a terminal operation – collect into a new list:

collection.stream().sorted(new CustomComparator()).collect(Collectors.toList());

9.  Advantage of SpringBoot over Spring MVC.

Spring Boot is an extension of Spring, which eliminates the boilerplate configurations required for setting up a Spring application. Featuring default codes and annotation-based configuration, Spring Boot enables a faster and more efficient development ecosystem.

The configurations required in Spring MVC are like DispatcherServlet configurations and View Resolver configurations. But Spring Boot handles the configurations automatically with its Auto-configuration feature.

As developers need to devote time to adding required dependencies, Spring MVC takes more time for development as compared to Spring Boot.

10. Change the port and default server in the Application.

Change the server of the application

Using Property Files

By default, the embedded server starts on port 8080

So, let’s see how to provide a different value in an application.properties file:

server.port=8081

Now the server will start on port 8081.

And we can do the same if we’re using an application.yml file:

server:  
   port : 8081

You will need to update pom.xml, add the dependency for spring-boot-starter-jetty. Also, you will need to exclude default added spring-boot-starter-tomcat dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

In gradle,

configurations {
    compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-jetty")
}

11.  Different methods of Rest API?

There are total 5 method of rest api

  1. GET
  2. POST
  3. PUT
  4. DELETE
  5. PATCH

12. Difference between patch and put?

  • Patch and Put both are used to update the data. But Patch updates only the required field but PUT updates all the fields again.
  • HTTP PUT is said to be idempotent, So if you send retry a request multiple times, that should be equivalent to a single request modification.
  • HTTP PATCH is basically said to be non-idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on the server.
  • Idempotent Methods in REST. REST APIs use HTTP methods such as POST, PUT, and GET to interact with resources such as an image, customer name, or document.
  • When using an idempotent method, the method can be called multiple times without changing the result. 

13. Can we create using Put method?

Yes We can create

  • It helps you to store the supplied entity under the supplied URI
  • If the supplied entity already exists, then you can perform the update operation, or you can create with that URI.
  • You can create a resource as many times as you like.
  • Creating a resource with PUT method is very easy.
  • You do not need to check whether the user has clicked the submit button multiple times or not.
  • It can identify the entity enclosed with the request.

14. Underlying structure of Java streams?

Java Stream is an on-demand computed data structure. It doesn’t store data, it operates on the source data structure (collection and array) and produces pipelined data that we can use to implement internal iteration.

Steps to create and use Java Stream

Step to Create source to the destination stream

Stream<Integer> numbersStream = numbers.stream();

Step to put data

numbersStream = numbersStream.map(x -> x*x);

Steps to Store the output

List newList = numbersStream.collect(Collectors.toList());

Some Stream intermediate operations

  • map
  • filter
  • sorted

Terminal Operations

  • collect
  • forEach
  • reduce

reference : https://medium.com/elevate-java/java-streams-an-in-memory-data-structure-d6984eea1091

15. Difference in YAML and JSON file in java.

Technically YAML is a superset of JSON. This means that, in theory at least, a YAML parser can understand JSON, but not necessarily the other way around.

Differences between YAML and JSON are:

YAMLJSON
Comments are denoted with a hash/number sign.Comments are not allowed.
Hierarchy is denoted by using double space characters. Tab characters are not allowed.Objects and Arrays are denoted in braces and brackets.
String quotes are optional but it supports single and double quotes.Strings must be in double quotes.
Root node can be any of the valid data types.Root node must either be an array or an object.

16. Annotation used for importing all configurations at application start.

 @SpringBootApplication

17. Internal working of Hashmap.

HashMap stores data in key value pair where key will be always unique and value can be duplicate. HashMap contains an array of the nodes. This node is represented as a class that uses an array and LinkedList data structure internally for storing Key and Value.

Hashmap has these 4 fields

  1. int hash
  2. K key
  3. V value
  4. Node next

There are various steps that is followed by the Hashmap to insert any value in Hashmap.

First steps is hashing where object converts into an integer value. The integer value helps in indexing and faster searches.

Also you should know hashcode() and equals() method

  • equals(): equals method checks the equality of two objects and compares the Key to know whether they are equal or not. equals() methods is overridden. Whenever you override the equals() method then you should override the hashCode() method.
  • hashCode(): hashCode() method returns the memory reference of the object in integer form. The value returned by the hashcode() method is a bucket number. The bucket number is the address of the element inside the map. Hash code of null Key is 0.
  • Buckets: A Bucket is element of the HashMap array that is used to store nodes. It is also treated as an Array of nodes. Each node has a data structure like a LinkedList. More than one node can share the same bucket and may have different in capacity.

18. What are containers?

Containers are packages of software that contain all of the necessary elements to run in any environment. In this way, containers virtualize the operating system and run anywhere, from a private data center to the public cloud or even on a developer’s personal laptop.

Containers are a form of operating system virtualization. A single container might be used to run anything from a small microservice or software process to a larger application. Inside a container are all the necessary executables, binary code, libraries, and configuration files.

Compared to server or machine virtualization approaches, however, containers do not contain operating system images. This makes them more lightweight and portable, with significantly less overhead. In larger application deployments, multiple containers may be deployed as one or more container clusters. Such clusters might be managed by a container orchestrator such as Kubernetes.

19. Count duplicate characters in a given String.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
       Scanner sc= new Scanner(System.in); 
        System.out.print("Please enter a string: ");  
        String str= sc.nextLine();   
        int  count, duplicateCount = 0;
        char strArr[] = str.toCharArray();  
        System.out.println("Count of the Duplicate characters in string: ");  
        for(int i = 0; i < strArr.length; i++) {  
            count = 1;  
            for(int j = i+1; j < strArr.length; j++) {  
                if(strArr[i] == strArr[j] && strArr[i] != ' ') {  
                    count++;  
                    strArr[j] = '0';  
                }  
            }  
            if(count > 1 && strArr[i] != '0')  
                duplicateCount++ ;
        } 
        System.out.println( "Total duplicate Character = "+duplicateCount); 
	}
}

Output

Please enter a string: aabbcccd
Count of the Duplicate characters in string: 
Total duplicate Character = 3

20. Second highest salary query.

SELECT MAX(SALARY) FROM Employee WHERE SALARY < (SELECT MAX(SALARY) FROM Employee);