Publicis Sapient 2024 Interview Structure and Questions

Explore the interview structure and common questions asked during Publicis Sapient interviews in 2024. Prepare for your upcoming interview with confidence.

6/6/202412 min read

This interview was done for Senior Associate Platform L2- Core Java + Micro Services role. There was total of 4 rounds of Interview.

  1. Telephonic Round(Screening) by HR

  2. Multiple Choice Questions and Java Coding Problem

  3. Technical Interview Round

  4. Manager Round

  5. Client Round(Depends on the project)

Below is the Java Multiple Choice Question asked. I will post on the other round in my future posts. Please write to the subscribe email if you want the know about the further rounds.

Publicis Sapient Java MCQ Test

Q 1. Open-Closed Principle is followed in which of the following design pattern?

Choose from the below Option

  1. Template Pattern

  2. Strategy pattern

  3. Builder Pattern

  4. Decorator Patern

  5. All the Above

  6. None of the Above

Correct Answer:
2. Strategy pattern

Explanation:
Strategy pattern embodies the OCP principle: the core functionality remains closed for modification, while new algorithms can be added as separate strategies, extending the behavior without altering existing code.
- Template Pattern: Partially aligns with OCP.
- Builder Pattern, Decorator Pattern: Don't directly follow OCP.

Q 2. What will be the Output of the below code?

public class Parent {
public void show() {
System.out.println("Parent Method");
}

public static void main(String[] args) {
Parent b = new Child();
b.show();
}
}
class Child extends Parent {
private void show() {
System.out.println("Child Method");
}
}

Choose from the below Option

  1. Parent Method

  2. Child method

  3. Compile Error

  4. Run Time Error

    Correct Answer:
    1. Parent Method

    Explanation:
    since the overridden show() method in Child is private, it's not accessible from outside the Child class.

Q 3. What are the Disadvantages of applying the GOF Singleton pattern?

Choose from the Options

  1. The Client Code can create mutiple instance at run time

  2. It reduces of the Class Hierachy as compared to the ohter factory design patterns

  3. It makes it easier for a certain family of Objects to work together

  4. It intoduces thread safety issue when the singleton instance is intantiated on demand

Correct Answer:
4. It intoduces thread safety issue when the singleton instance is intantiated on demand

Explanation:
Without proper synchronization, multiple threads could try to create multiple instances, violating the Singleton principle.

Q 4. It is also know as Wrapper, it is used when subclassing is not possible or Pratical to add functionality and it is used to add functionality at runtime. This Pattern is :

Choose from the Options

  1. Composite

  2. Adapter

  3. Decorator

  4. Proxy

Correct Answer:
3. Decorator

Explanation:
Decorator pattern offers a flexible way to extend object functionality without modifying the original class or inheritance hierarchy. It's a powerful tool for promoting loose coupling and dynamic behavior in object-oriented programming.

Q 5. The post order traversal of a binary tree is DEBFCA. Find out the pre order traversal

Choose from the Options

  1. ABFCDE

  2. ADBFEC

  3. ABDECF

  4. ABDCEF

    Correct Answer:
    3. ABDECF

    Explanation:
    Following the pre-order traversal order (root, left subtree, right subtree), the traversal would be:ABDECF

Q 6. What does the zeroth element of the string array passed to the standard main method contain in Java?

Here are the options provided:

  1. The name of the class.

  2. The string "java".

  3. The number of arguments.

  4. The first argument of the argument list, if present.

Correct Answer:
3. The number of arguments.

Explanation:
In Java, the args parameter in the main method is a string array that contains the command-line arguments passed to the program when it's executed. The zeroth element (index 0) of this array holds the number of arguments passed, not the arguments themselves. The arguments themselves start from index 1.

Q 7. When inorder traversing a tree resulted in EACKFHDGB, the preorder traversal would return:

Choose from below options

  1. FEAKDCHBG

  2. FAEKCDBHG

  3. EAFKHDCBG

  4. FAEKCDHGB

Correct Answer:
2. FAEKCDBHG

Explanation:
Inorder Traversal: EACKFHDGB tells us the order of nodes visited left-to-right during an inorder traversal.Preorder traversal visits the root node first, then the left subtree, and finally the right subtree.

Q 8. In a queue, the initial values of front pointer f rear pointer r should ideally be .... and........... respectively.

Choose from below options

  1. 0 and 1

  2. 0 and -1

  3. -1 and 0

  4. 1 and 0

Correct Answer:
2. 0 and -1

Q 9. Which class is at the top of the exception classes hierarchy?

Choose from below options

  1. Exception

  2. Error

  3. Throwable

  4. Object

Correct Answer:
3. Throwable

Q 10. Which of the following are not legal Java identifiers?

Choose from below options:

  1. goto

  2. unsigned

  3. String

  4. _xyz

Correct Answer:
1. goto

Explanation:
goto is a Reserved Keyword in Java

Q 11. Which three guarantee that a thread will leave the running state?

  1. yield()

  2. wait()

  3. notify()

  4. notifyAll()

  5. sleep(1000)

  6. aliveThread.join()

  7. Thread.killThread()

The answer choices are:

  • 1, 2 and 4

  • 2, 5 and 6

  • 3, 4 and 7

  • 4, 5 and 7

Correct Answer:
2,5 and 6

Explanation:

  • wait(): The thread surrenders control and waits for notification, leaving the running state.

  • join(): The calling thread blocks until the target thread finishes, forcing it to leave running.

  • sleep(1000): The thread pauses execution for a specific time, effectively not running.

Q 12. When exceptions can occur in Java code. The answer is:

The options are:

  1. Run Time

  2. Compilation Time

  3. Can Occur Any Time

  4. None of the options

Correct Answer:
3. Can Occur Any Time

Explanation:
Java exceptions can occur at various points in the program's lifecycle, making "Can Occur Any Time" the most accurate choice.

Q 13. Which of the following are valid declarations of the standard main() method?

The choices are:

  1. static void main(String args[]){}

  2. public static int main(String args[]){}

  3. public static void main (String args) {}

  4. final static public void main (String[] arguments) {}

Correct Answer:
4. final static public void main (String[] arguments) {}

Explanation:

  1. missing access modifier public

  2. Incorrect return type

  3. incorrect Argument should be String array

Q 14. Which of the following is true about ENUM

  • a) Enum can have non static object variables.

  • b) Enum are comparable.

  • c) Constructors of Enum are private.

  • d) Enum can't have a constructor.

The answer choices are:

  1. a,b and c

  2. b,c and d

  3. c,d and a

  4. a and b

Correct Answer:
2. b,c and d

Explanation:
Enums cannot have non-static object variables. All fields within an enum are implicitly public, static, and final.

Q 15. How does set ensure that there are no duplicates? Select all that apply.

Choose from below Options:

  1. It compares the objects by examining only equals() methods.

  2. It compares the objects by examining only hashCode() method.

  3. Given two objects a and b if a.hashCode() evaluated to true then it is further assumed that a.equals(b) also results to true.

  4. b.hashCode() evaluates to true then it is further assumed that the objects are duplicate.

  5. If any of the a.hashCode() b.hashCode() or a equals(b) evaluation results to true then it is assumed that the objects are duplicate.

Correct Answer:
5. If any of the a.hashCode() b.hashCode() or a equals(b) evaluation results to true then it is assumed that the objects are duplicate.

Q 16. Is ArrayList fail-fast?

  • True

  • False

Correct Answer:
True

Q 17. Given the following compilable statement:

Collections.sort(myArrayList);
What class should the objects stored in myArrayList implement and what method must the objects stored in myArrlist override?

Choose from below Options:

  1. Comparable, compareTo()

  2. Comparable, compare()

  3. Comparator, compare()

  4. Comparator, compareTo()

Correct Answer:
1. Comparable, compareTo()

Explanation:
The Collections.sort() method is used to sort an ArrayList in Java. In order to use this method, the objects stored in the ArrayList must implement the Comparable interface and override the compareTo() method.

Q 18. Which of the following statements are true for HashMap?

  • A) Keys can be duplicated but not Values

  • B) Values can be duplicated but not the keys.

  • C) HashMap is a hashing-based implementation of Map interface, used to store key-value pairs where key and value both can be custom java class.

  • D) HashMap keeps elements in ordered manner.

Choose from below Options:

  1. B and C

  2. A and D

  3. C and D

  4. A and C

Correct Answer:
1.B and C

Explanation:

  • HashMaps do not allow duplicate keys.

  • HashMaps allow duplicate values.

  • HashMap does not keep elements in an ordered manner.

  • HashMap is indeed a hashing-based implementation of the Map interface.

Q 19. Which statement is true in Java.

The Options are:

  1. A static method cannot be synchronized.

  2. If a class has synchronized code, multiple threads can still access the nonsynchronized code.

  3. Variables can be protected from concurrent access problems by marking them with the synchronized keyword.

  4. When a thread sleeps, it releases its locks.

Correct Answer:
Except for Option 1, all the Options are True

Q 20. How to create thread pools in Java. The options are:

  1. Callable Interface

  2. Future Interface

  3. ExecutorService

  4. None of the above

Correct Answer:
3. ExecutorService

Explanation:
The ExecutorService interface provides a way to submit tasks to a thread pool.

Q 21. Which one is True

  1. A thread can call a non synchronized instance method of an Object when a synchronized method is being executed

  2. Thread.sleep() release the lock

  3. Two Threads can call two diffect scynchronised instance method of an Object

  4. Wait keeps the locks

Correct Answer:
All the Statement are True

Q 22. Below method of Runtime class forcibly terminates the currently running Java Virtual machine and should be used with extreme caution?

  1. public void halt()

  2. public void exit(int status)

  3. public void halt(int status)

  4. public boolean removeShutdownHook()

Correct Answer:
2. public void exit(int status)

Explanation:
public void halt(int status) method abruptly terminates the JVM without any cleanup or finalization tasks. It bypasses the standard shutdown sequence and registered shutdown hooks are not executed.

Q 23. Which of the below statements are true about Perm Gems?

Choose Options :

  1. Contains the application metadata required by the JVM to describe classed and method used in the application

  2. perm Gen is populated by JRE based on current classes being used by application

  3. Perm Gen does not contain JAVA SE library classes

  4. perm gen is not part of java heap memory and method area is part of thee space in perm gen

  5. All the options

  6. none of the options

Correct Answer:
5. All the Options

Q 24. How can we request the garbage collector to run?

  • A. Runtime.clearMemory()

  • B. Runtime.gc()

  • C. System.gc()

  • D. System.finalize()

Choose Options :

  1. A & C

  2. B & D

  3. B & C

  4. C & D

Correct Answer:
3. B & C

Q 25. Which Statement is true for Java Functional Interfaces

Choose Options :

  1. @FunctionalInterface annotation is optional while creating functional interfaces.

  2. Functional Interface should have only one abstract method

  3. Functional Interface can have multiple default methods

  4. All of the Above.

Correct Answer:
4. All of the Above.

Q 26. Choose the correct output for the following code snippet

public class Example {
public static void main(String[] args) {
Optional<String> GOT = Optional.of("Game of Thrones");
String[] str = new String[10];
Optional<String> strOpt = Optional.ofNullable(str[9]);
System.out.println(strOpt.isPresent());
System.out.println(GOT.isPresent());
}
}

Choose Options :

  1. False & True

  2. True & True

  3. True & False

  4. Compile Error

Correct Answer:
1. False & True

Explanation:

  • strOpt.isPresent() evaluates to false because strOpt is assigned null using Optional.ofNullable(str[9]).

  • GOT.isPresent() evaluates to true because GOT has a value assigned to it using Optional.of("Game of Thrones").

27. Which of the following is a benefit from using @Override annotation?

Choose Options :

  1. Override annotation says that the method marked must be overriden by subclass

  2. It helps in runtime to dynamic binding the method to appropriate object

  3. Complier can warn you if the method designated with override is not a correct override

  4. None of the Above

Correct Answer:
3. Complier can warn you if the method designated with override is not a correct override.

28. Following syntac is valid for which Java Version:

ToIntBitFunction add = (a,b) -> a + b;

Choose from below Options:

  1. None of the Java Versions

  2. Java 8 and later

  3. Java 7 and later

  4. Java 5 and later

Correct Answer:
2. Java 8 and later

Q 29. Which code snippet is correct to follow the below code (in the question) to make use of an HttpEntity Object to encapsulate request headers and use it as a parameter?

The method returns a ResponseEntity Object containing the result of a REST request

String url = "http://localhost:8080/users/{$username}";
User user = new User();
user.setEmail("MrDoe@pet.com");
user.setUserName("jessicaJones");
//set other properties
...
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
final HttpEntity<User> userRequest = new HttpEntity<>(user, headers);

Choose from below options

  1. ResponseEntity<User> responseEntity = restTemplate.execute(url, HttpMethod.PUT, User.class, "johndoe", userRequest);

  2. ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, userRequest, User.class, "johndoe");

  3. ResponseEntity<User> responseEntity = restTemplate.getForObject(url, HttpMethod.PUT, userRequest);

  4. ResponseEntity<User> responseEntity = restTemplate.getForObject(url, userRequest);

Correct Answer:
2. ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, userRequest, User.class, "johndoe");

Explanation:

  • restTemplate.exchange(url, HttpMethod.PUT, userRequest, User.class, "johndoe"):

  • restTemplate: This refers to an instance of the RestTemplate class, which is used to make HTTP requests.

  • url: This is the URL of the REST endpoint you want to send the PUT request to, with a placeholder for the username ({$username}).

  • HttpMethod.PUT: This specifies the HTTP method to be used, which is PUT in this case.

  • userRequest: This is the HttpEntity object you created earlier, containing the User object (user) and the headers (headers).

  • User.class: This specifies the expected type of the response object, which is a User object in this case.

  • "johndoe": This is the value you want to replace the placeholder {$username} in the URL with.

Q 30. For a J2EE component, which code fragement is the correct and portable way of accessing a Web service?

Choose from below Options

  1. "// Use the service implementation class to get the Stub OrderService_Impl impl = new OrderService_Impl();
    Stub stub = (Stub) impl.getOrderServicePort();
    OrderService port - (OrderService) stub;
    // Call business method
    Order myorder = port.getOrderDetails(Orderld);"

  2. "Context ic = new InitialContext();
    OrderServiceStub svc (OrderServiceStub) ic.lookup(""java:comp/env/svc/OrderService"");
    // Lookup the Service Endpoint Interface
    OrderService port = svc.getOrderServicePort();
    // Call business method
    Order myorder = port.getOrderDetails(Orderld);"

  3. "Context ic = new InitialContext();
    Service svc (Service) ic.lookup(""java:comp/env/svc/OrderService"")
    // Lookup the Service Endpoint Interface
    OrderService port = (OrderService) svc.getPort(OrderService.class);
    // Call business method
    Order myorder = port.getOrderDetails(Orderld);"

  4. "ServiceFactory sf = ServiceFactory.newInstance();
    QName qname = new QName(""urn:OrderService"", ""OrderSvc"");
    // Create service with the WSDL URL and the service qname Service svc = sf.createService(wsdlURL, qname);
    QName qnamePort = new QName(""urn:OrderService"", ""OrderService"");
    Order Service port (OrderService) svc.getPort(qnamePort, OrderService.class);
    // Call business method
    Order myorder = port.getOrderDetails(Orderld);"

Correct Answer:
Option 2

Explanation:
JNDI lookup: It utilizes JNDI (Java Naming and Directory Interface) to locate the web service reference. This is the standard approach for J2EE deployments as it allows for centralized configuration and easier management. Portable: JNDI is a standard Java API, making the code portable across different J2EE servers. Separation of concerns: The code doesn't directly access the implementation class (OrderService_Impl). It retrieves the service reference from JNDI, promoting loose coupling.

Q 31. What is a benefit of validating an XML document on the sender's side?

Choose from below Options

  1. It ensures that the recipients are able to validate the document

  2. It ensures that the document conforms to the dicument's schema

  3. It ensures that the recipents are able to map the document's elements to the same Java types.

  4. It ensures that all types that are used in the document conform to the primitive types defined in the XML schema specification

Correct Answer:
2. It ensures that the document conforms to the dicument's schema
1. It ensures that the recipients are able to validate the document

Explanation:

  • Early Error Detection: By validating on the sender's side, any syntax errors, missing elements, or violations of the schema (e.g., incorrect data types, invalid values) are caught early in the process. This prevents sending invalid data that might cause parsing errors or unexpected behavior on the receiver's side.

  • Improved Communication Efficiency: Catching and fixing errors before transmission reduces the likelihood of communication failures and the need for retransmission or manual intervention.

  • Sender-Side Control: Validation on the sender's side gives the sender more control over the data being sent. They can ensure the data is well-formed and adheres to the agreed-upon schema, promoting data integrity.

Q 32. Which of the following is true regarding the below Spring Controller?

@Rescontroller
public class OwnerController {
@RequestMapping(value = "/owner/{ownerId}", method = RequestMethod.POST)
@ResponseBody
public Owner findOwner(@PathVariable("ownerId") int ownerId){
return new Owner();
}
}

Choose from below Options

  1. RequestMethod.GET method is more accurate than POST

  2. @PathVariable should be replaced with @PathParam annotation

  3. Returning the 201 HTTP status code is better 4

  4. @ResponseBody could be removed

Correct Answer:
1. RequestMethod.GET method is more accurate than POST

Q 33. Can you autowire byType when more than one bean with the same type exists?

  • False

  • True

Correct Answer:
False

Q 34. Imagine that there are two exception classes :

MyBaseBusinessException and MySubBaseBusinessException which extends from MyBaseBusinessException. if rollback-for="MyBaseBusinessException" and no-rollback-for="MySubBusinessException" are configured what happens when a MySubBusinessException is thrown from transactional context?

Choose from below Options

  1. no-rollback-for rule' is applied and transaction will not rollback

  2. rollback-for' is applied and transaction will be rollbacked

  3. Exception is thrown during application context initialization since configuration is ambiguous

  4. None of the above

Correct Answer:
1. no-rollback-for rule' is applied and transaction will not rollback

Explanation:
While the configuration might seem ambiguous at first glance, Spring's exception handling prioritizes the most specific rule. In this case, no-rollback-for for the exact exception type (MySubBaseBusinessException) takes precedence over the general rule for the base class (MyBaseBusinessException).

Q 35. When Spring instantiates a map, it prefers JDF 1.4+ collection implementations (LinkedHashMap) to Commons Collections 3.x versions (org.apache.commons.collections.map.LinkedMap ), falling back to JDK 1.3 collections (standard HashMap) as worst case.

  • TRUE

  • FALSE

Correct Answer:
FALSE

Explanation:
Spring prefers to use standard Java collections from the java.util package, specifically HashMap for maps.

Q 36. With local transactions, the application server is involved in transaction management and it can help ensure correctness accross multiple resources.

  • FALSE

  • TRUE

Correct Answer:
FALSE

Q 37. Which Transaction Manager implementation would be most appropriate to use following scenario : Your Spring based application is to be deployed on JEE Application Server.

Choose from below Options

  1. JpaTransactionManager

  2. HibernateTransactionManager

  3. JtaTransactionManager

  4. DataSourceTransactionManager

Correct Answer:
3. JtaTransactionManager

Explanation:

  • Using JtaTransactionManager promotes better integration with the JEE container's transaction services.

  • This allows for centralized transaction management across different resources within the container.

  • While other options might work for specific scenarios, JtaTransactionManager aligns best with the overall JEE architecture for transaction management.

Q 38. In Junit, when does @Before annotation get called?

Choose from below Options

  1. Only once, before execution of any one of the test case

  2. Before execution of each test cases

  3. At class initialization

  4. Before existing the class

Correct Answer:
2. Before execution of each test cases

39. In Junit, what is the purpose of @AfterClass annotation?

Choose from below Options

  1. To run clean up activity after completion of all test cases

  2. To apply basic settings required to perform each test cases

  3. To apply enviroment specific settings required to perform each test case

  4. To run clean up activity on completion of each test case

Correct Answer:
1. To run clean up activity after completion of all test cases

40. Which one is not a valid JUnit Assumptions method?

Choose from below Options

  1. assumeFalse

  2. assumingThat

  3. assumeTrue

  4. assumingTrue

Correct Answer:
4. assumingTrue