Top 40 TCS Java Developer Interview Questions [with Answers]
Java is one of the most versatile programming languages as it offers libraries, frameworks, and tools for creating various applications and websites. Due to its versatility many top companies such as TCS actively hire Java developers. In order to work as a Java developer at TCS, you need to clear their technical interview rounds. To help you with this, we have compiled some top TCS Java developer interview questions with the best answers to help ace your interview.
Tata Consultancy Services (TCS): An Overview
It is essential to have a strong understanding of the company you’re applying to work for before moving on to the questions. There are high chances that you can get asked about the company, its history, or any recent developments. Here’s a brief overview of TCS.
What is TCS?
Tata Consultancy Services or TCS is an IT service and consultancy company, renowned for its innovative solutions to help businesses grow. They aim to touch every life and make a positive impact through technology. Working in this industry for the last 50 years, they offer various services such as IT consulting, cyber security, cloud, data analytics, and enterprise solutions across industries.
TCS Hiring Process
TCS has a well-crafted hiring process that assesses your skills, knowledge, and other attributes. To be eligible for the interview, you need to have a 60% or above aggregate in all your academic qualifications (i.e. 10th, 12th, and Bachelor’s/Master’s degree) without any backlogs.
The hiring process broadly consists of a written test followed by three interview rounds. The written test or aptitude test, assesses your verbal aptitude, quantitative ability, and logical reasoning.
The test is 80 minutes long with a total of 35 questions and a negative marking of 0.33 per wrong answer. It is the first step of the interview process. Once you clear this round, the interview rounds will begin. Practice some aptitude test questions and answers before appearing for the test to get a hang of it.
You will have to excel in the following rounds to land a job at TCS:
- HR Interview Round: This is conducted to get a clear picture of your experience, skills, qualifications, knowledge about the company, and why you wish to work with TCS, among other things. With the HR round, the HR manager assesses whether you are a good fit for the position and the company.
- Group Discussion (GD) Round: In this round, you will be provided with a topic relevant to your applied position. You will be asked to have a discussion on the given topic with your group members for about 15-20 minutes.
- Technical Interview Round: Here, your technical skills and knowledge will be tested. The questions will generally be related to the position you have applied. Questions could be asked about various topics such as Java, Python, SQL, and coding.
- Managerial Interview Round: In this round, you will be interviewed by the manager of the team who will examine your leadership skills, decision-making skills, conflict resolution ability, and teamwork.
Also Read: TCS Interview Questions and Answers
TCS Java Interview Questions for Freshers
Here are some TCS Java developer interview questions for freshers to help you prepare for the technical interview round.
Q1. What is inheritance in Java?
Answer: Inheritance in Java refers to the new class or sub-class inheriting properties, functionalities, and behavior from the existing class or superior class. Additionally, it reduces redundancy, allows code reusability, and provides a clearer code structure.
Q2. What are the various benefits of a database management system?
Answer: Database management system or DBMS is a software that assists in organizing, managing, and systematically accessing data. The benefits of DBMS are as follows:
- Improved data integrity and consistency by reducing redundancy and enforcing rules and relationships.
- Enhanced data security by restricting unauthorized access.
- Better data backup and recovery due to efficient data recovery mechanisms preventing accidental deletions and cyberattacks.
- Improved data-driven decision-making by providing access to consistent and organized data.
Q3. Define a schema.
Answer: A schema in database management is essentially a blueprint of a database. It defines how data is organized, managed, stored, and related within it. Its key elements include tables, columns, data types (defining the format and range of each value in a column), and relationships (defining how tables are connected and interact with each other).
Q4. What is an array?
Answer: An array is a tool specialized to offer efficient memory management and data access for similar or homogeneous data. It is an excellent tool that can be used during situations where performance and consistency of data types are critical. For instance, working with numerical for scientific computing.
Q5. What is the output of the following program?
public class Prg {
public static void main(String args[]){
System.out.print('A' + 'B');
}
}
Answer: The output of the program will be 167.
Q6. What is the output of the following program?
public class pg {
public static void main(String[] args) {
System.out.print("Hello");
System.out.printl<n("Guys!");
}
Answer: The output will be HelloGuys!
Q7. What is the output of the following program?
public class Prg {
public static void main(String[] args) {
char [] str={'i','n','c','l','u','d','e','h','e','l','p'};
System.out.println(str.toString());
}
Answer: The output of the following program will be includehelp.
Q8. What is the output of the following program?
class Test2 {
ublic
static void main(String[] args)
{
byte x = 12;
byte y = 13;
byte result = x + y;
System.out.print(result);
}
Answer: The output of the following program will be -128, not 25 as one may expect initially.
Q9. What is JDK, JVM, and JRE?
Answer: JDK or Java Development Kit, is a software development kit designed to create Java applications. It allows developers to develop, compile, test, and debug Java programs. It includes a Java virtual machine, Java compiler, Java runtime environment, and a few additional tools such as debuggers.
JVM or Java Virtual Machine is a platform that helps in executing Java bytecodes.
JRE or Java Runtime Environment is an essential part of JDK to run Java applications, including JVM and Java class libraries.
Q10. What are exception and exception handling in Java?
Answer: An exception in Java is an unexpected event that disrupts the normal operation of a program during deployment. It can occur due to various reasons such as coding error, runtime error, and external factors such as hardware malfunction, power failure, and user input errors.
Exception handling in Java is a process of anticipating, detecting, and responding to expectations in a controlled manner. The basic workflow of exception handling includes try block, catch block, and finally block.
Q11. Differentiate between Hashmap and Hashtable?
Answer: Hashmap and Hashtable are data structures in Java but they have a few differences.
Feature | Hashmap | Hashtable |
Thread Safety | Not Allowed | Allowed |
Null Key | Allowed | Not Allowed |
Null Value | Allowed | Not Allowed |
Performance | Faster | Slower |
Iterator | Fail-test | Not fail-test |
Legacy | No | Yes |
Q12. What is the OOPS concept in Java?
Answer: Object-Oriented Programming or OOPS focuses on organizing code around objects. OOPS offers improved code reusability, organization, maintenance, and a more flexible and scalable program. The key concepts in OOPS include class, objects, inheritance, polymorphism, encapsulation, and abstraction.
Q13. What are the differences between abstract class and interface?
Answer:
Feature | Abstract | Interface |
Implementation | Can have both abstract and concrete methods. | Only contains abstract methods. |
Multiple Inheritance | Can extend one parent class and implement multiple interfaces. | Can extend multiple interfaces and cannot inherit from classes. |
State | Can have member variables (state). | Cannot have member variables. |
Usage | Shared functionality with specialization, base class for inheritance. | Defining behavior contracts, multiple classes implement differently. |
Flexibility | Provides some pre-defined implementation with room for customization. | Defines only expected behavior and possibility for diverse implementations. |
Decoupling | Limited decoupling within its inheritance hierarchy. | Strong decoupling between implementing classes. |
Example | Animal (abstract) with methods breathe, eat, subclasses define move differently. | Drawable (interface) with methods draw, different classes like Circle and Square implement it. |
Q14. Write a code to reverse a string.
Answer: The code to reverse a string is as follows:
public class StringReverser {
public static String reverseString(String inputString) {
// Approach 1: StringBuilder (efficient and versatile)
StringBuilder reversed = new StringBuilder(inputString);
return reversed.reverse().toString();
// Approach 2: Iterative character reversal
// char[] characters = inputString.toCharArray();
// int left = 0, right = characters.length - 1;
// while (left < right) {
// char temp = characters[left];
// characters[left++] = characters[right];
// characters[right--] = temp;
// }
// return new String(characters);
// Approach 3: Recursive string reversal (elegant but less efficient for large strings)
// if (inputString.length() == 0) {
// return "";
// }
// return reverseString(inputString.substring(1)) + inputString.charAt(0);
}
public static void main(String[] args) {
String originalString = "Hello, world!";
String reversedString = reverseString(originalString);
System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString);
}
}
Q15. Explain the difference between == and .equalsTo.
Answer: The difference between == and .equalTo depends generally on depends on the context and data types.
Context | == | .equalTo |
Primitive Data Type | Compares the actual values of the variables. Results in true (if values are identical) or false (if not identical). | Not applicable in this data type. |
Reference Data Type | Compares the memory addresses of the variables. If variables point to the same object in memory it results in true otherwise false. | Compares the actual values of the objects referenced by the variables. |
Q16. Why do we use static in the main methods?
Answer: We use static in the main methods because when a Java program starts, there are no objects at that stage. The main method allows execution without an object. Additionally, it allows JVM to locate and invoke the program without any object interactions.
Q17. How can we avoid null pointer execution?
Answer: We can avoid null pointer execution by following a few strategies:
- Always initialize variables with appropriate values when declaring them.
- Use the conditional statement “if or ternary operations” to verify whether a variable is null before using it.
- Using Java’s optional<T> class to represent potentially null values.
- Utilizing static code analysis tools to identify potential null pointer issues during the development phase.
Q18. What is the use of the “final” keyword in Java?
Answer: The key uses of the “final” keyword are as follows:
- Preventing value changes
- Preventing method overriding
- Preventing class inheritance
- Clearing immutable objects
Q19. What are the various types of inheritance in Java?
Answer: The types of inheritance in Java include:
- Single Inheritance: In a single inheritance, a subclass inherits from a single direct superclass.
- Multilevel Inheritance: In this, a subclass inherits from a superclass, which itself inherits from another superclass, forming a chain.
- Hierarchical Inheritance: Here, multiple subclasses inherit from a single superclass, forming a tree-like structure.
- Multiple Inheritance: In this, a subclass inherits from multiple superclasses. Multiple inheritance is not directly supported by Java.
Q20. What is the use of the “byte” keyword in Java?
Answer: The “byte” keyword in Java can be used to:
- Save memory when dealing with large amounts of small integers.
- Storing raw binary data.
- Representing flags or boolean-type values.
- Working with file I/O, where data is frequently read and written in bytes.
Also Read: TCS Angular Interview Questions and Answers
TCS Java Interview Questions for Experienced Candidates
Here are some TCS Java programmer interview questions for experienced professionals, guiding them to crack the technical round at TCS!
Q21. Explain the difference between RDBMS and DBMS.
Answer: The difference between RDBMS and DBMS is as follows:
Criteria | RDBMS | DBMS |
Structure | Organizes data in rows and columns with consistent relation between them. | Ability to manage data in various structures such as tables, hierarchical, navigational, or unstructured. |
Data Relationship | Emphasizes relationships between tables using defined keys: primary and foreign. | Relationships between the data may not be explicitly defined. |
Query Language | Primarily uses SQL. | Language depends on the underlying data structure. |
Performance | Optimized for querying across related tables, particularly with complex joins and filters. | Performance may depend on the underlying data structure and query language used. |
Scalability | Scalability for large databases can be challenging. | Certain non-relational DBMS can offer better scalability. |
Examples | MySQL, Oracle Database, Microsoft SQL Server, PostgreSQL. | MongoDB (document-oriented), Neo4j (graph database), Redis (key-value store). |
Q22. What is the functionality of a linked list?
Answer: Linked lists are a linear data structure that stores a sequence of elements in non-contiguous memory locations. They offer flexibility and dynamic memory allocation compared to arrays, which have fixed sizes. Its operations include insertion, deletion, searching, and traversal.
Q23. How do you implement polymorphism in Java?
Answer: Here are the methods through which one can implement polymorphism in Java:
1. Method Overriding: Subclasses can redefine methods inherited from the superclass. Example code:
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
2. Method Overloading: Multiple methods in a class can have the same name but distinct parameter lists. Example code:
class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
3. Dynamic Method Dispatch: Java determines the method to call at runtime based on the actual object type. Example code:
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound(); // Output: Woof!
animal2.makeSound(); // Output: Meow!
Q24. Explain the role of the “finalize()” method.
Answer: The “finalize()” method plays a crucial role in garbage collection in Java. The role of the “finalize()” keyword includes:
- When triggered before GC (when data is unreachable), helps reclaim it before removing the object.
- Offers the final opportunity to the object to perform any necessary cleanups.
- GC is not obliged to call to “finalize()” before reclaiming an object. It usually depends on GC implementation and system load.
Q25. What is the output of the following code?
public class StringComparison {
public static void main(String a[]){
String str = "JavaTpoint is a great website to acquire knowledge";
StringBuffer obj =
new StringBuffer("JavaTpoint is a great website to acquire knowledge");
if(str.contentEquals(obj)){
System.out.println("The content of the string is equal");
} else {
System.out.println("The content of the string is not equal");
}
StringBuffer obj1 =
new StringBuffer("It is another string");
if(str.contentEquals(obj1)){
System.out.println("The content of the string is equal");
} else {
System.out.println("The content of the string is not equal");
}
}
}
Answer: The output of the code will be
The content of the string is equal
The content of the string is not equal
Q26. What will the following code result in?
class factorial
{
static int factorialexm(int num){
if(num==0)
return 1;
else
return (num * factorialexm(num-1));
}
public static void main(String args[]){
int fact = 1, i;
int num = 8;
fact = factorialexm(num);
System.out.println("Factorial of "+num+" is: "+fact);
}
}
Answer: The output will be Factorial of 8 is: 40320
Q27. Write a code for a string in Java by using the string literal method.
Answer: Here’s a code for a string in Java using the string literal method:
public class StringDemo {
public static void main(String[] args) {
// Declare and initialize a string variable using a string literal
String myString = "This is a string created using a string literal.";
// Print the string to the console
System.out.println(myString);
}
}
Q28. Create a Java Singleton class.
Answer: Here’s the code for a Java Singleton class:
public class Singleton {
// Private static instance of the class
private static volatile Singleton instance;
// Private constructor to prevent external instantiation
private Singleton() {
}
// Thread-safe getInstance method for controlled access
public static synchronized Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
// Example method within the Singleton
public void doSomething() {
System.out.println("This is a Singleton method.");
}
}
Q29. Explain multi-threading.
Answer: Multi-threading in Java allows one to execute multiple tasks consequently, improving performance and responsiveness. Multi-threading can be a powerful tool, but it requires careful design and implementation to avoid pitfalls and maximize performance.
Q30. Explain memory management in Java.
Answer: Java handles memory automatically unlike C++/C. It makes use of an allocator to automatically allocate memory for objects when they are created and deallocate them when they become unreachable. Additionally, garbage collection is an essential component of Java memory management, responsible for identifying and reclaiming unused memory.
Q31. Write the code for handling exceptions through the multiple catch blocks method.
Answer:
public class HandlingMultipleExceptions {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 0};
int result = numbers[4] / 0; // Both array index out of bounds and divide by zero exceptions
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} catch (Exception e) { // General catch-all block for unexpected exceptions
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("This code always executes, regardless of exceptions.");
}
}
}
Q32. Write the code to implement a linked list in Java.
Answer:
Step 1: Create a node class.
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
Step 2: Create a Linked List Class.
class LinkedList {
Node head;
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
public void deleteNode(int data) {
if (head == null) {
return;
}
if (head.data == data) {
head = head.next;
return;
}
Node current = head;
while (current.next != null && current.next.data != data) {
current = current.next;
}
if (current.next == null) {
return; // Node not found
}
current.next = current.next.next;
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
Q33. How do you implement a stack in Java using an array?
Answer: Here’s the code to implement a stack in Java using an array:
class Stack {
private int[] elements;
private int top = -1;
private int capacity;
public Stack(int capacity) {
this.capacity = capacity;
elements = new int[capacity];
}
public void push(int element) {
if (isFull()) {
throw new StackOverflowError("Stack is full");
}
elements[++top] = element;
}
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return elements[top--];
}
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return elements[top];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1;
}
}
Q34. What are the different subsets of SQL?
Answer: The different subsets of SQL include:
- DDL or Data Definition Language: It deals with the schemas and descriptions and how the data resides in the database.
- DML or Data Manipulation Language: It deals with data manipulation within tables.
- DCL or Data Control Langauge: It is used to control access to data and manage database security.
- TCL or Transaction Control Language: Used for managing transactions, and ensuring data integrity and consistency.
- DQL or Data Query Language: It is a subset used for retrieving data.
Q35. What is the difference between socket and session?
Answer: A socket is a software endpoint used for bidirectional communication between two programs over a network. Whereas a session is a logical grouping of related communication exchanges between two communicating entities (e.g., client and server) over a specific period.
Q36. What is the use of a constructor in Java?
Answer: The primary role of constructors in Java is to initiate an object’s state, ensuring it begins in a valid and consistent condition. Additionally, constructors enforce encapsulation. You can define multiple constructors with distinct parameter lists for flexibility in object creation.
Q37. Write a Java program to insert a string into another one.
Answer: Here is how you can insert one string into another:
public class StringInsertion {
public static void main(String[] args) {
String originalString = "Hello";
String stringToInsert = "World";
int insertionIndex = 3;
// Using StringBuilder for efficient string manipulation
StringBuilder builder = new StringBuilder(originalString);
builder.insert(insertionIndex, stringToInsert);
String resultingString = builder.toString();
System.out.println(resultingString); // Output: HelWorldlo
}
}
Q38. Write a Java program to show the usage of the equal() method.
Answer: The following is an example of how you can use the equal() method:
public class EqualsMethodDemo {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = "World";
String str4 = new String("Hello"); // Different object, same content
String str5 = "hello"; // Different case
System.out.println("str1.equals(str2): " + str1.equals(str2)); // true (same content, same object)
System.out.println("str1.equals(str4): " + str1.equals(str4)); // true (same content, different objects)
System.out.println("str1 == str4: " + (str1 == str4)); // false (different object references)
System.out.println("str1.equals(str3): " + str1.equals(str3)); // false (different content)
System.out.println("str1.equals(
Q39. What is the program to create an abstract class?
Answer: The program to create an abstract class is as follows:
public abstract class Animal {
// Concrete methods (can have implementation)
public void eat() {
System.out.println("Animal is eating.");
}
// Abstract method (no implementation, must be implemented in subclasses)
public abstract void makeSound();
}
Q40. What are the various types of sorting in Java?
Answer: Sorting in Java refers to arranging elements in an array or collection in a specified order, usually ascending or descending. Sorting in Java is classified into two broad categories:
- Comparison-based Sorting – This includes bubble sort, selection sort, insertion sort, merge sort, quick sort, and heal sort.
- Non-comparison-based Sorting – This includes counting sort and radix sort.
Conclusion
It is essential to practice these questions before the interview to answer with confidence. So, keep this comprehensive list of TCS Java developer interview questions with answers handy. Additionally, pursuing a course in Java can help you brush up before an interview or upskill yourself. Consider, enrolling in a core Java course to learn Java from experts.
Would you be able to ace a TCS Java interview? Let us know in the comments section below. Also, check out our blog on Java interview questions to complete your preparation.