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.
This interview was done for Senior Associate Platform L2- Core Java + Micro Services role. There was total of 4 rounds of Interview.
Telephonic Round(Screening) by HR
Multiple Choice Questions and Java Coding Problem
Technical Interview Round
Manager Round
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
Template Pattern
Strategy pattern
Builder Pattern
Decorator Patern
All the Above
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
Parent Method
Child method
Compile Error
Run Time Error
Correct Answer:
1. Parent MethodExplanation:
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
The Client Code can create mutiple instance at run time
It reduces of the Class Hierachy as compared to the ohter factory design patterns
It makes it easier for a certain family of Objects to work together
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
Composite
Adapter
Decorator
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
ABFCDE
ADBFEC
ABDECF
ABDCEF
Correct Answer:
3. ABDECFExplanation:
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:
The name of the class.
The string "java".
The number of arguments.
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
FEAKDCHBG
FAEKCDBHG
EAFKHDCBG
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
0 and 1
0 and -1
-1 and 0
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
Exception
Error
Throwable
Object
Correct Answer:
3. Throwable
Q 10. Which of the following are not legal Java identifiers?
Choose from below options:
goto
unsigned
String
_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?
yield()
wait()
notify()
notifyAll()
sleep(1000)
aliveThread.join()
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:
Run Time
Compilation Time
Can Occur Any Time
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:
static void main(String args[]){}
public static int main(String args[]){}
public static void main (String args) {}
final static public void main (String[] arguments) {}
Correct Answer:
4. final static public void main (String[] arguments) {}
Explanation:
missing access modifier public
Incorrect return type
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:
a,b and c
b,c and d
c,d and a
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:
It compares the objects by examining only equals() methods.
It compares the objects by examining only hashCode() method.
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.
b.hashCode() evaluates to true then it is further assumed that the objects are duplicate.
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:
Comparable, compareTo()
Comparable, compare()
Comparator, compare()
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:
B and C
A and D
C and D
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:
A static method cannot be synchronized.
If a class has synchronized code, multiple threads can still access the nonsynchronized code.
Variables can be protected from concurrent access problems by marking them with the synchronized keyword.
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:
Callable Interface
Future Interface
ExecutorService
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
A thread can call a non synchronized instance method of an Object when a synchronized method is being executed
Thread.sleep() release the lock
Two Threads can call two diffect scynchronised instance method of an Object
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?
public void halt()
public void exit(int status)
public void halt(int status)
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 :
Contains the application metadata required by the JVM to describe classed and method used in the application
perm Gen is populated by JRE based on current classes being used by application
Perm Gen does not contain JAVA SE library classes
perm gen is not part of java heap memory and method area is part of thee space in perm gen
All the options
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 :
A & C
B & D
B & C
C & D
Correct Answer:
3. B & C
Q 25. Which Statement is true for Java Functional Interfaces
Choose Options :
@FunctionalInterface annotation is optional while creating functional interfaces.
Functional Interface should have only one abstract method
Functional Interface can have multiple default methods
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 :
False & True
True & True
True & False
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 :
Override annotation says that the method marked must be overriden by subclass
It helps in runtime to dynamic binding the method to appropriate object
Complier can warn you if the method designated with override is not a correct override
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:
None of the Java Versions
Java 8 and later
Java 7 and later
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
ResponseEntity<User> responseEntity = restTemplate.execute(url, HttpMethod.PUT, User.class, "johndoe", userRequest);
ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, userRequest, User.class, "johndoe");
ResponseEntity<User> responseEntity = restTemplate.getForObject(url, HttpMethod.PUT, userRequest);
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
"// 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);""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);""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);""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
It ensures that the recipients are able to validate the document
It ensures that the document conforms to the dicument's schema
It ensures that the recipents are able to map the document's elements to the same Java types.
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
RequestMethod.GET method is more accurate than POST
@PathVariable should be replaced with @PathParam annotation
Returning the 201 HTTP status code is better 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
no-rollback-for rule' is applied and transaction will not rollback
rollback-for' is applied and transaction will be rollbacked
Exception is thrown during application context initialization since configuration is ambiguous
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
JpaTransactionManager
HibernateTransactionManager
JtaTransactionManager
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
Only once, before execution of any one of the test case
Before execution of each test cases
At class initialization
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
To run clean up activity after completion of all test cases
To apply basic settings required to perform each test cases
To apply enviroment specific settings required to perform each test case
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
assumeFalse
assumingThat
assumeTrue
assumingTrue
Correct Answer:
4. assumingTrue