Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

TCS Java Language Questions

Last Updated on August 27, 2024 by Abhishek Sharma

The TCS National Qualifier Test (NQT) is a gateway for fresh graduates and entry-level professionals to start their careers with Tata Consultancy Services (TCS), one of the world’s leading IT services companies. The TCS NQT interview process is designed to evaluate candidates on various dimensions, including their technical expertise, problem-solving abilities, and communication skills. It typically involves multiple stages, including a written test, technical interview, and HR interview. Each stage is critical in determining a candidate’s suitability for a role at TCS.

This article serves as your comprehensive guide to tackling TCS Java interview questions. Whether you’re a fresh graduate eager to land your first job or an experienced developer aiming to advance your career, the insights presented here will help you grasp the essential topics and strategies required to succeed in your TCS Java interview questions. From fundamental Java concepts to advanced topics that TCS interviewers often explore, join us on a journey to hone your Java expertise and increase your chances of making a lasting impression in the competitive TCS interview process.

TCS Java Language Questions: Fundamentals

This section contains the list of TCS java language questions that were asked to candidates in recent Interviews.

Q – 1 What is the difference between JDK, JRE, and JVM?
Ans – JDK, JRE, and JVM are all related to Java programming language and are essential components of the Java platform. Here are the differences between them:

JDK (Java Development Kit):
JDK is a software development kit that includes all the tools required to develop, debug and deploy Java applications. It includes the Java compiler, Javadoc, Java Archive (JAR) files, and other development tools. JDK is used by developers who want to create Java applications and applets.

JRE (Java Runtime Environment):
JRE is a software package that provides the Java Virtual Machine (JVM), Java class libraries, and other components required to run Java applications. JRE is used by end-users who want to run Java applications on their machines. It does not include development tools such as the Java compiler.

JVM (Java Virtual Machine):
JVM is a virtual machine that provides an environment in which Java bytecode can be executed. It interprets compiled Java code and provides a runtime environment for executing Java programs. The JVM is an essential component of both the JDK and JRE. It provides platform independence to Java applications, meaning that Java code can be run on any machine with a JVM installed, regardless of the underlying hardware and operating system.

Q – 2 Difference between String, String Builder, and String Buffer.
Ans – In Java, String, StringBuilder, and StringBuffer are all classes used to represent text. Here are the differences between them:

String:
A string is an immutable class, which means that once a String object is created, its value cannot be changed. Every time a modification is made to a String object, a new String object is created. This can be inefficient for large strings or frequent modifications. String objects are thread-safe, making them suitable for use in multi-threaded applications.

StringBuilder:
StringBuilder is a mutable class, which means that its value can be modified without creating a new object. It is more efficient than String when it comes to frequent modifications to the text. It is not thread-safe, however, so it is not recommended to use it in multi-threaded applications.

StringBuffer:
StringBuffer is similar to StringBuilder in that it is a mutable class that can be modified without creating a new object. The main difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe, making it suitable for use in multi-threaded applications. However, its use can result in performance overhead, especially in single-threaded applications.

Q – 3 What is Serialization in Java?
Ans – Serialization in Java is the process of converting an object into a stream of bytes, which can be saved to a file or transmitted over a network, and later restored to an object with the same state as before serialization. This process allows objects to be saved and restored across different platforms, programming languages, or even time.

To make an object serializable, the class needs to implement the java.io.Serializable interface. This interface is a marker interface, meaning it has no methods, and its sole purpose is to indicate that the class can be serialized.

The serialization process is done using the ObjectOutputStream class, which writes the object to an output stream, and the deserialization process is done using the ObjectInputStream class, which reads the object from an input stream.

The serialized object contains the data of the object, along with information about the class’s type, fields, and methods. When the object is deserialized, this information is used to recreate the object with the same state as before serialization.

Q – 4 What are List, Set, and Map in Java?
Ans – In Java, List, Set, and Map are interfaces used to represent collections of objects. Here are the differences between them:

List:
A list is an interface used to represent an ordered collection of elements. It allows duplicates, and its elements can be accessed using an index. The most commonly used implementation of the List interface is the ArrayList, which provides dynamic resizing of the list, making it suitable for situations where the size of the list is unknown or can change dynamically.

Set:
A Set is an interface used to represent an unordered collection of unique elements. It does not allow duplicates, and its elements cannot be accessed using an index. The most commonly used implementation of the Set interface is the HashSet, which provides constant-time performance for the basic operations, such as adding, removing, and checking if an element is present in the set.

Map:
A map is an interface used to represent a collection of key-value pairs. Each key is unique, and its associated value can be accessed using the key. The most commonly used implementation of the Map interface is the HashMap, which provides constant-time performance for basic operations, such as adding, removing, and retrieving an element.

Q – 5 What is the difference between checked and unchecked exceptions?
Ans – In Java, exceptions can be classified into two types: checked exceptions and unchecked exceptions.

Checked Exceptions:
Checked exceptions are the exceptions that the Java compiler forces the programmer to handle or declare in the method signature using the throws keyword. They are checked at compile-time, meaning that the code will not compile unless the exception is caught or declared to be thrown. These exceptions typically represent errors that are recoverable and are expected to occur during normal program execution, such as file not found or database connection failure.

Unchecked Exceptions:
Unchecked exceptions are the exceptions that the Java compiler does not force the programmer to handle or declare in the method signature. They are not checked at compile-time, meaning that the code will compile whether or not the exception is caught or declared to be thrown. These exceptions typically represent programming errors that are not recoverable and should be avoided by fixing the code.

Q – 6 why do we use static keyword when writing the main method in Java?
Ans – In Java, the static keyword is used in the declaration of the main method to indicate that the method is a class method and can be called without an instance of the class being created.

The main method is the entry point for the Java application, and it must be declared as a public static void method in order to be executed by the Java Virtual Machine (JVM). The public keyword indicates that the method can be accessed from outside the class, the void keyword indicates that the method does not return a value, and the static keyword indicates that the method can be called without an instance of the class being created.

The reason for using the static keyword in the declaration of the main method is that the JVM needs to be able to call the main method without creating an instance of the class. If the main method were not declared as static, the JVM would need to create an instance of the class before calling the main method, which would not be appropriate for an entry point method.

By declaring the main method as static, we ensure that the method can be called by the JVM without creating an instance of the class and that it has access to all the static members of the class. This allows us to write code in the main method that initializes the static members of the class or uses other static methods and variables.

Q – 7 What is the lambda expression in Java?
Ans – Lambda expressions are a new feature introduced in Java 8 that allows the creation of anonymous functions. A lambda expression is a short block of code that takes in parameters, executes an expression or a block of statements, and returns a value or void.

Lambda expressions are commonly used when working with functional interfaces, which are interfaces that have only one abstract method. They provide a concise and easy-to-read way to implement the abstract method of a functional interface, making it easier to write functional-style code.

The syntax is as follows:

(parameter_list) -> { body }

where parameter_list is a comma-separated list of parameters, and body is the code to be executed.

For example, the following code creates a lambda expression that takes two integers and returns their sum:

(int x, int y) -> x + y

Lambda expressions can be used in various places in Java, such as in the implementation of functional interfaces, in streams, and in parallel processing.

Q – 8 What is the difference between a HashMap and a TreeMap in Java?
Ans – Both HashMap and TreeMap are classes that implement the Map interface in Java, but they differ in their underlying data structure and performance characteristics.

Here are some of the key differences between HashMap and TreeMap:

  • Performance: HashMap is generally faster than TreeMap for most operations, especially for large datasets. The average time complexity of HashMap is O(1), while that of TreeMap is O(log n).
  • Ordering: HashMap does not maintain the order of key-value pairs, while TreeMap maintains the natural ordering of keys.
  • Null keys: HashMap allows null keys, while TreeMap does not allow null keys.
  • Iteration: HashMap provides faster iteration over the key-value pairs than TreeMap.

Q – 9 What is Weak Hash Map?
Ans – Weak Hash Map is a class in Java that implements the Map interface and provides a way to store key-value pairs in which the keys are weakly referenced. This means that if a key has no strong references to it, and only weak references exist, then it may be garbage collected, allowing its associated value to be removed from the WeakHashMap.

The use of weak references in WeakHashMap can be useful in situations where we want to cache values associated with objects, but don’t want to keep those objects in memory if they are no longer being used. By using weak references, we can allow the garbage collector to reclaim memory for objects that are no longer needed, which can help to reduce memory usage in our applications.

Q – 10 What do you mean by String Immutability in Java?
Ans – In Java, a String is immutable, which means that once a String object is created, its value cannot be changed. If we attempt to modify the contents of a String object, a new String object will be created with the modified value. This is in contrast to mutable objects, such as arrays or collections, whose values can be modified directly.

For example, consider the following code:

String str = "Hello";
str.concat(" World");
System.out.println(str);

In this code, we create a String object with the value "Hello". We then attempt to concatenate the value " World" to the String using the concat() method. However, this does not modify the original String object. Instead, a new String object is created with the value "Hello World", which is then discarded, as we don’t assign it to any variable. Finally, we print the original String object, which still has the value "Hello".

The immutability of String objects has several benefits in Java. It makes String objects thread-safe, which means that they can be safely used in a multi-threaded environment without the need for synchronization. It also allows String objects to be used as keys in Map implementations, as their hash codes are fixed and cannot change.

TCS Java Language Questions: Coding

Here are some Java coding questions that were asked in TCS Coding Round.

Q1. Write a Java program to find the largest and second largest number in an array of integers.
Ans –

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes {
    public static void findLargestAndSecondLargest(int[] arr) {
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > largest) {
                secondLargest = largest;
                largest = arr[i];
            } else if (arr[i] > secondLargest && arr[i] != largest) {
                secondLargest = arr[i];
            }
        }

        System.out.println("Largest: " + largest);
        System.out.println("Second Largest: " + secondLargest);
    }

    public static void main(String[] args) {
        int[] arr = {4,6,1,12,8,9,7,5,15};
        findLargestAndSecondLargest(arr);
    }
}

Input:

4 6 1 12 8 9 7 5 15

Output:

Largest: 15
Second Largest: 12

Q2. Write a Java program to find the length of the longest increasing subarray in an array.
Ans –

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes {
    public static int findLengthOfLongestIncreasingSubarray(int[] arr) {
        int maxLen = 1;
        int curLen = 1;

        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > arr[i - 1]) {
                curLen++;
            } else {
                maxLen = Math.max(maxLen, curLen);
                curLen = 1;
            }
        }

        return Math.max(maxLen, curLen);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 1, 2, 3, 4, 5, 6, 7};
        int length = findLengthOfLongestIncreasingSubarray(arr);
        System.out.println("Length of longest increasing subarray: " + length);
    }
}

Input:

Given array : [1 2 3 1 2 3 4 5 6 7]

Output:

Length of longest increasing subarray: 7

Q3. Write a Java program that deletes all white spaces from a string.
Ans –

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes{
    public static void main(String[] args) {
        String str = "   Hello,   World!   ";
        String result = str.replaceAll("\\s", "");
        System.out.println("Original String: \"" + str + "\"");
        System.out.println("String with no spaces: \"" + result + "\"");
    }
}

Output:

Original String: “   Hello,   World!    ”
String with no spaces: “Hello,World!”

Q4. Write a Java program for the Spiral Traversal of a Matrix in Java.
Ans –

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes {
    public static void printSpiral(int[][] matrix) {
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) {
                System.out.print(matrix[top][i] + " ");
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                System.out.print(matrix[i][right] + " ");
            }
            right--;

            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    System.out.print(matrix[bottom][i] + " ");
                }
                bottom--;
            }

            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    System.out.print(matrix[i][left] + " ");
                }
                left++;
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        printSpiral(matrix);
    }
}

Input:

1 2 3 4
5 6 7 8
9 10 11 12

Output:

1 2 3 4 8 12 11 10 9 5 6 7

Conclusion
The TCS NQT interview experience is a comprehensive assessment of a candidate’s abilities, both technical and non-technical. Success in this process requires a strong understanding of core subjects, practical problem-solving skills, and effective communication. By thoroughly preparing for each stage of the interview, candidates can enhance their chances of securing a position at TCS. The experience not only tests knowledge but also gives insight into the expectations and work culture of one of the top IT firms in the world.

FAQs Related to TCS IPA Java Coding Questions

Here are some Frequently Asked Questions on TCS Java Language Questions

Q1: What topics should I focus on for the TCS NQT technical interview?
A1:
For the technical interview, focus on programming languages like C, C++, Java, or Python, data structures, algorithms, database management, operating systems, and basic concepts of computer science. Be prepared to solve coding problems and explain your approach.

Q2: How can I prepare for the TCS NQT written test?
A2:
To prepare for the written test, practice quantitative aptitude, logical reasoning, verbal ability, and basic programming questions. There are numerous online resources, practice papers, and mock tests available that can help you get familiar with the question patterns.

Q3: What can I expect in the HR interview during the TCS NQT process?
A3:
The HR interview typically focuses on your resume, communication skills, career aspirations, understanding of TCS as a company, and your willingness to work in different roles or locations. Be honest and confident in your responses.

Q4: Is previous project experience important for the TCS NQT interview?
A4:
Yes, previous project experience is important, especially in the technical interview. Be ready to discuss your projects in detail, including the technologies used, your role in the project, and the challenges you faced.

Q5: How long does the TCS NQT interview process take?
A5:
The entire TCS NQT interview process can take several weeks, depending on the number of candidates and scheduling. The written test results are usually followed by the technical and HR interviews within a few days to a week.

Leave a Reply

Your email address will not be published. Required fields are marked *