Have a question?
Message sent Close

Ultimate Guide to Cognizant Interview Questions for Freshers 2024

Cognizant Technology Solutions stands out as a renowned multinational corporation, offering an extensive array of IT services. Its digital transformation expertise, adaptable engagement model, industry-specific approach, and strong management record are commendable. If you aspire to thrive in a dynamic work environment and carve a successful career path, Cognizant might be the perfect fit for you. Dive into this blog to equip yourself with the insights and tips needed to excel in the Cognizant interview. Explore a range of commonly asked questions designed to help you confidently demonstrate your skills and capabilities.

Table of Contents

Cognizant Interview Process

At Cognizant, the interview process is meticulously crafted to assess not only your technical acumen but also your soft skills. Interviewers gauge your communication proficiency, personality attributes, dedication to work, and alignment with the company’s culture and values.

On-Campus Recruitment: During on-campus recruitment, Cognizant collaborates with universities or colleges, leveraging their placement cells. Activities include conducting interviews, job fairs, and networking events. Typically, final-year undergraduates or postgraduates are targeted through this process.

Off-Campus Recruitment: In off-campus recruitment, Cognizant advertises job openings on various digital platforms such as job portals, social media, and its career website. This method caters to a diverse range of candidates, from entry-level to experienced professionals, accommodating varied levels of expertise.

Cognizant Technical Round Interview Process

Aptitude Test: Embark on a journey of problem-solving and analytical prowess. The aptitude test at Cognizant delves deep into your ability to unravel complexities and tackle challenges head-on.

Technical Round (Programming Test): Enter the realm of programming prowess, where your coding finesse and knack for debugging shine. This round is a litmus test of your technical acumen and mastery of concepts crucial for the role you aspire for.

HR Round: As the curtain draws close, step into the spotlight to showcase more than just your skills. The HR round at Cognizant delves into the essence of your being, evaluating your communication finesse, personality traits, and cultural fit within the organization.

Cognizant HR Round Interview Questions

Q1. Tell us about yourself?
Ans: I recently graduated with a B.Sc in Computer Science and have a deep passion for software engineering. Through internships and projects, I’ve honed my skills and developed a collaborative and problem-solving mindset.

Q2. Why do you wish to work at Cognizant?
Ans: Cognizant’s innovative reputation, diverse culture, and commitment to employee development align perfectly with my career aspirations. I’m eager to contribute to a company that values creativity and embraces new technologies.

Q3. What are your strengths and weaknesses?
Ans:I excel in attention to detail, analytical thinking, and adaptability. While I thrive in these areas, I continuously work on improving my time management skills through feedback and implementing efficient strategies.

Q4. Describe a time you faced a challenge and how you overcame it?
Ans: In a previous project, we encountered a critical bug close to the release deadline. I coordinated with the team, conducted thorough testing, and implemented a workaround to meet the timeline. This experience taught me the importance of communication and quick decision-making under pressure.

Q5. Do you prefer to work independently or as part of a team?
Ans: I value both independence and teamwork. Independence allows for deep focus and efficiency, while collaboration brings diverse perspectives and creativity. I adapt my approach based on the task at hand.

Q6. What are your salary expectations?
Ans: I’ve researched industry standards and am open to negotiation. My priority is finding a role aligned with my career goals and offering growth opportunities.

Q7. How well do you handle the pressure?
Ans: I prioritize tasks, manage deadlines, and remain calm under pressure. During a high-stakes project, I delivered results while maintaining a positive attitude.

Q8. Where do you see yourself in 5 years?
Ans: In 5 years, I aim to be a senior software engineer specializing in cloud computing. I believe Cognizant’s learning opportunities will help me achieve this goal.

Q9. Do you have any questions for us?
Ans: I’m interested in learning about Cognizant’s mentorship programs and its approach to fostering innovation among employees.

Q10. What do you enjoy outside of work?
Ans: Outside of work, I enjoy hiking, photography, and playing the guitar. These activities contribute to my personal development and well-being.

Q11. Describe a complex technical challenge you faced and how you approached and resolved it?
Ans: In a previous project, we tackled a scalability issue with our database system by optimizing queries and implementing caching mechanisms. This experience showcased my problem-solving skills and technical expertise.

Q12. Tell us about a time you had to adapt to a significant change in the workplace?
Ans: During the transition to remote work due to the pandemic, I embraced virtual collaboration tools and adjusted my schedule to maintain productivity.

Q13. Describe your leadership style and how you motivate your team?
Ans: I believe in empowering team members and fostering a positive work environment. I motivate through recognition and clear goal-setting.

Q14. How do you handle multiple deadlines?
Ans: I prioritize tasks, delegate when necessary, and communicate effectively with stakeholders to manage expectations.

Q15. Describe a time you had to manage a difficult client or stakeholder relationship?
Ans: By listening to concerns, providing explanations, and building trust, I successfully navigated a challenging stakeholder situation.

Q16. How do you stay updated with the latest trends and advancements in your field?
Ans: I participate in conferences, follow industry leaders, and engage in online communities to stay informed.

Q17. Tell us about a time you had to deal with a situation where your work ethic or values were challenged?
Ans: When asked to compromise on quality for speed, I advocated for maintaining standards and integrity.

Q18. Describe a time you went above and beyond your job description to achieve a positive outcome?
Ans: By introducing automation tools during a critical project, I improved efficiency and received positive feedback.

Q19. What are your career goals, and how does this position align with them?
Ans: I aim to become a project management leader, and this position offers opportunities to lead teams and contribute to organizational success.

Q20. What are your learning and development goals, and how do you plan to achieve them?
Ans: I plan to enhance my project management skills through courses and certifications, seeking mentorship for guidance and growth.

Cognizant Interview Questions for freshers

Q1. What are RESTful Web Services? Describe how you would design a simple RESTful service.
Ans: RESTful Web Services are a set of architectural principles for designing networked applications. They use HTTP methods to perform operations such as reading data (GET), updating data (PUT), creating data (POST), and deleting data (DELETE) on resources. Here’s a simple design for a RESTful service:

  1. Identify Resources: Determine what data your service will expose. For example, a blog service might have resources like “posts” and “comments”.
  2. Define URIs: Assign unique URIs (Uniform Resource Identifiers) to each resource. For instance, /posts for posts and /posts/{id}/comments for comments on a specific post.
  3. Use HTTP Methods: Utilize appropriate HTTP methods for CRUD operations. GET to retrieve data, POST to create, PUT/PATCH to update, and DELETE to remove resources.
  4. Response Formats: Decide on the format of responses, commonly JSON or XML. Ensure consistency across endpoints.
  5. Handle Errors: Define error responses for invalid requests, including proper HTTP status codes and error messages in the response body.
  6. Statelessness: Ensure that each request contains all the information necessary to process it, without relying on previous requests. This enhances scalability and simplifies client-server communication.

Example:
Suppose we are designing a RESTful API for a bookstore.

  • Resource: Book
  • URI: /books/{id}
  • HTTP Methods: GET (retrieve book details), POST (add a new book), PUT (update book details), DELETE (remove a book)
  • Response Format: JSON
  • Error Handling: Proper HTTP status codes and error messages in JSON format

This simple design adheres to REST principles and facilitates easy interaction with the bookstore’s data.

Q2. What is the fill factor in SQL? What is its default value?
Ans: Fill Factor: Fill factor in SQL determines the percentage of space on each leaf-level page to be filled with data, leaving room for future expansion. It helps to reduce page splits and fragmentation.

Default Value: The default fill factor value in SQL Server is 100, meaning pages are filled completely.

Q3. How does garbage collection work? What algorithm is used in garbage collection is a memory management mechanism? The algorithm automatically detected the unused objects in the memory and deleted them?
Ans: Garbage Collection: Garbage collection is a memory management process in programming languages like Java and C#. It automatically detects and removes unreferenced objects from memory, reclaiming space for new objects.

Algorithm: Various algorithms are used in garbage collection, such as:

  • Mark and Sweep: This algorithm identifies reachable objects by starting from known roots (e.g., global variables) and recursively marking all referenced objects. Unmarked objects are then swept and removed from memory.
  • Generational GC: Objects are categorized into generations based on their age. Younger objects are more likely to become garbage, so they’re collected more frequently, while older objects are collected less often.
  • Copy Collection: This algorithm divides memory into two equal halves and alternately uses one half for allocation while collecting garbage from the other half.

Q4. Describe the process and benefits of Normalization in databases.
Ans: Normalization: Normalization is a database design technique used to organize data into tables to minimize redundancy and dependency. It involves dividing large tables into smaller ones and defining relationships between them. The process typically involves several normal forms, like 1NF, 2NF, 3NF, and BCNF.

Process:

  1. Identify Entities: Identify distinct entities and their attributes.
  2. Create Tables: Create separate tables for each entity and assign attributes.
  3. Define Relationships: Establish relationships between tables using primary and foreign keys.
  4. Apply Normal Forms: Ensure each table satisfies the requirements of various normal forms, eliminating data redundancy and anomalies.

Benefits:

  • Reduced Redundancy: Eliminates data duplication, saving storage space and ensuring consistency.
  • Improved Data Integrity: Minimizes update anomalies and maintains data integrity.
  • Simplified Updates: Updates and modifications become more straightforward and efficient.
  • Enhanced Query Performance: Optimizes query performance by reducing the need for complex joins and scans.

Q5. What factors influence whether or not a detection algorithm is required in a deadlock avoidance system?
Ans: Deadlock Detection Algorithm: Deadlock detection algorithms are necessary in systems where deadlock prevention or avoidance mechanisms are not feasible due to resource utilization or performance constraints. Factors influencing their requirement include:

  • Resource Utilization: If resources are heavily utilized and cannot be reserved in advance, detection becomes necessary to handle potential deadlocks.
  • System Complexity: As system complexity increases, the likelihood of deadlock occurrences rises, making detection vital.
  • Performance Impact: The overhead of deadlock detection must be weighed against its benefits. In high-performance systems, detection algorithms may be preferred over prevention or avoidance strategies.
  • Criticality of Applications: For critical applications, where system downtime due to deadlocks is unacceptable, detection mechanisms provide a means to recover from deadlock situations efficiently.

Q6. What is a bootloader?
Ans: Bootloader: A bootloader is a small program that initializes the operating system when a computer starts up. It resides in the device’s non-volatile memory (like ROM or flash memory) and is executed immediately after the system is powered on. The primary function of a bootloader is to load and execute the operating system kernel to start the boot process. It performs tasks like hardware initialization, checking system integrity, and loading the OS into memory.

Q7. Explain the concept of Exception Handling in Java.
Ans: Exception Handling in Java: Exception handling in Java enables programmers to handle runtime errors gracefully, preventing application crashes and improving robustness. It involves detecting, responding to, and recovering from exceptional conditions, known as exceptions.

Key Concepts:

  • Try-Catch Blocks: Exception-prone code is enclosed within a try block, followed by one or more catch blocks to handle specific exceptions.
  • Throw: Developers can explicitly throw exceptions using the throw keyword to indicate abnormal conditions.
  • Finally: The finally block contains code that is executed regardless of whether an exception occurs or not. It’s often used for resource cleanup.
  • Checked and Unchecked Exceptions: Checked exceptions must be caught or declared by the calling method, whereas unchecked exceptions (runtime exceptions) do not require handling explicitly.

Example:

try {
    // Exception-prone code
    int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
    // Handle arithmetic exception
    System.out.println("Cannot divide by zero.");
} finally {
    // Cleanup code
    System.out.println("Execution complete.");
}

Q8. Write the code to find the length of a string without using the string functions?

public class StringLength {
    public static void main(String[] args) {
        String str = "Hello, World!";
        int length = 0;
        
        // Iterate through the characters of the string
        for (char c : str.toCharArray()) {
            length++;
        }
        
        System.out.println("Length of the string: " + length);
    }
}

Q9. What are the primitive data types in Java?
Ans: Primitive Data Types: In Java, primitive data types are the basic building blocks for storing data. They include:

  • byte: 8-bit signed integer
  • short: 16-bit signed integer
  • int: 32-bit signed integer
  • long: 64-bit signed integer
  • float: 32-bit floating-point number
  • double: 64-bit floating-point number
  • char: 16-bit Unicode character
  • boolean: Represents true or false values

Example:

int age = 30;
double price = 19.99;
char grade = 'A';
boolean isStudent = true;

Q10. How will you print the address of a variable without using a pointer?
Ans: In Java, you cannot directly access memory addresses like in languages that support pointers. Java manages memory through references, and direct memory manipulation is not allowed for safety reasons.

Q11. What is the difference between int and Integer in Java?
Ans:

  • int: int is a primitive data type in Java that represents a 32-bit signed integer value.
  • Integer: Integer is a wrapper class in Java that encapsulates an int value into an object. It provides utility methods for dealing with int values.

Example:

int num = 10; // primitive int
Integer number = 20; // Integer object


Q12. What exactly is index hunting, and how does it aid query performance?
Ans: Index Tuning: Index tuning, also known as index optimization or index hunting, is the process of improving database query performance by optimizing the use of indexes.

Benefits:

  • Faster Query Execution: Properly designed indexes allow the database engine to locate and retrieve data more efficiently, resulting in faster query execution.
  • Reduced Resource Consumption: By minimizing the number of full table scans and reducing disk I/O operations, index tuning can significantly reduce resource consumption.
  • Improved Scalability: Efficient indexes ensure that database performance remains consistent as data volume increases, promoting scalability.
  • Enhanced User Experience: Faster query response times lead to a better user experience, especially in applications where responsiveness is critical.

Q13. What do you understand about Proactive, Retroactive, and Simultaneous Update in the context of DBMS?
Ans: Update Anomalies: In database management systems (DBMS), update anomalies occur when changes to data lead to inconsistencies or loss of data integrity. Different update strategies aim to mitigate these anomalies:

  • Proactive Update: In proactive update, changes are immediately propagated to all relevant records to maintain consistency. It ensures that data remains up-to-date but may incur additional overhead for each update operation.
  • Retroactive Update: Retroactive update involves modifying existing data after changes have occurred, often using logs or historical records to reconcile inconsistencies. It allows for flexible update operations but may require more complex recovery mechanisms.
  • Simultaneous Update: Simultaneous update employs locking mechanisms or concurrency control techniques to ensure that multiple updates to the same data do not interfere with each other. It enables concurrent access to data while preventing conflicts and maintaining consistency.\

Q14. How does Dynamic Loading help in better memory space utilization?
Ans: Dynamic Loading: Dynamic loading is a programming technique where a software module is loaded into memory only when it’s needed, rather than being loaded at the start of the program’s execution. It improves memory space utilization in several ways:

  • Reduced Memory Footprint: By loading modules on demand, dynamic loading reduces the initial memory footprint of the program, allowing more efficient use of available memory resources.
  • Faster Startup Time: Loading only necessary modules speeds up the program’s startup time, as it doesn’t need to load unnecessary components upfront.
  • Optimized Resource Allocation: Dynamic loading allows resources to be allocated dynamically based on runtime requirements, optimizing resource allocation and improving overall system performance.
  • Enhanced Flexibility: Dynamically loaded modules can be unloaded from memory when they are no longer needed, freeing up memory space for other tasks and improving overall system flexibility.

Q15. What is Agile methodology, and how does it differ from traditional waterfall project management?
Ans: Agile Methodology: Agile is an iterative approach to software development that prioritizes flexibility, collaboration, and customer feedback. It emphasizes adaptive planning, evolutionary development, early delivery, and continuous improvement.

Differences from Waterfall:

  • Iterative vs. Sequential: Agile follows an iterative approach, with development done in small increments or sprints, while waterfall is sequential, with distinct phases like requirements, design, implementation, testing, and deployment.
  • Customer Involvement: Agile encourages regular customer collaboration and feedback throughout the development process, whereas waterfall typically involves customer input only at the beginning and end of the project.
  • Flexibility vs. Rigidity: Agile embraces change and allows for flexibility in requirements and priorities, accommodating evolving customer needs. Waterfall, on the other hand, follows a fixed plan and is less adaptable to change once development begins.
  • Delivery Timing: Agile promotes early and frequent delivery of working software, providing tangible value to customers sooner. Waterfall delivers the entire product at the end of the development cycle.
  • Risk Management: Agile mitigates risks through incremental development, allowing for early detection and resolution of issues. Waterfall’s rigid structure may lead to late-stage discovery of problems, increasing project risk.

Q16. What is a dangling pointer?
Ans: Dangling Pointer: A dangling pointer is a pointer that points to a memory location that has been deallocated or freed, leading to unpredictable behavior when accessed. Dangling pointers often occur when memory is deallocated, but the corresponding pointer is not updated or invalidated, leaving it pointing to invalid memory.

Example:

int *ptr = (int *)malloc(sizeof(int)); // Allocate memory
free(ptr); // Deallocate memory
// ptr is now a dangling pointer

Q17. What are the similarities and differences between Shortest Job First (SJF) and Shortest Remaining Time First (SRTF) CPU scheduling algorithms?
Ans:
Similarities:

  • Both SJF and SRTF are non-preemptive scheduling algorithms.
  • They prioritize processes based on their burst time, executing the shortest jobs first.

Differences:

  • Preemption: SJF is non-preemptive, meaning once a process starts executing, it continues until completion. SRTF is preemptive, allowing shorter jobs to interrupt longer ones.
  • Burst Time Estimation: SJF requires accurate burst time estimation for each process before execution, while SRTF dynamically adjusts based on remaining burst time.
  • Response Time: SRTF typically results in shorter response times compared to SJF, as it allows shorter jobs to execute without waiting for longer ones to finish.
  • Context Switching Overhead: SRTF incurs more context switching overhead due to frequent preemptions, potentially affecting system performance.

Q18. Can you explain memory leaks?
Ans: Memory Leaks: Memory leaks occur in software when memory that is allocated dynamically is not released properly after it’s no longer needed, leading to a gradual depletion of available memory. Memory leaks can result in reduced system performance, increased resource consumption, and eventual application crashes.

Causes:

  • Unreleased Memory: Failure to release dynamically allocated memory using functions like free() in C or delete in C++.
  • Lost References: Losing references to allocated memory blocks without deallocating them, preventing access and reclamation.
  • Cyclic References: Circular references between objects, preventing garbage collection in languages with automatic memory management.

Impact:

  • Performance Degradation: Memory leaks can cause gradual performance degradation as available memory decreases.
  • Resource Exhaustion: Continued leakage can lead to resource exhaustion, causing system instability or crashes.
  • Debugging Challenges: Identifying and fixing memory leaks can be challenging, especially in complex applications.

Prevention:

  • Proper Memory Management: Ensure that dynamically allocated memory is released when it’s no longer needed.
  • Memory Profiling Tools: Use memory profiling tools to detect and diagnose memory leaks during development and testing.
  • Code Reviews: Conduct thorough code reviews to identify potential memory leaks and address them early in the development process.

Q19. List out the differences between Generalization and Specialization in DBMS?
Ans: Generalization:

  • Definition: Generalization is the process of combining multiple entities with similar attributes and behaviors into a more general superclass or higher-level entity.
  • Hierarchy: Generalization creates a hierarchy where the generalized entity becomes the parent (superclass), and the specific entities are its children (subclasses).
  • Attributes: Generalized entities inherit common attributes and behaviors from the superclass, promoting code reuse and simplifying maintenance.
  • Example: Animal (superclass) generalizes into Mammal, Reptile, and Bird (subclasses).

Specialization:

  • Definition: Specialization is the process of creating new entities (subclasses) from an existing generalized entity (superclass) by adding additional attributes or behaviors.
  • Extension: Specialization extends the capabilities of the superclass by defining more specific entities tailored to particular requirements.
  • Attributes: Specialized entities inherit attributes and behaviors from the superclass while adding unique characteristics specific to each subclass.
  • Example: Mammal (superclass) specializes into Dog, Cat, and Elephant (subclasses) with additional attributes like breed and habitat.

Q20. Write the steps to create, update and drop a view in SQL?
Ans: Creating a View:

CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Updating a View:

CREATE OR REPLACE VIEW view_name AS
SELECT new_column1, new_column2, ...
FROM new_table_name
WHERE new_condition;

Dropping a View:

DROP VIEW view_name;

Q21. What is an array?
Ans: Array: An array is a data structure that stores a collection of elements of the same data type in contiguous memory locations. Each element in the array is accessed by its index, which represents its position in the array. Arrays provide an efficient way to store and manipulate data, allowing random access to elements based on their indices.

Example:

int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
String[] names = {"Alice", "Bob", "Charlie"}; // Array of strings

Q22. Explain the mark and sweep algorithm?
Ans: Mark and Sweep Algorithm: The mark and sweep algorithm is a garbage collection algorithm used to reclaim memory occupied by unreachable objects. It consists of two phases: marking and sweeping.

1. Mark Phase:

  • Traversal: The algorithm traverses the entire object graph starting from known root objects (e.g., global variables, stack frames) and marks reachable objects as live.
  • Marking: Reachable objects are marked using a flag or a bit in their header to indicate their live status.

2. Sweep Phase:

  • Sweeping: The algorithm scans through the entire heap, deallocating memory for objects that are not marked as live (unreachable).
  • Reclamation: Memory occupied by unreachable objects is reclaimed and added back to the pool of available memory for future allocations.

Key Points:

  • Efficiency: Mark and sweep are efficient for reclaiming memory in systems where pauses due to garbage collection are acceptable.
  • Fragmentation: The algorithm may lead to fragmentation as memory is not compacted after reclaiming, potentially affecting memory utilization.
  • Reference Counting: Mark and sweep are often used in conjunction with reference counting to handle cyclic references and reclaim memory for unreachable cyclic structures.

Q23. Explain malloc?
Ans: malloc: malloc stands for “memory allocation” and is a standard library function in C and C++ used to dynamically allocate memory during runtime. It reserves a block of memory of a specified size and returns a pointer to the beginning of the allocated memory block.

Syntax:

void *malloc(size_t size);

Parameters:

  • size: The number of bytes to allocate.

Return Value:

  • If successful, malloc returns a pointer to the allocated memory block.
  • If memory allocation fails (e.g., due to insufficient memory), it returns NULL.

Example:

int *arr = (int *)malloc(5 * sizeof(int)); // Allocate memory for an integer array of size 5
if (arr != NULL) {
    // Memory allocation successful
} else {
    // Memory allocation failed
}

Q24. What is polymorphism in object-oriented programming? Give an example.
Ans: Polymorphism: Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables code reuse, flexibility, and extensibility in software design.

Types of Polymorphism:

  1. Compile-time Polymorphism: Achieved through method overloading and operator overloading.
  2. Runtime Polymorphism: Achieved through method overriding and dynamic method binding.

Example:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        animal1.sound(); // Output: Dog barks
        animal2.sound(); // Output: Cat meows
    }
}

In this example, Animal is a superclass, and Dog and Cat are subclasses. Despite being of different types, animal1 and animal2 can both invoke the sound method, demonstrating polymorphic behavior at runtime.

Q25. Explain the difference between an interpreter and a compiler?
Ans: Interpreter:

  • Execution: An interpreter translates source code into machine code line by line and executes it immediately.
  • Performance: Interpreters are generally slower than compilers because they translate and execute code simultaneously.
  • Feedback: Provides immediate feedback as errors are encountered during interpretation.
  • Examples: Python, JavaScript, Ruby.

Compiler:

  • Translation: A compiler translates the entire source code into machine code (object code) in one go before execution.
  • Execution: The compiled machine code is executed separately, often resulting in faster execution compared to interpretation.
  • Performance: Compilers optimize code during the translation process, potentially leading to better performance.
  • Examples: C, C++, Java (with JIT compilation).

Hybrid Approaches: Some programming languages use hybrid approaches, like Just-In-Time (JIT) compilation, which combines elements of interpretation and compilation. JIT compilers translate source code into machine code on-the-fly during execution, offering a balance between speed and flexibility.

Q26. What is recursion?
Ans: Recursion: Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. It allows problems to be broken down into smaller, more manageable subproblems, often resulting in elegant and concise solutions.

Key Elements:

  • Base Case: A termination condition that prevents infinite recursion and defines the smallest instance of the problem that can be solved directly.
  • Recursive Case: A case where the function calls itself with a smaller or simpler input, progressing towards the base case.

Example (Factorial Function):

public class Main {
    static int factorial(int n) {
        if (n == 0 || n == 1) { // Base case
            return 1;
        } else { // Recursive case
            return n * factorial(n - 1);
        }
    }
    
    public static void main(String[] args) {
        int result = factorial(5); // Output: 120
        System.out.println("Factorial of 5: " + result);
    }
}

In this example, the factorial function calls itself recursively with a smaller value of n until it reaches the base case (n = 0 or n = 1), at which point it returns 1. The intermediate results are multiplied together to compute the factorial of the original input.

Q27. Can you explain a string?
Ans: String: In programming, a string is a sequence of characters, typically used to represent text. Strings are one of the most commonly used data types in programming languages, providing operations for manipulation, comparison, and concatenation.

Characteristics:

  • Immutable: Strings are usually immutable, meaning their values cannot be changed once they are created. Operations like concatenation or substring creation return new string objects.
  • Encoding: Strings can be encoded using various character encodings, such as ASCII, UTF-8, or UTF-16, to represent characters from different languages and character sets.
  • Length: The length of a string is the number of characters it contains. It can be obtained using built-in functions or methods provided by programming languages.

Example:

String str = "Hello, World!";
System.out.println(str.length()); // Output: 13

In this example, str is a string containing the text “Hello, World!”. The length() method returns the length of the string, which is 13 characters.

Q28. What is a data type?
Ans: Data Type: In programming, a data type is a classification that specifies which type of value a variable can hold. It defines the operations that can be performed on the data, the meaning of the data, and the way values of that type can be stored.

Common Data Types:

  • Primitive Data Types: Integers, floating-point numbers, characters, booleans, etc.
  • Composite Data Types: Arrays, structures, classes, etc.
  • Abstract Data Types: Defined by the user to model specific concepts or entities in the problem domain.

Example:

int age = 30; // Integer data type
double price = 19.99; // Floating-point data type
char grade = 'A'; // Character data type
boolean isStudent = true; // Boolean data type

In this example, age is an integer variable, price is a floating-point variable, grade is a character variable, and isStudent is a boolean variable. Each variable is assigned a value of a specific data type.

Q29. What is an integer?
Ans: Integer: An integer is a whole number, positive or negative, without any decimal point. It represents a discrete value, typically used for counting or indexing purposes.

Characteristics:

  • Signed vs. Unsigned: Integers can be signed (capable of representing both positive and negative values) or unsigned (only positive values).
  • Range: The range of values an integer can represent depends on its size (number of bits) and whether it’s signed or unsigned.
  • Operations: Integers support arithmetic operations such as addition, subtraction, multiplication, and division.

Example:

int age = 30; // Signed integer
unsigned int count = 100; // Unsigned integer

In this example, age is a signed integer representing a person’s age, while count is an unsigned integer representing a count or quantity.

Q30. What is the OOPs concept?
Ans: OOPs Concept: Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods or functions). OOP focuses on structuring software around objects and their interactions, enabling modular, reusable, and maintainable code.

Key Concepts of OOP:

  • Encapsulation: Bundling data and methods that operate on the data into a single unit (class) and restricting access to the data through well-defined interfaces (access specifiers).
  • Inheritance: Defining new classes (subclasses or derived classes) based on existing ones (superclasses or base classes), inheriting their attributes and behaviors and allowing for code reuse and specialization.
  • Polymorphism: The ability of objects of different classes to be treated as objects of a common superclass, enabling code reuse, flexibility, and extensibility through method overriding and dynamic method binding.
  • Abstraction: Representing essential features of an entity while hiding unnecessary details, allowing complex systems to be modeled more effectively and reducing complexity for users and developers.

Example (Java):

class Animal {
    String name;
    
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.sound(); // Output: Dog barks
    }
}

In this example, Animal is a superclass, and Dog is a subclass inheriting from Animal. The main method demonstrates polymorphic behavior, treating a Dog object as an Animal, illustrating the key concepts of OOP.

How to apply for Cognizant ?


There are multiple avenues through which you can submit your application to Cognizant. These include utilizing employment websites, accessing Cognizant’s dedicated career portal, participating in recruitment events, leveraging the employee referral system, or seeking guidance from placement professionals.

Click here to visit Cognizant official website


Explore further details about the hiring processes and interview Q&A for related companies by clicking here.


Disclaimer: The provided Cognizant interview questions and answers for freshers are for educational purposes. While they offer valuable insights, the hiring process and interview details are subject to change at the discretion of the company. Individual experiences may vary, and success depends on various factors. Candidates are encouraged to supplement this resource with thorough preparation and adaptability to specific interview scenarios.

Good luck!