Cognizant GenC Java Cluster Mock Interview
Cognizant GenC Java Cluster Mock Interview
Questions
Here is a comprehensive set of answers to common Java interview questions. Each question includes a
detailed answer and keywords that interviewers typically look for.
Java Fundamentals
3. What is bytecode?
Answer: Bytecode is the intermediate, platform-independent code generated by the Java compiler
from the source code. It is a set of instructions for the Java Virtual Machine (JVM). When a Java
program is executed, the JVM's interpreter or Just-In-Time (JIT) compiler translates this bytecode into
native machine code that the host computer's processor can execute.
Keywords: Intermediate code, platform-independent, JVM instruction set, JIT compiler.
JVM (Java Virtual Machine): It is an abstract machine that provides the runtime environment in
which Java bytecode can be executed. It is responsible for loading, verifying, and executing the
Page 1 of 12
bytecode. It is platform-dependent.
JRE (Java Runtime Environment): It is the software package that contains everything needed to
run a compiled Java program, including the JVM, the Java Class Library, and other supporting
files. You need JRE to run Java applications.
JDK (Java Development Kit): It is the full-featured software development kit for Java. It includes
the JRE (so it has the JVM) plus development tools such as the compiler ( javac ), debugger
( jdb ), and archiver ( jar ). You need the JDK to develop (compile and debug) Java applications.
In short: JDK = JRE + Development Tools , and JRE = JVM + Class Libraries .
Keywords: JVM (runs code), JRE (to run applications), JDK (to develop applications), compiler,
libraries.
Platform: Java is platform-independent (due to bytecode and JVM), while C++ is platform-
dependent (compiles to native machine code).
Memory Management: Java has automatic garbage collection, whereas C++ requires manual
memory management using new / delete , which can lead to memory leaks.
Pointers: Java does not support explicit pointers, which enhances security and simplicity. C++
allows direct memory manipulation through pointers.
Inheritance: Java supports single inheritance for classes but allows multiple inheritance through
interfaces. C++ supports multiple inheritance for classes, which can lead to the "Diamond
Problem."
Keywords: Platform independence, garbage collection, no pointers, multiple inheritance
(interfaces).
Auto-boxing: The automatic conversion that the Java compiler makes between a primitive type
and its corresponding object wrapper class. For example, converting an int to an Integer .
Unboxing: The reverse process of converting an object of a wrapper type to its corresponding
primitive value. For example, converting an Integer to an int .
This feature simplifies code by eliminating the need for manual conversion.
Keywords: Automatic conversion, primitive types, wrapper classes.
Page 2 of 12
8. What is casting in Java?
Answer: Casting is the process of converting a value from one data type to another. This is commonly
done with both primitive types (like converting a double to an int ) and reference types (like
converting an object of a subclass to its superclass type).
Keywords: Type conversion, primitive types, reference types.
Implicit Casting (Widening): This is done automatically by the compiler when converting a smaller
data type to a larger data type where there is no risk of data loss. For example, int to long or
float to double .
Explicit Casting (Narrowing): This must be done manually by the programmer using the cast
operator () . It is required when converting a larger data type to a smaller one, as there is a
potential for data loss. For example, double to int .
Keywords: Widening (implicit), narrowing (explicit), automatic, manual, data loss.
String Handling
Security: Immutable strings protect sensitive data (like passwords or database URLs) because
they cannot be changed after creation.
Thread Safety: Since strings cannot be modified, they are inherently thread-safe and can be
shared among multiple threads without the need for synchronization.
Caching and Performance: Immutability allows Java to cache strings in the String Constant Pool.
When the same string literal is used multiple times, Java can return a reference to the existing
string from the pool instead of creating a new object, saving memory and improving performance.
Keywords: Immutable, security, thread safety, caching, String Constant Pool.
Page 3 of 12
StringBuffer : Its methods are synchronized, making it thread-safe. This means only one
thread can access its methods at a time, which can create a performance bottleneck in multi-
threaded environments.
StringBuilder : It is not synchronized, making it not thread-safe. However, this lack of
overhead makes it faster than StringBuffer . It should be used in single-threaded
environments or when thread safety is handled externally.
Keywords: Mutable, StringBuffer (thread-safe, synchronized, slower), StringBuilder
(not thread-safe, faster).
1. Using a String Literal: e.g., String s1 = "Java"; . This method utilizes the String Constant
Pool. If the string already exists in the pool, a reference to it is returned.
2. Using the new keyword: e.g., String s2 = new String("Java"); . This method always
creates a new String object in the heap memory, regardless of whether a string with the same
value already exists in the pool.
Keywords: String literal, new keyword, String Constant Pool, heap.
14. What is the difference between == and .equals() when comparing Strings?
Answer:
== operator: This is a reference comparison operator. When used with objects like Strings, it
checks if two reference variables point to the exact same object in memory.
.equals() method: This method compares the actual content (sequence of characters) of the
strings. It returns true if the two strings have the same value, regardless of where they are
stored in memory.
When comparing strings for content equality, you should always use the .equals() method.
Keywords: == (reference equality, memory location), .equals() (content equality, value).
OOP Concepts
Page 4 of 12
16. What is the difference between super and this keywords in Java?
Answer:
this : The this keyword is a reference to the current instance of the class. It is used to refer
to the current object's members (fields or methods) or to call another constructor of the same
class.
super : The super keyword is a reference to the immediate parent class object. It is used to
call the parent class's members (fields or methods) or to call the parent class's constructor.
Keywords: this (current instance), super (parent class instance).
Page 5 of 12
21. Does an abstract class support multiple inheritance? Explain.
Answer: No. In Java, a class, whether it is abstract or concrete, cannot extend more than one class.
Java does not support multiple inheritance of classes to avoid complexities like the Diamond Problem.
An abstract class can, however, implement multiple interfaces.
Keywords: Single inheritance, extends one class, implements multiple interfaces.
Overloaded: Yes, a static method can be overloaded. You can have multiple static methods with
the same name in the same class as long as their parameter lists are different.
Overridden: No, a static method cannot be truly overridden. If a subclass defines a static method
with the same signature as a static method in its superclass, it is known as method hiding, not
overriding. The method that gets called is determined at compile-time based on the reference
type, not at runtime based on the object type.
Keywords: Overloading (yes), Overriding (no), method hiding, compile-time binding.
Page 6 of 12
Feature Abstract Class Interface
Abstract Classes: Yes, they have constructors. Although you cannot create an instance of an
abstract class directly with new , its constructor is called when an instance of a concrete
subclass is created (via the super() call). This is necessary to initialize the fields defined in the
abstract class.
Interfaces: No, they do not have constructors because they cannot contain instance fields. Their
purpose is to define a contract, not to have a state.
Keywords: Abstract class (yes, for state initialization), Interface (no, no state).
29. What is the difference between compile-time polymorphism and run-time polymorphism?
Answer:
Compile-time Polymorphism (Static Binding): This is achieved through method overloading. The
compiler determines which method to call at compile time based on the method signature (the
number, type, and order of parameters).
Run-time Polymorphism (Dynamic Binding): This is achieved through method overriding. The
method to be called is determined at runtime by the JVM, based on the actual type of the object,
not the type of the reference variable.
Page 7 of 12
Keywords: Method overloading (compile-time), method overriding (run-time), static binding,
dynamic binding.
32. What is the difference between the new keyword and instanceof operator?
Answer: They serve completely different purposes.
new keyword: It is an operator used to create an instance (an object) of a class. It allocates
memory on the heap for the new object and returns a reference to it.
instanceof operator: It is an operator used to check the type of an existing object. It does not
create anything; it only performs a check.
Keywords: new (creates object), instanceof (checks object type).
Page 8 of 12
35. Can an outer class be static?
Answer: No, an outer class (a top-level class) cannot be declared as static . The static keyword
means the member belongs to the type itself, not an instance. This concept doesn't apply to top-level
classes. Only nested classes (a class within another class) can be declared as static .
Keywords: Top-level class (no), nested class (yes).
37. Explain access modifiers in the same package and different packages (class, subclass).
Answer:
private Yes No No No
final : A keyword used as a non-access modifier. It can be applied to a variable (to make it a
constant), a method (to prevent overriding), or a class (to prevent inheritance).
finally : A block used in exception handling ( try-catch-finally ). The code inside the
finally block is always executed, regardless of whether an exception occurs, making it ideal
for resource cleanup.
finalize : A method from the Object class. It is called by the garbage collector just before
an object is destroyed. Its use is discouraged as its execution is not guaranteed.
Keywords: final (keyword, constant), finally (block, always executes), finalize
(method, garbage collection).
Page 9 of 12
modifiers are static , final , abstract , synchronized , volatile , and transient .
Keywords: static , final , abstract , synchronized .
volatile : This keyword is used in concurrent programming. It ensures that any modification to
the volatile variable is always visible to other threads immediately. It guarantees visibility but
not atomicity.
transient : This keyword is used during serialization. It marks a field to be excluded when an
object is serialized, meaning its value will not be saved to the byte stream.
Keywords: volatile (thread visibility), transient (exclude from serialization).
Exception Handling
throw : The throw keyword is used to explicitly throw a single exception from a method or any
block of code. It is followed by an instance of an Exception class.
throws : The throws keyword is used in a method signature to declare the exceptions that the
method might throw. It informs the caller that it needs to handle or propagate these potential
exceptions.
Keywords: throw (throws an exception), throws (declares an exception).
OutOfMemoryError : This error is thrown by the JVM when it cannot allocate any more
memory on the heap to create new objects, and the garbage collector cannot free up enough
space.
Page 10 of 12
StackOverflowError : This error is thrown when the application's call stack becomes too
deep, typically due to infinite or very deep recursion.
Keywords: Error , heap space ( OutOfMemoryError ), call stack ( StackOverflowError ),
recursion.
Error: Represents serious, unrecoverable problems that are typically caused by the JVM or the
environment, such as OutOfMemoryError or StackOverflowError . Applications are not
expected to handle them.
Exception: Represents conditions that a program might want to catch and handle. They are
typically caused by the application itself, like NullPointerException or IOException .
Keywords: Throwable , Error (unrecoverable, system), Exception (recoverable,
application).
46. What is the difference between checked exceptions and unchecked exceptions?
Answer:
Checked Exceptions: These are exceptions that the compiler forces you to handle at compile-
time, either by using a try-catch block or by declaring them with the throws keyword. They
are subclasses of Exception (but not RuntimeException ). Examples include
IOException and SQLException .
Unchecked Exceptions: These are exceptions that are not checked at compile time. They are
subclasses of RuntimeException . The compiler does not require you to handle them.
Examples include NullPointerException , ArrayIndexOutOfBoundsException .
Keywords: Compile-time check (checked), runtime (unchecked), RuntimeException .
Page 11 of 12
48. Can you explain garbage collection in Java with an example?
Answer: Garbage Collection (GC) is the process of automatic memory management in Java. The JVM's
garbage collector identifies and reclaims memory occupied by objects that are no longer referenced by
the program. For example, if you create an object Person p = new Person(); and later set p =
null; , the Person object in the heap becomes unreachable. The GC will eventually find this
unreachable object and deallocate its memory.
Keywords: Automatic memory management, heap, unreachable objects, System.gc() .
Collection (with 'n'): This is an interface. It is the root interface in the collection hierarchy
(excluding maps). Interfaces like List and Set extend the Collection interface.
Collections (with 's'): This is a class. It is a utility class that provides various static, helper
methods for operating on collections, such as sorting ( Collections.sort() ), searching, and
creating synchronized collections.
Keywords: Collection (interface), Collections (utility class, static methods).
Page 12 of 12