KEMBAR78
Cognizant GenC Java Cluster Mock Interview | PDF | Method (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
40 views12 pages

Cognizant GenC Java Cluster Mock Interview

The document provides a comprehensive set of answers to common Java interview questions, covering topics such as Java fundamentals, string handling, and OOP concepts. It includes detailed explanations of key concepts like platform independence, bytecode, inheritance, and polymorphism, along with relevant keywords for each topic. This resource serves as a guide for candidates preparing for Java interviews.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views12 pages

Cognizant GenC Java Cluster Mock Interview

The document provides a comprehensive set of answers to common Java interview questions, covering topics such as Java fundamentals, string handling, and OOP concepts. It includes detailed explanations of key concepts like platform independence, bytecode, inheritance, and polymorphism, along with relevant keywords for each topic. This resource serves as a guide for candidates preparing for Java interviews.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Cognizant Gen C Java 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

1. Why is Java so popular?


Answer: Java's popularity stems from several key features. It is platform-independent ("Write Once, Run
Anywhere"), which allows code to run on any device with a Java Virtual Machine (JVM). It is a strongly
object-oriented language, promoting clean, reusable, and maintainable code. Java also boasts a
massive ecosystem with a rich standard library, extensive third-party libraries, and a large, active
community providing excellent support and tools. Its automatic memory management through garbage
collection simplifies development and reduces memory-related errors.
Keywords: Platform-independent, WORA, JVM, Object-Oriented, large ecosystem, garbage collection,
secure.

2. What is platform independence in Java?


Answer: Platform independence means that a Java program can run on any operating system or
hardware for which a Java Virtual Machine (JVM) is available, without needing to be recompiled. The
Java compiler converts the source code into an intermediate format called bytecode. This bytecode is
not machine-specific; instead, it is interpreted and executed by the JVM, which is tailored for the
specific underlying platform. This concept is famously known as "Write Once, Run Anywhere" (WORA).
Keywords: Write Once Run Anywhere (WORA), bytecode, Java Virtual Machine (JVM), compiler.

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.

4. Compare JDK, JVM, and JRE.


Answer:

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.

5. What are the important differences between C++ and Java?


Answer:

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).

6. Why do we need Wrapper classes in Java?


Answer: Wrapper classes are needed to convert primitive data types (like int , char , float ) into
objects. This is essential because many Java frameworks and collections, like ArrayList or
HashMap , can only store objects, not primitive types. Wrapper classes also provide utility methods
and allow primitive types to have a null value.
Keywords: Primitives to objects, collections framework, null value, utility methods.

7. What is auto-boxing and unboxing?


Answer:

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.

9. What is the difference between implicit casting and explicit casting?


Answer:

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

10. Why are strings immutable in Java?


Answer: Strings are immutable in Java for several key reasons:

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.

11. What is the String Constant Pool in Java?


Answer: The String Constant Pool (SCP) is a special memory area in the heap where Java stores string
literals. When a string is created using a literal (e.g., String s = "hello"; ), the JVM checks the
pool first. If the string already exists, a reference to the existing string is returned. If not, a new string
object is created in the pool, and its reference is returned. This mechanism conserves memory.
Keywords: Heap memory, string literals, memory optimization, caching.

12. What is the difference between StringBuilder and StringBuffer ?


Answer: Both StringBuilder and StringBuffer are mutable classes used for string
manipulation. The key difference is thread safety.

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).

13. How many ways can we create a String in Java?


Answer: There are two primary ways to create a String object in Java:

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).

15. How does the intern() method work in Java?


Answer: The intern() method creates an exact copy of a String object in the String Constant Pool.
When intern() is called on a String object, the JVM checks if the pool already contains a string equal
to this object. If it does, the reference to the string from the pool is returned. Otherwise, this String
object is added to the pool, and a reference to this new object is returned. It can be used to ensure all
strings with the same content share the same memory.
Keywords: String Constant Pool, reference, memory sharing.

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).

17. Explain the toString() method.


Answer: The toString() method is defined in the Object class and returns a string
representation of an object. By default, it returns the class name followed by the '@' symbol and the
object's hash code in hexadecimal. It is highly recommended to override the toString() method in
your own classes to provide a meaningful, human-readable representation of the object's state.
Keywords: Object representation, string, override, Object class.

18. What is the hashCode() method used for in Java?


Answer: The hashCode() method, also from the Object class, returns an integer hash code value
for the object. This value is used by hash-based collections like HashMap , HashSet , and
Hashtable to store and retrieve objects efficiently. The contract between hashCode() and
equals() is crucial: if two objects are equal according to equals() , they must have the same hash
code.
Keywords: Hash-based collections, HashMap , equals() contract, integer value.

19. Explain inheritance with examples in Java.


Answer: Inheritance is an OOP principle where a new class (subclass or child class) derives properties
and behaviors (fields and methods) from an existing class (superclass or parent class). It promotes code
reusability and establishes an "IS-A" relationship. For example, a Car class can inherit from a
Vehicle class using the extends keyword. The Car IS-A Vehicle and will inherit methods like
startEngine() while also having its own specific methods like turnOnRadio() .
Keywords: IS-A relationship, code reuse, extends keyword, superclass, subclass.

20. What is the "Diamond Problem" and how is it solved?


Answer: The "Diamond Problem" refers to the ambiguity that arises when a class inherits from two or
more classes that have a common base class. If a method is overridden in the intermediate classes, it's
unclear which implementation the final derived class should inherit. Java avoids this problem by not
supporting multiple inheritance of classes. However, a similar issue could arise with interfaces. Since
Java 8, interfaces can have default methods. If a class implements two interfaces with a default
method of the same signature, the class must explicitly override the method to resolve the ambiguity.
Keywords: Multiple inheritance, ambiguity, default methods, interfaces.

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.

22. Can a static method be overloaded and overridden?


Answer:

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.

23. What is an interface in Java?


Answer: An interface in Java is a reference type that acts as a contract for classes. It can contain only
constants, method signatures, default methods, static methods, and nested types. It cannot contain
instance fields or constructors. A class that implements an interface must provide an
implementation for all of its abstract methods. Interfaces are a key way to achieve 100% abstraction
and a form of multiple inheritance.
Keywords: Contract, 100% abstraction, implements , default methods.

24. Can a class implement multiple interfaces?


Answer: Yes, a class can implement multiple interfaces. This is Java's way of achieving a form of
multiple inheritance, where a class can inherit the abstract methods from several interfaces.
Keywords: Multiple implementation, implements keyword.

25. What is an abstract class?


Answer: An abstract class is a class that is declared with the abstract keyword and cannot be
instantiated. It is designed to be subclassed. It can contain both abstract methods (methods without a
body) and concrete methods (methods with a body). It is used to achieve partial abstraction and to
provide a common base for a group of related subclasses.
Keywords: abstract keyword, cannot be instantiated, partial abstraction, base class.

26. Compare abstract class vs interface in Java.


Answer:

Feature Abstract Class Interface

Can have abstract and non- Can have abstract and


Methods
abstract methods. default/static methods.

Page 6 of 12
Feature Abstract Class Interface

Can have instance variables Can only have public


Fields ( final , non- final , static , static final
non- static ). constants.

A class can extend only one A class can implement


Inheritance
abstract class. multiple interfaces.

Has a constructor (called via Does not have a


Constructor
super() ). constructor.

To provide a common base with To define a contract of


Purpose some shared implementation (IS-A behaviors (CAN-DO
relationship). relationship).

Keywords: Single vs multiple


inheritance, state (fields) vs
contract, constructor.

27. Do abstract classes and interfaces have constructors? Why?


Answer:

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).

28. What is polymorphism in Java?


Answer: Polymorphism, meaning "many forms," is the ability of an object to take on many forms. In Java,
it allows a single action to be performed in different ways. The most common use is when a parent class
reference is used to refer to a child class object. It is achieved through method overloading (compile-
time polymorphism) and method overriding (run-time polymorphism).
Keywords: Many forms, method overloading, method overriding.

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.

30. What is compile-time polymorphism also called?


Answer: Compile-time polymorphism is also known as static polymorphism or early binding.
Keywords: Static binding, early binding.

31. What is the use of the instanceof operator in Java?


Answer: The instanceof operator is used to test whether an object is an instance of a specific
class, a subclass, or an interface. It returns a boolean value ( true or false ). It is commonly used to
avoid ClassCastException before performing an explicit downcast.
Keywords: Type checking, ClassCastException , boolean.

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).

33. What is encapsulation in Java?


Answer: Encapsulation is the practice of bundling the data (fields) and the methods that operate on the
data into a single unit (a class). It also involves hiding the internal state of an object from the outside.
This is achieved by making fields private and providing public getter and setter methods to
access and modify them, allowing for controlled access.
Keywords: Data hiding, bundling, private fields, public getters/setters.

Advanced Java Concepts

34. How many ways can we create an object in Java?


Answer: There are several ways to create an object in Java:

1. Using the new keyword: The most common way.


2. Using Class.forName() and newInstance() : A form of reflection.
3. Using Constructor.newInstance() : Another reflection-based method.
4. Using the clone() method: Creates a copy of an existing object.
5. Using Deserialization: Creates an object from a byte stream.
Keywords: new , newInstance() , reflection, clone() , deserialization.

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).

36. What is an anonymous class in Java?


Answer: An anonymous class is a class that does not have a name. It is declared and instantiated in a
single expression. It is typically used for one-time implementations of an interface or for extending a
class, often for event handlers or short-lived objects like a Runnable .
Keywords: No name, single expression, one-time use, event handlers.

37. Explain access modifiers in the same package and different packages (class, subclass).
Answer:

Same Same Subclass Other Class


Modifier
Class Package (Diff. Pkg) (Diff. Pkg)

public Yes Yes Yes Yes

protected Yes Yes Yes No

default Yes Yes No No

private Yes No No No

Keywords: public , protected , default ,


private , visibility, package.

38. What is the difference between final , finally , and finalize ?


Answer:

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).

39. What is a non-access modifier in Java?


Answer: Non-access modifiers are keywords that provide information about the characteristics of a
class, method, or variable to the JVM, but do not control its access level. The main non-access

Page 9 of 12
modifiers are static , final , abstract , synchronized , volatile , and transient .
Keywords: static , final , abstract , synchronized .

40. What happens when a variable is marked as volatile or transient ?


Answer:

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

41. What is the difference between throw and throws ?


Answer:

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).

42. What is the need for the finally block?


Answer: The finally block is needed to ensure that a certain piece of code is executed regardless
of what happens in the try block (whether an exception is thrown or not). Its primary use is for
resource cleanup, such as closing files, database connections, or network sockets, to prevent resource
leaks.
Keywords: Guaranteed execution, resource cleanup, try-catch .

43. What is the OutOfMemoryError and StackOverflowError in Java?


Answer: Both are subtypes of Error , indicating serious problems that a normal application should
not try to catch.

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.

44. Is it allowed to have a try block without catch or finally ?


Answer: No. A try block must be followed by either at least one catch block or a finally block,
or both. A try block by itself is a compilation error.
Keywords: try-catch , try-finally , try-catch-finally .

45. What is the difference between an error and an exception in Java?


Answer: Both are subclasses of Throwable .

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 .

Serialization, GC, and Collections

47. What is serialization in Java?


Answer: Serialization is the process of converting an object's state into a byte stream. This byte stream
can then be stored in a file, database, or transmitted across a network. The reverse process is called
deserialization. A class must implement the Serializable marker interface to be serializable.
Keywords: Object to byte stream, Serializable interface, persistence, network transfer.

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() .

49. What is the Collection framework in Java?


Answer: The Collection framework is a unified architecture for representing and manipulating
collections (groups of objects). It provides a set of interfaces (like List , Set , Map ) and classes (like
ArrayList , HashSet , HashMap ) to store data efficiently. It also includes algorithms to work with
these collections, such as sorting and searching.
Keywords: Interfaces ( List , Set , Map ), classes ( ArrayList , HashSet ), data structures,
algorithms.

50. Difference between Collection and Collections .


Answer:

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

You might also like