TCS Interview Questions

Certainly! Tata Consultancy Services (TCS) technical interviews can vary depending on the role and technology stack, but they generally cover a broad range of technical topics. Here's a detailed list of 20 common technical interview questions that you might encounter at TCS, along with comprehensive answers.

1.What is the difference between a class and an object in OOP?

Answer: In Object-Oriented Programming (OOP), a class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have. An object, on the other hand, is an instance of a class. While a class is a concept or a definition, an object is a concrete instance of that class in memory, with actual values assigned to the attributes.

Example
// Class definition class Car { String color; int year; void drive() { System.out.println("Driving"); } } // Object instantiation Car myCar = new Car(); myCar.color = "Red"; myCar.year = 2020; myCar.drive();

2. Explain the concept of inheritance in Java.

Answer: Inheritance is a fundamental concept in OOP where one class (subclass or child class) inherits the attributes and methods of another class (superclass or parent class). This allows for code reusability and establishes a hierarchical relationship between classes. In Java, inheritance is achieved using the extends keyword.

Example
// Superclass class Animal { void eat() { System.out.println("This animal eats food."); } } // Subclass class Dog extends Animal { void bark() { System.out.println("The dog barks."); } } // Usage Dog myDog = new Dog(); myDog.eat(); // Inherited method myDog.bark(); // Subclass-specific method

3. What is polymorphism in OOP?

Answer: Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. The two types of polymorphism in Java are method overloading and method overriding.

  • Method Overloading: Methods with the same name but different parameters within the same class.

  • Example
    class Display { void show(int a) { System.out.println("Integer: " + a); } void show(String a) { System.out.println("String: " + a); } }
  • Method Overriding: Subclass provides a specific implementation of a method that is already defined in its superclass.

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

4. What are Java Collections? Name some commonly used collections.

Answer: Java Collections are a framework that provides various classes and interfaces for storing and manipulating groups of objects. They allow for data storage, retrieval, manipulation, and aggregation.

Commonly used collections:

  • List: Ordered collection allowing duplicates. Examples: ArrayList, LinkedList.
  • Set: Unordered collection with no duplicates. Examples: HashSet, LinkedHashSet.
  • Queue: Collection used for holding elements prior to processing. Examples: LinkedList (implements Queue), PriorityQueue.
  • Map: Collection of key-value pairs. Examples: HashMap, TreeMap.

5. Explain the concept of encapsulation with an example.

Answer: Encapsulation is the bundling of data (attributes) and methods (behaviors) that operate on the data into a single unit, typically a class, and restricting access to some of the object's components. This is done to protect the internal state of the object from unintended interference and misuse.

Example
class Person { private String name; // Private variable public String getName() { // Public getter method return name; } public void setName(String name) { // Public setter method this.name = name; } } Person person = new Person(); person.setName("John Doe"); System.out.println(person.getName());

6. What is a constructor in Java?

Answer: A constructor is a special method in a class that is called when an object is instantiated. It initializes the newly created object. Constructors have the same name as the class and do not have a return type.

Example
class Person { String name; // Constructor Person(String name) { this.name = name; } } Person person = new Person("Alice"); System.out.println(person.name);

7. What is the difference between == and equals() in Java?

Answer:

  • == Operator: Checks if two references point to the same object in memory (i.e., it checks for reference equality).
  • equals() Method: Checks if the values of two objects are the same (i.e., it checks for value equality). The equals() method should be overridden in custom classes to provide meaningful equality comparison.
Example
String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1 == str2); // False, different references System.out.println(str1.equals(str2)); // True, same value

8. Explain the concept of exception handling in Java.

Answer: Exception handling in Java is a mechanism to handle runtime errors, allowing the normal flow of the program to be maintained. It is done using the try, catch, finally, and throw keywords.

  • try Block: Contains code that might throw an exception.
  • catch Block: Catches and handles the exception.
  • finally Block: Executes code after the try and catch blocks, regardless of whether an exception occurred or not.
  • throw Keyword: Used to explicitly throw an exception.
Example
try { int result = 10 / 0; // This will throw ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } finally { System.out.println("This will always execute."); }

9. What is the use of the final keyword in Java?

Answer: The final keyword in Java can be used in three contexts:

  • Final Variable: Once assigned, its value cannot be changed.
  • Final Method: Cannot be overridden by subclasses.
  • Final Class: Cannot be subclassed.
Example
final int MAX_VALUE = 100; // Final variable class A { final void display() { // Final method System.out.println("This is a final method."); } } class B extends A { // Cannot override display() method from A }

10. What is a thread in Java?

Answer: A thread in Java is a lightweight subprocess, the smallest unit of processing. It allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Threads can be created by implementing the Runnable interface or extending the Thread class.

Example
class MyThread extends Thread { public void run() { System.out.println("Thread is running."); } } MyThread t1 = new MyThread(); t1.start(); // Starts the thread

11. What is the difference between ArrayList and LinkedList in Java?

Answer:

  • ArrayList: Uses a dynamic array to store elements. It provides fast random access but slower insertion and deletion operations compared to LinkedList.
  • LinkedList: Uses a doubly linked list. It provides fast insertion and deletion operations but slower random access compared to ArrayList.
Example
ArrayList<'Integer> arrayList = new ArrayList<'>(); arrayList.add(1); arrayList.add(2); LinkedList linkedList = new LinkedList<'>(); linkedList.add(1); linkedList.add(2);

12. What is the Singleton design pattern?

Answer: The Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance. It is used to control access to a resource that is shared across the application.

Example
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

13. Explain the difference between abstract class and interface in Java.

Answer:

  • Abstract Class: Can have both abstract (unimplemented) methods and concrete (implemented) methods. It can have fields, constructors, and access modifiers.
  • Interface: Can only have abstract methods (from Java 8 onwards, it can have default and static methods). Fields in an interface are implicitly public, static, and final. Interfaces are used to achieve abstraction and multiple inheritance.
Example
// Abstract class abstract class Animal { abstract void makeSound(); void sleep() { System.out.println("Sleeping"); } } // Interface interface Animal { void makeSound(); default void sleep() { System.out.println("Sleeping"); } }

14. What is the purpose of synchronized keyword in Java?

Answer: The synchronized keyword is used to ensure that only one thread can access a block of code or method at a time, thereby preventing thread interference and memory consistency errors. It can be applied to methods or blocks of code.

Example
class Counter { private int count = 0; public synchronized void increment() { // Synchronized method count++; } }

15. Explain the concept of JDBC in Java.

Answer: Java Database Connectivity (JDBC) is a Java API that enables Java applications to interact with databases. It provides methods to execute SQL queries, update data, and retrieve results.

Basic Steps in JDBC:

  1. Load the Driver: Class.forName("com.mysql.jdbc.Driver");
  2. Establish Connection: Connection con = DriverManager.getConnection(url, user, password);
  3. Create Statement: Statement stmt = con.createStatement();
  4. Execute Query: ResultSet rs = stmt.executeQuery("SELECT * FROM table");
  5. Process Result: while (rs.next()) { ... }
  6. Close Resources: rs.close(); stmt.close(); con.close();

16. What is a deadlock in multithreading? How can it be avoided?

Answer: A deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources. This happens when each thread holds a resource and waits for additional resources held by other threads.

To avoid deadlock:

  1. Avoid Nested Locks: Avoid holding multiple locks at once.
  2. Lock Ordering: Always acquire locks in a consistent order.
  3. Timeouts: Use timeouts for lock acquisition.
  4. Deadlock Detection: Implement detection mechanisms to handle deadlock situations.

17. What is the difference between throw and throws in Java?

Answer:

  • throw: Used to explicitly throw an exception from a method or block of code.
  • throws: Used in a method signature to declare that a method can throw one or more exceptions, which must be handled by the calling method.
Example
// Using throw public void validate(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be 18 or older"); } } // Using throws public void readFile(String file) throws IOException { // Code that might throw IOException }

18. What is a lambda expression in Java?

Answer: A lambda expression in Java is a concise way to represent an anonymous function (method) that can be passed around and executed. Lambda expressions are used primarily to implement functional interfaces.

Stntax
(parameters) -> expression
Example
list = Arrays.asList("a", "b", "c"); list.forEach(s -> System.out.println(s)); // Lambda expression

19. What is the difference between HashMap and TreeMap in Java?

Answer:

  • HashMap: Stores key-value pairs in a hash table. It does not maintain any order of elements and allows null keys and values. It offers constant-time performance for basic operations.
  • TreeMap: Implements the NavigableMap interface and stores elements in a red-black tree. It maintains a sorted order of keys based on their natural ordering or a comparator provided at map creation. It does not allow null keys.
Example
HashMap<Integer, String> hashMap = new HashMap<>(); hashMap.put(1, "A"); hashMap.put(2, "B"); TreeMap<Integer, String> treeMap = new TreeMap<>(); treeMap.put(1, "A"); treeMap.put(2, "B");

20. What is the purpose of the transient keyword in Java?

Answer: The transient keyword is used to indicate that a field should not be serialized when an object is converted to a byte stream. This is useful for fields that contain sensitive information or are not needed in the serialized form.

Example
class Employee implements Serializable { private String name; private transient int ssn; // ssn will not be serialized }

These answers cover fundamental concepts and common interview topics, but TCS interviews may also include questions specific to the technologies or languages relevant to the position you are applying for. It's always a good idea to review job-specific requirements and practice coding problems related to those technologies.

Next Article ❯