TCS Java Interview Questions

TCS Java Interview Questions

On August 21, 2024, Posted by , In Interview Questions,Java, With Comments Off on TCS Java Interview Questions
TCS Java interview Questions & Answers

Table of contents

Tata Consultancy Services (TCS) is a global leader in IT services, consulting, and business solutions, renowned for its commitment to innovation and excellence. With a presence in over 46 countries, TCS offers a wide range of services, including software development, cloud computing, AI, and machine learning. As part of its continuous growth and expansion, TCS regularly seeks skilled Java developers who can contribute to its diverse projects and maintain its position as a technology leader. The hiring process at TCS is rigorous, designed to identify candidates with strong technical skills, problem-solving abilities, and a deep understanding of Java programming.

Preparing for a TCS Java interview requires a thorough understanding of core Java concepts, frameworks, and real-world application scenarios. By focusing on commonly asked interview questions, candidates can gain a competitive edge, demonstrating their knowledge and readiness for the challenges they might face on the job. This collection of TCS Java interview questions covers essential topics such as object-oriented programming, exception handling, collections framework, multi-threading, and Java 8 features, among others. Mastering these questions not only helps in cracking the TCS interview but also builds a solid foundation for a successful career in Java development.

Join our real-time project-based Java training in Hyderabad for comprehensive guidance on mastering Java and acing your interviews. We offer hands-on training and expert interview preparation to help you succeed in your Java career.

1. What are the main principles of Object-Oriented Programming (OOP) in Java?

The main principles of Object-Oriented Programming (OOP) in Java are encapsulation, inheritance, polymorphism, and abstraction.

  • Encapsulation: Encapsulation is the bundling of data and methods that operate on that data within a single unit, typically a class. It restricts direct access to some of an object’s components, which can help prevent the accidental modification of data.
  • Inheritance: Inheritance is a mechanism where one class (child class) inherits the fields and methods of another class (parent class). This promotes code reuse and establishes a natural hierarchy.
  • Polymorphism: Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. The most common use of polymorphism is when a parent class reference is used to refer to a child class object.
  • Abstraction: Abstraction involves hiding the complex implementation details and showing only the essential features of the object. This can be achieved using abstract classes and interfaces.

2. Explain the concept of inheritance in Java. How does it differ from composition?

Inheritance in Java is a mechanism where one class (subclass or derived class) inherits the fields and methods of another class (superclass or base class). This allows the subclass to use the methods and properties of the superclass without having to rewrite the code. It also allows for method overriding, where a subclass can provide a specific implementation of a method that is already defined in its superclass.

Composition, on the other hand, is a design principle where a class is composed of one or more objects of other classes. This means that instead of inheriting behavior, a class achieves functionality by containing instances of other classes that implement the desired behavior. Composition is often preferred over inheritance because it provides greater flexibility and avoids issues related to the tight coupling of classes.

Read more: Arrays in Java interview Questions and Answers

3. What is polymorphism in Java? Provide examples of compile-time and runtime polymorphism.

Polymorphism in Java is the ability of a single action to operate in different ways. There are two types of polymorphism in Java: compile-time (static) polymorphism and runtime (dynamic) polymorphism.

Compile-time Polymorphism:

This is achieved through method overloading. Method overloading occurs when a class has multiple methods with the same name but different parameters (different type, number, or both). The method to be called is determined at compile-time.
Example:

public class MathUtils {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}

Runtime Polymorphism: This is achieved through method overriding. Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method to be called is determined at runtime.
Example:

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

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

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound();  // Outputs "Dog barks"
    }
}

4. Describe exception handling in Java. What are checked and unchecked exceptions?

Exception handling in Java is a powerful mechanism that handles runtime errors, allowing the normal flow of the program to be maintained. The core of Java’s exception handling is the try-catch block.

  • Checked Exceptions: These are exceptions that are checked at compile-time. The Java compiler checks if the program handles these exceptions or not. If a method is throwing a checked exception, it should either handle the exception using a try-catch block or declare it using the throws keyword.Example: IOException, SQLException.
  • Unchecked Exceptions: These are exceptions that are not checked at compile-time. These include errors and runtime exceptions. The program does not require any explicit handling of these exceptions.Example: ArrayIndexOutOfBoundsException, NullPointerException.

Read more: Accenture Java interview Questions and Answers

5. Explain the use of the ‘final’ keyword in Java. Where can it be applied?

The final keyword in Java can be used to define an entity that cannot be modified. It can be applied in three contexts: variables, methods, and classes.

  • Final Variables: When a variable is declared as final, its value cannot be changed once initialized. This makes the variable a constant.
    Example:final int MAX_VALUE = 100;
  • Final Methods: A final method cannot be overridden by subclasses. This is used to prevent altering the behavior of the method in the subclass.
    Example:
public final void display() { 
System.out.println("This is a final method."); 
}
  • Final Classes: A final class cannot be subclassed. This is used to prevent inheritance.
    Example:
public final class Constants { 
// class definition 
}

6. What is the Java Collections Framework? Name some of the key interfaces and classes.

The Java Collections Framework (JCF) is a unified architecture for representing and manipulating collections of objects. It includes a set of interfaces and classes to handle collections, allowing developers to perform various operations such as searching, sorting, insertion, manipulation, and deletion.

Key interfaces in the Java Collections Framework include:

  • Collection: The root interface of the collection hierarchy.
  • List: An ordered collection (also known as a sequence).
  • Set: A collection that does not contain duplicate elements.
  • Queue: A collection designed for holding elements prior to processing.
  • Map: An object that maps keys to values, not technically part of the Collection interface hierarchy but part of the framework.

Key classes in the Java Collections Framework include:

  • ArrayList: Implements the List interface, backed by a dynamic array.
  • HashSet: Implements the Set interface, backed by a hash table.
  • LinkedList: Implements both List and Deque interfaces, backed by a doubly linked list.
  • HashMap: Implements the Map interface, backed by a hash table.
  • TreeMap: Implements the Map interface, backed by a Red-Black tree.

Read more: List Class in Salesforce Apex

7. How does Java handle memory management and garbage collection?

Java handles memory management through an automatic process called garbage collection. The Java Virtual Machine (JVM) automatically manages memory allocation and deallocation, so developers do not need to explicitly free memory, unlike in languages like C or C++.

  • Memory Management: Java’s memory model is divided into several parts, including the heap and the stack. Objects are allocated memory on the heap, while references to these objects and primitive data types are stored on the stack.
  • Garbage Collection: The JVM has a garbage collector that automatically deallocates memory that is no longer in use, freeing up resources for new objects. When there are no references to an object, it becomes eligible for garbage collection. The garbage collector periodically scans the heap to identify and remove these unreferenced objects, helping to prevent memory leaks and optimize memory usage.

8. Describe the differences between an interface and an abstract class in Java.

An interface and an abstract class in Java are both used to achieve abstraction but have some key differences:

  • Interface:
    • An interface can have only abstract methods (until Java 8, where default and static methods were introduced).An interface cannot have instance variables, only constants (static final variables).A class can implement multiple interfaces, allowing for multiple inheritance.Methods in an interface are implicitly public and abstract.
    Example:public interface Animal { void eat(); }
  • Abstract Class:
    • An abstract class can have both abstract and concrete methods.An abstract class can have instance variables.A class can extend only one abstract class (single inheritance).Methods in an abstract class can have any visibility: public, protected, or private.
    Example:
public abstract class Animal { 
public abstract void eat(); public void sleep() { System.out.println("Sleeping..."); 
} 
}

9. What are lambda expressions in Java? How do they improve code readability and functionality?

Lambda expressions, introduced in Java 8, are a way to define anonymous methods (functions) in a concise and functional style. They enable developers to write cleaner and more readable code, especially when dealing with collections and functional interfaces.

A lambda expression consists of three parts:

  • A comma-separated list of formal parameters enclosed in parentheses.
  • An arrow token (->).
  • A body that consists of a single expression or a block of code.

Example:

// Traditional way
Runnable r1 = new Runnable() {
    public void run() {
        System.out.println("Hello, world!");
    }
};

// Using lambda expression
Runnable r2 = () -> System.out.println("Hello, world!");

Lambda expressions improve code readability by reducing boilerplate code, making it easier to understand and maintain. They also enhance functionality by enabling the use of functional programming features like streams and higher-order functions.

Read more: Scenario Based Java Interview Questions [2024]

10. Explain the significance of the ‘transient’ and ‘volatile’ keywords in Java.

  • Transient:

The transient keyword is used in the context of serialization. When an instance variable is declared as transient, it will not be serialized. This means that the variable’s value will not be saved when the object is written to an output stream, and it will be ignored during the serialization process.

Example:

class Employee implements Serializable { 
private String name; 
private transient int age; // 'age' will not be serialized 
}
  • Volatile:
    • The volatile keyword is used in the context of multi-threading. When a variable is declared as volatile, it means that the value of the variable will always be read from and written to the main memory. This ensures visibility and consistency of the variable’s value across multiple threads.
    Example:
public class SharedData { 
private volatile boolean flag = true; 
}

11. Write a Java program to reverse a string without using built-in reverse functions.

public class ReverseString {
    public static void main(String[] args) {
        String original = "Hello, World!";
        String reversed = reverse(original);
        System.out.println("Reversed string: " + reversed);
    }

    public static String reverse(String str) {
        char[] charArray = str.toCharArray();
        int left = 0, right = charArray.length - 1;
        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
            left++;
            right--;
        }
        return new String(charArray);
    }
}

This program converts the input string into a character array to manipulate individual characters. It uses two pointers: one starting from the beginning (left) and the other from the end (right) of the array. The characters at these positions are swapped, and the pointers are moved towards each other until they meet in the middle. This effectively reverses the string.

12. Implement a Java program to find the factorial of a given number using recursion.

public class Factorial {
    public static void main(String[] args) {
        int number = 5;
        int result = factorial(number);
        System.out.println("Factorial of " + number + " is: " + result);
    }

    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        }
        return n * factorial(n - 1);
    }
}

The program calculates the factorial of a given number using a recursive approach. The factorial method calls itself with decremented values of the input number (n). The base case for the recursion is when n is 0, returning 1. For all other values, the method returns n multiplied by the factorial of n-1.

13. Write a Java program to check if a given number is a prime number.

public class PrimeNumber {
    public static void main(String[] args) {
        int number = 29;
        boolean isPrime = isPrime(number);
        if (isPrime) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }
    }

    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

The program checks if a number is prime by verifying that it is greater than 1 and has no divisors other than 1 and itself. It iterates from 2 to the square root of the number, checking if any number divides it without a remainder. If such a divisor is found, the number is not prime; otherwise, it is prime.

14. Implement a Java program to sort an array of integers using the bubble sort algorithm.

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        bubbleSort(arr);
        System.out.println("Sorted array: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    // swap arr[j] and arr[j + 1]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

This program sorts an array using the bubble sort algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the array is sorted. The largest unsorted element “bubbles” to its correct position in each iteration, reducing the unsorted portion of the array.

15. Write a Java program to find the longest substring without repeating characters.

import java.util.HashSet;
import java.util.Set;

public class LongestSubstring {
    public static void main(String[] args) {
        String str = "abcabcbb";
        String result = longestSubstringWithoutRepeating(str);
        System.out.println("Longest substring without repeating characters: " + result);
    }

    public static String longestSubstringWithoutRepeating(String str) {
        int n = str.length();
        int maxLength = 0;
        int start = 0;
        String longest = "";
        Set<Character> set = new HashSet<>();

        for (int end = 0; end < n; end++) {
            while (set.contains(str.charAt(end))) {
                set.remove(str.charAt(start));
                start++;
            }
            set.add(str.charAt(end));
            if (end - start + 1 > maxLength) {
                maxLength = end - start + 1;
                longest = str.substring(start, end + 1);
            }
        }
        return longest;
    }
}

The program finds the longest substring without repeating characters using a sliding window technique. It uses two pointers (start and end) and a set to track characters in the current window. As the end pointer moves through the string, characters are added to the set. If a duplicate character is found, the start pointer is moved to the right until the duplicate is removed. The length of the longest window without duplicates is tracked and updated throughout the process.

Comments are closed.