[go: up one dir, main page]

0% found this document useful (0 votes)
36 views26 pages

Oop1 031329

It's a bood

Uploaded by

paul
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)
36 views26 pages

Oop1 031329

It's a bood

Uploaded by

paul
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/ 26

Chapter 1 (8 marks)

Q1. List any 5 criteria of object orientation that fall under the category of methods and languages.
 Encapsulation: This means keeping data and the methods that work with that data together in one place (like a capsule). It
helps protect the data from being changed directly from outside.
 Abstraction: This is about simplifying complex things by showing only the necessary details. You focus on what an object
does, not how it does it, which makes it easier to understand.
 Inheritance: This allows a new class to take properties and methods from an existing class. It’s like a child inheriting traits
from a parent, helping you reuse code and build on it.
 Polymorphism: This lets one method do different things based on the object it’s acting on. You can have methods that look
the same but behave differently depending on the object.
 Dynamic Binding: This means the method that should be called is determined at runtime instead of compile time. It allows
for flexibility in how methods are executed, especially in polymorphism.

Q2. What are the essential features of a development environment supporting object-oriented software constructions?
 Integrated Development Environment (IDE): A robust IDE provides tools for writing, debugging, and managing code,
including features like syntax highlighting, code completion, and integrated debugging to streamline the development
process.
 Class and Object Management: The environment should facilitate the creation, modification, and organization of classes
and objects, allowing developers to easily manage relationships and hierarchies through visual representations.
 Support for Inheritance and Polymorphism: The development environment should allow easy implementation of
inheritance and polymorphism, enabling code reuse and the creation of flexible, extensible systems.
 Version Control Integration: Built-in version control tools help manage changes to the codebase, allowing for
collaboration among team members and maintaining a history of modifications.
 Testing and Debugging Tools: Effective testing frameworks and debugging tools are essential for ensuring that objects and
methods behave as expected, allowing developers to identify and fix issues quickly.
 Documentation Support: The environment should provide tools for generating and maintaining documentation, including
class and method descriptions, to help developers understand the system and facilitate easier maintenance.

Q3. Why is creating libraries an important aspect of object-oriented software construction?


 Code Reusability: Libraries allow developers to reuse existing code instead of writing it from scratch. This saves time and
effort, as common functionalities are already implemented and tested.
 Modularity: Libraries promote a modular approach to software design. By organizing related classes and functions into
libraries, developers can manage and maintain code more effectively.
 Encapsulation: Libraries help encapsulate functionality, meaning users can interact with a library without needing to
understand its internal workings. This simplifies usage and reduces the risk of errors.
 Standardization: Using libraries encourages the use of standard methods and practices across projects, which can lead to
better consistency and easier collaboration among developers.
 Maintenance and Updates: When libraries are updated or improved, all applications using those libraries can benefit from
the enhancements without needing to change the individual application code.
 Collaboration: Libraries can be shared among teams or the wider developer community, facilitating collaboration and
knowledge sharing, which can lead to more innovative solutions and faster development.

Q4. Briefly explain the different categories on which the set of criteria for object-oriented software construction is based
upon.
 Structure: This category looks at how classes and objects are organized. It includes concepts like encapsulation (keeping
data safe within classes) and inheritance (sharing features between classes).
 Behavior: This focuses on how objects interact with each other. It includes polymorphism, which allows methods to work
differently based on the object type, and how objects send and receive messages.
 Design Principles: These are guidelines for creating good object-oriented designs. They help ensure that classes do one job
well (Single Responsibility Principle) and can be easily extended (Open/Closed Principle).
 Development Practices: This includes methods like Agile or Test-Driven Development (TDD) that support effective
software development. They emphasize teamwork, quick changes, and continuous testing.
 Documentation: Good documentation explains how classes and methods work. It helps everyone understand the code better
and makes maintenance easier.
 Tool Support: This refers to the software tools (like IDEs and testing tools) that help developers write and manage their
code more effectively, improving productivity and code quality.

Q5. Explain what assertion with respect to class design is. Explain the term pre-condition, post. Condition and class
invariants.
Assertion: an assertion is a statement that checks if a certain condition is true at a specific point in a program. Assertions
help ensure that an object is in the correct state before and after a method runs.
 Pre-condition:
 A pre-condition is a rule that must be true before a method runs. It tells you what needs to be true about the inputs or the
object's state for the method to work correctly.
 Example: If you have a method to withdraw money from a bank account, a pre-condition might be that the account balance
should be enough to cover the withdrawal.
 Post-condition:
 A post-condition is a rule that must be true after a method has finished running. It tells you what should be true about the
object's state or output once the method is done.
 Example: After withdrawing money, a post-condition could be that the account balance should be reduced by the amount
withdrawn.
 Class Invariants:
 Class invariants are rules that must always be true for an object of a class, no matter what. They help ensure that the object
remains valid throughout its life.
 Example: For a bank account class, a class invariant might be that the account balance should never be negative at any time.

Q6. Explain the term single inheritance with an example in java. What is the significance of constraint generality with respect
to class design?
Single Inheritance: where a child class inherits methods and properties from only one parent class.
Example:
// Parent class
class Animal {
void speak() {
System.out.println("Animal makes a sound");
}
}
// Child class
class Dog extends Animal { // Dog inherits from Animal
void bark() {
System.out.println("Woof!");
}
}
// Main class to test
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.speak(); // Inherited method
myDog.bark(); // Dog's own method

}
Significance of Generality Constraint:
 Promotes Reusability: By designing classes that are general enough, you can reuse them in various contexts without major
modifications. This reduces code duplication.
 Ensures Consistency: Constraints help maintain a consistent interface and behavior across related classes. This means that
users of the class can expect similar behavior, leading to fewer errors.
 Enhances Collaboration: In team environments, generalized classes help different developers work on their components
without interfering with each other's code, as they can build on a stable foundation.
 Improves Flexibility: General classes can be extended or modified more easily in the future, allowing the system to adapt to
changing requirements without significant redesign.

Chapter 2 (4 marks)

Q1. List and explain the merits and limitations of functional decomposition.
Merits/Advantages

 Easier Problem Solving: Breaking a problem into smaller parts makes it easier to understand and solve. You can focus on
one part at a time.
 Simplifies Debugging: When each part of a program is separated into smaller functions, it becomes easier to locate and fix
bugs in the system.
 Modularity: Functions represent small, independent modules, making the code more organized and easier to maintain.
Limitations\Disadvantages
 Scalability Issues: As systems grow, functional decomposition might not handle the increasing complexity well, making it
harder to maintain the system.
 Lack of Data Encapsulation: Functional decomposition can lead to scattered data handling across different functions,
making it harder to protect or manage data.
 Tight Coupling: Functions might depend on one another closely, making changes in one function affect others, reducing
flexibility in large systems.

Q2. Why Object-Based Decomposition is Better than Functional Decomposition:


1. Focus on Real-World Entities:
 Object-Based Decomposition: Breaks a system into objects, which represent real-world entities (like a "Car" or
"Employee"). This makes it easier to model systems as we see them in reality.
 Functional Decomposition: Focuses on breaking down tasks or actions (like "drive" or "calculate salary"). This can
sometimes lead to a less intuitive design because actions alone don't capture the whole concept.
2. Encapsulation:
 Object-Based: Objects bundle both data (attributes) and behavior (methods) together, protecting data from unintended
access. This keeps the system secure and organized.
 Functional: Functions often handle data separately, leading to a scattered approach to managing information. This increases
the risk of data mishandling.
3. Reusability and Flexibility:
 Object-Based: Objects can easily be reused in different contexts without modifying the rest of the code. You can create new
objects from existing ones (inheritance), making the system flexible.
 Functional: While functions can be reused, they focus only on tasks. They don't promote the rich reusability that comes
from OOP features like inheritance or polymorphism.
Q3. What is object-oriented software constructions?
Object-oriented software construction is a software development approach that emphasizes the organization of software systems
around objects rather than functions or data structures. The essential building blocks of a system are called objects in object-oriented
software development, and they encompass both data and behavior.
 Encapsulation: Objects keep their data private and only expose necessary functionality, which helps in protecting and
managing data.
 Inheritance: You can create new objects by extending existing ones, allowing reuse of code and adding new features
without starting from scratch.
 Polymorphism: Objects can take on different forms, meaning the same method can behave differently for different objects.
 Abstraction: Complex systems are simplified by focusing on only the necessary details, hiding unnecessary complexities.
Q4. What is the pre-mature ordering problem found in functional decomposition? Explain how this problem is taken care of
in an object-oriented approach. (Imp)
The premature ordering problem occurs when the functions are organized in a fixed sequence too early in the design process.
The object-oriented approach overcomes this by:
 Encapsulating data and behavior within objects.
 Allowing flexible and dynamic interactions between objects.
 Utilizing OOP principles like encapsulation, polymorphism, and late binding.

Chapter 3 & 4 (14 marks)


Q1. What is a class?
Class: A blueprint or template that defines the structure and behavior (methods and variables) of objects.
Example:

A Book class might have:


 Attributes: title, author, pages
 Methods: open the book, read a page

// Defining the class


class Book {
// Attributes of the class
String title;
String author;
int pages;
}
Q2. What is an object?
an object is an instance of a class. It represents a real-world entity or concept with properties (attributes) and behaviors
(methods). Objects interact with each other by invoking methods, and each object can hold its own state.
Example: Note: Use this example for class,object,construtors and methods.
// Define a class called Car
class Car {
// Properties (attributes) of the Car class
String make;
String model;
int year;

// Constructor to initialize the Car object


Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method to display car details (behavior of the object)


void displayDetails() {
System.out.println("Car Make: " + make);
System.out.println("Car Model: " + model);
System.out.println("Car Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Car class (an instance)
Car myCar = new Car("Toyota", "Camry", 2020);

// Call the method using the object


myCar.displayDetails();
}
}

Q3. Explain constructors and its type.


A constructor is a special method used to initialize objects. When an object is created, a constructor is called to assign
initial values to its attributes. constructors do not have a return type, and their name must be the same as the class name.
Key Characteristics of Constructors:
1. Same Name as Class: The constructor must have the same name as the class.
2. No Return Type: Constructors do not return a value (not even void).
3. Called Automatically: The constructor is invoked automatically when an object of the class is created.
Types of constructors
1. Default Constructor
A default constructor is a constructor that takes no parameters. Java provides a default constructor automatically. This constructor
initializes all instance variables to their default values.
// Default constructor (no parameters)
Car() {
make = "Unknown";
model = "Unknown";
year = 0; }
2. Parameterized Constructor
A parameterized constructor takes arguments, allowing you to assign specific values to object properties when an object is created.
// Parameterized constructor
Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year; }
Q4. Explain the relation between objects and classes.
 A class is an abstract template that defines properties (data) and behaviors (methods).
 An object is a specific realization or instance of a class with its own set of values for the defined properties.
 Objects are created from classes, and multiple objects can be created from the same class, each with potentially different
states.
This relationship is the essence of object-oriented programming, where we model real-world entities (objects) using the structure and
behavior defined by classes.
Q5. Explain Encapsulation.
In Encapsulation data and the methods are encapsulated together and restricting access to the internal state of an object.
Encapsulation is often achieved by using access modifiers such as private, protected, and public to control visibility and access to the
attributes and methods of a class.
Data Hiding: Encapsulation allows the internal details of an object to be hidden.
Controlled Access: Through encapsulation, you can control how the internal data of an object is accessed or modified.
Improved Security and Maintainability: Encapsulation makes it easier to maintain code, debug, and apply changes without
affecting external code that uses the object.
Example:
Class Car{
Private String make ;
Privat string model;
Public Car(String make,String model){
This.make=make;
This.model=model; }
}
Q6. Explain method with example.
Methods are used to define the behaviors of an object or perform operations on data. They allow code to be reused and make the
program more modular and maintainable.
// Method to display car details
void displayDetails() {
System.out.println("Car Make: " + make);
System.out.println("Car Model: " + model);
System.out.println("Car Year: " + year); }
Q7. Explain variable scope with an example.
• Variables may be declared in:
 Class – state variables
 Method/constructor – local variables (and parameters)
 Inner block of a method – also local variables
• A variable is recognized throughout the block in which it was defined. This is called the scope of the variable.
• Local variables are allocated when the method is entered and freed when the method exits.
• The same name may be used in different scopes, and refer to totally different things
• If the same name is used in an outer and inner scope, then the inner scope definition “hides” the outer one.
• this operator – it is illegal to declare 2 local variable with the same name inside the same or enclosing scopes. However u
can have local variables, including formal parameters to methods, which overlap with the same name as the class instance
variables. However when the local variable has the same name as the instance variable , the local variable hides instance
variable. So u can use “this” to access the instance variable by the same name.
• public class Test
• {
• public static void main(String args[])
• {
• {
• // The variable x has scope within
• // brackets
• int x = 10;
• System.out.println(x);
• }

• // Uncommenting below line would produce
• // error since variable x is out of scope.

• // System.out.println(x);
• }
• }
• Output:
• 10
Q8. Explain Visibility modifiers (access modifiers)
Access modifiers are keywords in Java that are used to set accessibility. An access modifier restricts the access of a class, constructor,
data member and method in another class.
Java language has four access modifier to control access level for classes and its members.
•Default: Default has scope only inside the same package
•Public: Public has scope that is visible everywhere
•Protected: Protected has scope within the package and all sub classes
•Private: Private has scope only within the classes
public class Vehicle {
// Public variable public String type;
// Private variable private String vin;
// Protected variable protected String color;
// Default variable String engineType;}

Q9. Explain Visibility modifiers of a class with an example.


Default: when no modifier is present , by default the class is accessible by all the classes within the same package.
Class DefaultCar{
Private String make;
Private String model;}
Public: A public class is accessible by any class.
Public class PublicCar{
Private String make;
Private String model;}

Q10. Explain visibility modifier of a method with an example


Default: when no modifier is present , by default the class is accessible by all the classes within the same package.
Public: A public class is accessible by any class.
Protected: Referenced within package, or by sub classes outside package.
Private: A private method is accessible only by the class itself.
Example: private void GetEmployee(int ID) {}

Q11. Explain visibility modifier of a variable with an example.


Default: when no modifier is present, by default the class is accessible by all the classes within the same package.
Public: A public variable is accessible from anywhere.
Protected: Referenced within package, or by sub classes outside package.
Private: A private variable is accessible only by the class itself.
Example:
public class Vehicle {
protected String make;
Private String model; }
Q12. Write a short note of static modifier.
The static modifier in Java is used to define class-level members, meaning the member belongs to the class itself rather than to
instances (objects) of the class. It can be applied to variables, methods, blocks, and nested classes.
Static Variables:
 Also known as class variables, these are shared among all instances of a class.
 They are stored in the memory only once and are initialized when the class is loaded.
 Changing a static variable's value affects all objects of the class.

static int totalCars = 0; // Static variable


Static Methods:
 Can be called without creating an instance of the class.
 They can only access static variables or other static methods, as they belong to the class and not to a specific object.
Static void showTotalCars() {
// Static method System.out.println("Total Cars: " + totalCars); }
Static Blocks:
 Used to initialize static variables or perform class-level operations when the class is first loaded.
 They execute only once, when the class is loaded into memory.
public class Car {
static int totalCars;
tatic { // Static block
totalCars = 100; // Initializing static variable
}
Static Classes (Nested):
 A static nested class can be declared inside another class.
 It cannot access non-static members of the outer class directly.
public class OuterClass {
static class NestedClass {
static void display() {
System.out.println("Static nested class");
}
}

}
Q13. Explain the use of "this" keyword.
In java “this” is a keyword used to refer to the current object of a class. We can use it to refer to any member of the class.
public Car(String model, String color)
{ this.model = model;
this.color = color; }
Q14. Differentiate between types of variables.

Instance Variables (Non-static Fields): Variables declared inside a class but outside any method, constructor, or block. They are
associated with individual objects (instances) of the class.
Class Variables (Static Fields): Variables declared with the static keyword inside a class but outside any method or block. These
variables belong to the class rather than to any specific instance.
Local Variables: Variables declared inside a method, constructor, or block. They are created when the method is called and
destroyed when the method completes execution.
Parameters : Variables that are passed to methods or constructors as inputs. They are used to pass data into methods and
constructors.
Chapter 5 (10 marks)
Q1. State and explain the different ways of memory allocation.
Note: the below ans can be used for Q3 & 4 . To write a short note about heap and stack memory.
Stack Memory Allocation:
 Purpose: Stack memory is used for storing primitive data types (e.g., int, float, etc.) and references to objects.
 Usage: Whenever a method is called, local variables, including references to objects (but not the objects themselves), are
stored in the stack.
 Lifespan: Variables in the stack are automatically deallocated once the method execution is complete. Hence, it follows a
Last-In-First-Out (LIFO) structure.
 Example: int a = 5; // 'a' is stored in the stack
Heap Memory Allocation:
 Purpose: Heap memory is used for dynamic memory allocation and is primarily used to store objects and their instance
variables (non-primitive types).
 Usage: When an object is created using the new keyword, it is allocated memory on the heap.
 Lifespan: Objects remain in heap memory until they are no longer referenced, at which point Java’s Garbage Collector
automatically reclaims the memory.
 Example: Employee emp = new Employee(); // 'emp' object is allocated in the heap

Static Memory Allocation:


 Purpose: Static memory is used to store static variables (class-level variables) and methods.
 Usage: Static variables are stored in a special memory area separate from the stack and heap. They are allocated memory at
class loading time and deallocated when the class is unloaded.
 Lifespan: Static variables live throughout the execution of the program unless explicitly destroyed.
 Example: static int counter = 0; // Static variable stored in static memory

Q2. Differentiate between Heap memory and stack memory.


 Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
► Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory
only contains local primitive variables and reference variables to objects in heap space.
► Objects stored in the heap are globally accessible whereas stack memory can't be accessed by other threads.
■ Memory management in stack is done in LIFO manner whereas it's more complex in Heap memory because it's used globally.
Heap memory is divided into Young-Generation, Old-Generation etc.
► Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
► When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws
java.lang.OutOfMemoryError: Java Heap Space error.
► Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack
memory is very fast when compared to heap memory.

Q5. What is garbage collection?


You all know that an object is created in the memory using new operator. Constructor is used to initialize the properties of that
object. When an object is no more required, it must be removed from the memory so that that memory can be reused for other
objects. Removing unwanted objects or abandoned objects from the memory is called garbage collection (GC).
► Garbage collection (GC) is the process that aims to free up occupied memory that is no longer referenced by any reachable Java
object, and is an essential part of the Java virtual machine's (JVM's) dynamic memory management system. In a typical garbage
collection cycle all objects that are still referenced, and thus reachable, are kept. The space occupied by previously referenced objects
is freed and reclaimed to enable new object allocation.

Q6. Explain the reference counting technique of garbage collection.


► Main Idea: Add a reference count field for every object. This Field is updated when the number of references to an object
changes.
►Reference counting collectors keep track of how many references are pointing to each Java object. Once the count for an object
becomes zero, the memory can be immediately reclaimed.
This immediate access to reclaimed memory is the major advantage of the reference-counting approach to garbage collection.
Example:
public class A{
int i;
A (int i) {
this.i=i; }
}
A a1 = new A(3);
A a2 = a1;
A a3 = new A(5);
A a5 = a3;.
a3 = a1;
A a4 = a5
a4 = a1;
a5 = a1;
Advantages
 Conceptually simple: Garbage is easily identified
 It is easy to implement.
 Immediate reclamation of storage
 Objects are not moved in memory during garbage collection.
Disadvantages
 Reference counting does not detect garbage with cyclic references.
 The overhead of incrementing and decrementing the reference count each time.
 Extra space: A count field is needed in each object.
 It may increase heap fragmentation.

Q7. Explain the mark and sweep technique of garbage collection.


► The mark-and-sweep algorithm is divided into two phases:
■ Mark phase: the garbage collector traverses the graph of references from the root nodes and marks each heap object it encounters.
Each object has an extra bit: the mark bit - initially the mark bit is 0. It is set to 1 for the reachable objects in the mark phase.
Sweep phase: the GC scans the heap looking for objects with mark bit 0 - these objects have not been visited in the mark phase -
they are garbage. Any such object is added to the free list of objects that can be reallocated. The objects with a mark bit 1 have their
mark bit reset to 0.
Advantages
 It can reclaim garbage that contains cyclic references.
 There is no overhead in storing and manipulating reference count fields.
 Objects are not moved during GC - no need to update the references to objects.
Disadvantages
 It may increase heap fragmentation.
 It does work proportional to the size of the entire heap.
 The program must be halted while garbage collection is being performed.

Q8. Explain the stop and copy technique of garbage collection.


 The heap (memory) is split into two areas: an active region (where all objects are stored) and an inactive region (which is
empty).
 When the active region runs out of memory, the program pauses and the garbage collector starts.
 It copies all the still-in-use objects from the active region to the inactive region and updates any references to those objects.
 After copying, the active and inactive regions swap roles: the now-empty region becomes the new active space, and the
previously active region is cleared.
 This process reclaims all the memory used by objects that are no longer needed (the "garbage"), without copying them.
Advantages
 Only one pass through the data is required.
 It de-fragments the heap.
 It does work proportional to the amount of live objects and not to the memory size.
 It is able to reclaim garbage that contains cyclic references.
 There is no overhead in storing and manipulating reference count fields.
Disadvantages
 Twice as much memory is needed for a given amount of heap space.
 Objects are moved in memory during garbage collection (i.e., references need to be updated)
 The program must be halted while garbage collection is being performed.
Q9. Write a note on finalize method.
 It is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for
Garbage Collection, so as to perform clean-up activity. Clean-up activity means closing the resources associated with that
object like Database Connection. Network Connection or we can say resource de-allocation. Remember it is not a reserved
keyword.
 Once finalize method completes immediately Garbage Collector destroy that object.
Q10. Differentiate between final, finally and finalize.

Q11.What is object cloning in Java. State its advantages and disadvantages.


 The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.
 The java.lang.Cloneable Interface must be implemented by the class whose object clone we want to create. If we don't
implement Cloneable interface. generates Clone NotSupportedException. clone() method
 The clone() method is defined in the Object class.
 The clone() method saves the extra processing fask for creating the exact copy of an object. If we perform it by using the
new keyword, it will take a lot of processing time to be performed that is why we use object cloning.
Advantage of Object cloning
 You don't need to write lengthy and repetitive codes.
 It is the easiest and most efficient way for copying objects, especially if we are applying it to an already developed or an old
project. Just define a parent class, implement Cloneable interface provide the definition of the clone() method and the task
will be done.
 Clone() is the fastest way to copy array.
Disadvantage of Object cloning
 To use the Object.clone() method, we have to change a lot of syntax of our code, like implementing a Cloneable interface,
defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone() etc.
 We have to implement cloneable interface while it doesn't have any methods in it. We just have to use it to fell the JVM that
we can perform clone() on our object.
 Object.clone() is protected, so we have to provide our own clanell and indirectly call Object.clone() from it.
 Object.clone() doesn't invoke any constructor so we don't have any control over object construction.

Chapter 6 (14 marks)

Q1. What is the benefit/ advantage of inheritance?


 Code Reusability: Allows reuse of existing code, reducing redundancy by inheriting properties and methods from a parent
class.
 Improved Maintainability: Easier to maintain and update code, as changes made to a parent class are automatically
reflected in the child classes.
 Extensibility: Enables adding new features or behaviors to an existing class without modifying its code, by creating
subclasses that extend functionality.
 Polymorphism Support: Facilitates polymorphism, allowing the same method to behave differently based on the object
calling it, improving flexibility.
 Simplifies Code Structure: Encourages a logical hierarchical structure of classes, improving readability and organization.
 Overriding Methods: Allows child classes to provide specific implementations of methods that are defined in a parent
class.
Q2. Explain how inheritance promotes reusability and extendibility of code.
Inheritance Promotes Reusability:
 Reuse of Parent Class Methods: Child classes can inherit methods and properties from the parent class, avoiding code
duplication.
 Common Functionality Sharing: When multiple classes share common functionality, it can be defined once in a base
class and reused by different subclasses.
 Modifications in One Place: Changes or improvements made to the parent class automatically apply to all its child
classes, reducing the need to modify code in multiple places.
Inheritance Promotes Extendibility:
 Customizing Parent Class Behavior: Child classes can override or add new methods to extend or modify the behavior
of the parent class without altering the original code.
 Adding New Features: Developers can extend existing classes by adding new fields and methods to child classes while
keeping the original class intact.
 Building on Existing Classes: Inheritance allows new classes to be built on top of existing ones, facilitating the addition
of new functionality while preserving backward compatibility.

Q3. What are the different forms of inheritance?


Single inheritance: In single inheritance, subclasses inherit the features of one superclass.

class Animal { }
class Dog extends Animal { }

Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also
act as the base class to other class.
class Animal { }
class Mammal extends Animal { }
class Dog extends Mammal { }
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.

class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }

Multiple Inheritance: One class extending more than one class, which means a child class has two or more parent classes. Java does
not support multiple inheritance so through interface it is possible.

interface Animal { }
interface Pet { }
class Dog implements Animal, Pet { }

Hybrid Inheritance: A hybrid inheritance is a combination of more than one type of inheritance.

interface Animal { }
interface Pet { }
class Mammal { }
class Dog extends Mammal implements Animal, Pet { }

Q4. What are the issues with multiple inheritance?


 Ambiguity: Conflicts arise when two parent classes have methods or properties with the same name.
 Diamond Problem: Inherits from two classes with a common ancestor, causing ambiguity in method resolution.
 Increased Complexity: Makes class hierarchies harder to understand and maintain.
 Difficulties in Method Resolution: It can be challenging to determine which parent class method to invoke.
 Code Fragility: Changes in parent classes can unintentionally affect multiple child classes.
 Implementation Overhead: Managing multiple parent classes can introduce unnecessary complexity in design.
Q5. What is the difference between method overloading and method overriding?

Method Overloading Method Overriding


Method overloading is a compile-time polymorphism. Method overriding is a run-time polymorphism.
Method overloading helps to increase the readability of the Method overriding is used to grant the specific implementation
program. of the method which is already provided by its parent class or
superclass.
It occurs within the class. It is performed in two classes with inheritance relationships.
Method overloading may or may not require inheritance. Method overriding always needs inheritance.
In method overloading, methods must have the same name and In method overriding, methods must have the same name and
different signatures. same signature.
In method overloading, the return type can or can not be the In method overriding, the return type must be the same or co-
same, but we just have to change the parameter. variant.
Static binding is being used for overloaded methods. Dynamic binding is being used for overriding methods.
Private and final methods can be overloaded. Private and final methods can’t be overridden.
The argument list should be different while doing method The argument list should be the same in method overriding.
overloading.

Q6. Explain the concept of polymorphic attachment.


 Parent Class Reference: A reference variable of a parent class can hold references to objects of its subclasses.
 Dynamic Method Dispatch: The actual method called is determined at runtime, based on the object's type (not the reference
type).
 Polymorphism: Enables different behaviors through the same interface (e.g., method overriding in child classes).
 Flexible Code: Allows writing general code in the parent class that can work with objects of different subclasses.
 Key Benefit: Promotes flexibility and extensibility in code, allowing runtime behavior variations.
 Example: Animal a = new Dog(); // Parent reference, child object
a. sound(); // Calls Dog's overridden method at runtime.
Q7. What is dynamic binding?
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is
eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}

Q8. Differentiate between static and


dynamic typing in inheritance.
Q9. Explain the concept of abstract (differed) class.
 An abstract class cannot be instantiated, which means you are not allowed to create an object of it.
 To use an abstract class, you must inherit it from another class, provide implementations to the abstract methods in it
 If you inherit an abstract class, you must provide implementations to all its abstract methods.
 Example: abstract class Vehicle {}
Q10.State the uses of abstract (differed)features and classes.
 Common Structure: Abstract classes define a blueprint for related subclasses, enforcing a common structure.
 Partial Implementation: Provide some method implementations while leaving others abstract for subclasses to complete.
 Polymorphism: Enable polymorphic behavior, allowing abstract class references to refer to any subclass object.
 Code Reusability: Share common functionality across subclasses, promoting code reuse and reducing duplication.
 Prevent Direct Instantiation: Abstract classes cannot be instantiated, ensuring only specialized subclasses can be created.
 Contract Enforcement: Abstract methods enforce that all subclasses must implement certain behaviors, ensuring
consistency.

Q11.what is extension specialization paradox in inheritance?


Generalization
Converting a subclass type into a superclass type is called ‘Generalization‘because we are making the subclass to become more
general and its scope is widening. This is also called widening or up casting. Widening is safe because the classes will become
more general.
For example, if we say Car is a Vehicle, there will be no objection. Thus Java compiler will not ask for cast operator in
generalization.
Specialization
Converting a super class type into a sub class type is called ‘Specialization‘. Here, we are coming down from more general form
to a specific form and hence the scope is narrowed. Hence, this is called narrowing or down-casting.
Narrowing is not safe because the classes will become more and more specific thus giving rise to more and more doubts. For
example if we say Vehicle is a Car we need a proof. Thus, In this case, Java compiler specifically asks for the casting. This is
called explicit casting.
Q12. What is the role of differed (abstract) classes?
Abstract classes in Java play a key role in object-oriented programming by providing a base for subclasses to extend and implement:
 Code reusability: Abstract classes can help save time by avoiding the need to rewrite the same code.
 Data abstraction: Abstract classes help hide code complications from the end-user by reducing the project's characteristics
to only the necessary components.
 Loose coupling: Abstract classes can reduce dependencies exponentially.
 Dynamic resolution: Abstract methods can help solve multiple problems.
 Shared functionality: Abstract classes can offer a balance between enforcing a contract and providing some shared
functionality
Extra Points about abstract classes
 Abstract classes can have both abstract and non-abstract methods.
 Abstract classes can contain instance variables.
 A class can only extend one abstract class.
 Abstract classes can have constructors.
 You cannot create an object (or instance) of an abstract class.
Q13. Compare and contrast differed and effective classes.
 Abstract classes cannot be instantiated, while concrete classes can be directly instantiated to create objects.
 Abstract classes may leave some methods undefined (abstract), requiring subclasses to implement them. Concrete
classes provide full method implementations.
 Abstract classes are used when you need to define a template for future classes, whereas concrete classes are used when
you want a fully functional class that can be instantiated immediately.
 Abstract classes must be inherited by another class to be used; subclasses must provide implementations for abstract
methods. Concrete classes do not require inheritance to be used; they are self-sufficient.
 Abstract Classes Used to share common behavior across multiple classes but leave specific details to subclasses.
Concrete Classes Used when you want a fully functional class that can be used as-is.
 Abstract Classes: Focus on defining "what should be done”.Concrete Classes: Focus on defining "how it is done."
Chapter 7 (4 marks)

Q1. Explain multiple inheritance with a diagram.


Multiple Inheritance: One class extending more than one class, which means a child class has two or more parent classes. Java does
not support multiple inheritance so through interface it is possible.

Class C extends both class A and B.


interface Animal { }
interface Pet { }
class Dog implements Animal, Pet { }

Q2. Why is multiple inheritance not supported in Java?


 To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
 Consider a scenario where A, B, and C are three classes.
 The C class inherits A and B classes,
 If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method
of A or B class resulting in Diamond problem.
 Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes So whether
you have same method or different, there will be compile time error.
Code example of Multiple Inheritance

class A { void msg() } {System.out.println("Hello");}


class B { void } msg(){System.out.println("Welcome");}
class C extends A, B {//suppose if it were
public static void main(String args[]) {
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
Q3. Explain Diamond problem with the help of an example.
 Consider a scenario where A, B, and C are three classes.
 The C class inherits A and B classes,
 If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method
of A or B class resulting in Diamond problem.
Code example of Multiple Inheritance
class A { void msg() } {System.out.println("Hello");}
class B { void } msg(){System.out.println("Welcome");}
class C extends A, B {//suppose if it were
public static void main(String args[]) {
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
Q4. How to implement multiple inheritance in java?
To implement multiple inheritance in Java, since Java does not support multiple inheritance directly through classes, you can achieve
similar functionality using interfaces.
 Create multiple interfaces: Define multiple interfaces containing method signatures.
 Implement multiple interfaces in a single class: A class can implement multiple interfaces to inherit their methods.
 Override methods: In the class, provide the implementation of all the methods declared in the interfaces.
 Create an object of the class: Use the class that implements multiple interfaces to create an object and invoke the methods.
 Use default methods (optional): Interfaces can also have default methods, which allows providing some method
implementation in the interface itself.
 Handle ambiguity (in case of default methods): If two interfaces contain the same default method, override it in the
implementing class to resolve ambiguity.
Example Code
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method A from interface A");
}

public void methodB() {


System.out.println("Method B from interface B");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}
Q5. Why do we use interfaces?
 Achieve abstraction: Interfaces allow defining a contract (methods) without specifying the implementation, promoting
abstract design.
 Multiple inheritance: Java doesn't support multiple inheritance with classes, but interfaces allow a class to implement
multiple interfaces.
 Ensure implementation: Interfaces ensure that classes provide specific behavior by enforcing the implementation of the
declared methods.
 Loose coupling: By using interfaces, you can write code that is loosely coupled and flexible, making it easier to update or
replace implementations.
 Polymorphism: Interfaces allow objects of different classes to be treated in the same way if they implement the same
interface, supporting polymorphism.
 Code maintainability: Interfaces separate the "what" from the "how," making the code more modular, easier to maintain,
and extend over time.
Q6. How can diamond problems be resolved through interfaces?
interface A {
default void display() {
System.out.println("Display method from Interface A");
}
}
interface B {
default void display() {
System.out.println("Display method from Interface B");
}
}
class C implements A, B {
// Overriding the conflicting default method to resolve ambiguity
@Override
public void display() {
// You can explicitly choose which interface's method to call
A.super.display(); // Call display() from Interface A
// or
// B.super.display(); // Uncomment this to call display() from Interface B
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.display(); // Will call the overridden display() method in class C
}
}
 Interface A and B: Both define a default method display() with different implementations.
 Class C: Implements both interfaces A and B. To resolve the diamond problem (ambiguity between A's and B's display()
methods), class C overrides the display() method.
 Inside C’s display() method: You can specify which interface’s method to call using A.super.display() or B.super.display().

Chapter 8 (10 marks)


Q1. What are the different types of errors? What is exception handling?

•There are three categories of errors:


–syntax errors
–runtime errors
–logic errors.

•Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler.

•Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out.

•Logic errors occur when a program doesn't perform the way it was intended to.
 An exception is an abnormal condition that arises in a code sequence at run time
 A Java exception is an object that describes an exceptional condition that has occurred in a piece of code
 When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused
the error
 An exception can be caught to handle it or pass it on
 Exceptions can be generated by the Java run-time system, or they can be manually generated by your code.
 Performing action in response to exception
Examples
 Exit program (abort)
 Deal with exception and continue
 Print error message
 Request new data
 Retry action
Q2. What are checked and unchecked exceptions?
 Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These are also called
Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions
are ignored at the time of compilation.
 Runtime Exception, Error and their subclasses are known as unchecked exceptions.
 Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at compilation-time,
these are also called compile time exceptions. These exceptions cannot be ignored; the programmer should handle them.
 All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal
with the exceptions.

Q3 & 4. Explain exception handling mechanisms. Explain the various constructs used in exception handling.

 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally
 The try statement allows you to define a block of code to be tested for errors while it is being executed.
 If an exception occurs within the try block, it is thrown
 The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The try block
must be followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means we
can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed whether an
exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that
there may occur an exception in the method. It is always used with method signature.
Example:
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Q5. When do we use multiple catch construct?

 If more than one exception type can occur, then we use multiple catch clauses
 When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the
exception is executed
 After one catch statement executes, the others are bypassed

Example:
Q6. Explain nested try statements.
 The try block within a try block is known as nested try block in java.
Why use nested try block
 Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.
Exmple:
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}

Q7. Explain throw and throws.OR differentiate between throw and throws.
Throw: In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are
throwing the ArithmeticException otherwise print a message welcome to vote.
Example
public class MyClass {
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid"); else
System.out.println("welcome to vote");
}
public static void main(String args[]) {
try{
validate(13); } catch(ArithmeticException e){ System.out.println("exception " +e); } System.out.println("rest
of the code..."); }}

Output:
exception java.lang.ArithmeticException: not valid
rest of the code...
Throws: The throws keyword is used to declare the list of exception that a method may throw during execution of program. Any
method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that
method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword.
Example:
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try{
check();
}
catch(ArithmeticException e){System.out.println("caught" + e);}
}
}
Inside check function
caughtjava.lang.ArithmeticException: demo

throw throws

throws keyword is used to declare an exception possible during


throw keyword is used to throw an exception explicitly.
its execution.

throw keyword is followed by an instance of Throwable class throws keyword is followed by one or more Exception class
or one of its sub-classes. names separated by commas.

throws keyword is used with method signature (method


throw keyword is declared inside a method body.
declaration).

We can declare multiple exceptions (separated by commas)


We cannot throw multiple exceptions using throw keyword.
using throws keyword.

Q8. Explain with an example user defined exception.


 Define a subclass of the Exception class.
 The new subclass inherits all the methods of Exception and can override them.
class MyException extends Exception{
private int a;
MyException(int i) { a = i;}
public String toString (){ return “MyException[“ + a+”]”;}

}
class test{
static void compute (int a) throws Myexception{
if(a>10) throw new MyException(a);
System.out.println(“Normal Exit”);
}
public static void main(String args[]){
try{
compute(1);
compute(20);
}catch(MyException e){ System.out.println(“Caught “ +e);
}
}
Chapter 9 (16 marks)
Q1.Explain the concept of generics classes with an example class with at least one parameter type.

Generic Classes: A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type
parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more
parameters, are known as parameterized classes or parameterized types.
// A Simple Java program to show working of user defined Generic classes

Example :
// We use < > to specify Parameter type
class Test<T>
{
T val; // An object of type T is declared
Test(T val) { // constructor
this.val = val;
}
public T getval() {
return this.val;
}
}
class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getval());

// instance of String type


Test <String> sObj =new Test<String>("GeeksForGeeks");
System.out.println(sObj.getval());
}
}
Output:
15
Q2. Explain concept of genric function with an example code that defines and call this function from the main function.
 In Java, generic functions (or methods) allow us to create methods that operate on objects of various types while still
maintaining type safety. Instead of defining a method for each data type (e.g., int, String, double), we can define one generic
method and use it with any type of object.
Exampe:
// Define a class with a generic method
public class GenericExample {

// Generic method that accepts any type of object and prints it


public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println(); // For a new line
}

// Main function to call the generic method


public static void main(String[] args) {
// Integer array
Integer[] intArray = {1, 2, 3, 4, 5};
// String array
String[] strArray = {"Hello", "World", "Generics"};

// Calling the generic method with an Integer array


System.out.println("Integer Array:");
printArray(intArray); // Output: 1 2 3 4 5

// Calling the generic method with a String array


System.out.println("String Array:");
printArray(strArray); // Output: Hello World Generics
}
}

Q3.With the help of an example code, justify that with the help of genrics classes we can implement algorithms that work on
different datatypes.
´ Implementing generic algorithms: By using generics, we can implement algorithms that work on different types of objects
and at the same they are type safe too.
´ Example program to sort string, integers on Colletions.sort

import java.util.*;
public class GenClass {
public static void main(String[] args) {
List<String> names= new ArrayList<>();
names.add("mia"); names.add("sia"); names.add("tia");
List<Integer> intergs= Arrays.asList(3,5,2,4,7,1);
Collections.sort (names);
System.out.println(names);
Collections.reverse(names);
System.out.println(names);
Collections.sort (intergs);
System.out.println(intergs);
}}
´ Q4. With the help of example code briefly explain the use of any 3 collection classes
´ Java provides a set of standard collection classes that implement Collection interfaces. Examples include the follwing:
´ LinkedList - The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list
data structure.
´ ArrayList - The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays
that can grow as needed.
´ Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must
know in advance how many elements an array will hold.
´ Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects
are removed, the array may be shrunk.
´ HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
´ A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used
to determine a unique value, called its hash code.
´ The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key
into its hash code is performed automatically.
´ HashMap - The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic
operations, such as get( ) and put( ), to remain constant even for large sets.
Q5.list any 4 benefits of using generic classes in developing object oriented systems
´ Advantages of Generics:
Programs that uses Generics have many benefits over non-generic code.
´ 1. Code Reuse: We can write a method/class/interface once and use for any type we want.
´ 2. Type Safety : Generics generates errors at compile time than at run time (It’s always better to know problems in your
code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store
names of students and if by mistake programmer adds an integer object instead of string, compiler allows it. But, when we
retrieve this data from ArrayList, it causes problems at runtime.

List list = new ArrayList();


list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
´ 3. Type casting is not required: There is no need to typecast the object.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
´ 4. Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming
strategy says it is far better to handle the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Q6. Individual type casting is not needed when using generic classes. Explain the statement with the help of an
example code.
Individual Type Casting is not needed:
If we do not use generics, then, in the above example every-time we retrieve data from ArrayList, we have to typecast it.
Typecasting at every retrieval operation is a big headache. If we already know that our list only holds string data then we
need not to typecast it every time.
// We don't need to typecast individual members of ArrayList
import java.util.*;
class Test {
public static void main(String[] args) {
// Creating a an ArrayList with String specified
ArrayList <String> al = new ArrayList<> ();
al.add("Sachin");
al.add("Rahul");
// Typecasting is not needed
String s1 = al.get(0);
String s2 = al.get(1);
}}
// Java program to Demonstrate List Interface
import java.util.*;
public class GFG {
public static void main(String[] args){
List<Integer> l1 = new ArrayList<Integer>();
l1.add(0, 1);
l1.add(1, 2);
l1.add(2, 3);
l1.add(3, 4);
System.out.println(l1);
// Removes element from index 1
l1.remove(1);
// Printing the updated List 1
System.out.println(l1);
// Prints element at index 1 in list 1
System.out.println(l1.get(1));
// Replace 0th element with 5
l1.set(0, 5);
// Again printing the updated List 1
System.out.println(l1);
}
}

Q7.Explain Briefly the significance of collection framework(advantages)


´ The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for
manipulating them.
´ A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be
performed on each type of collection.
´ The classes and interfaces of the collections framework are in package java.util.
´ The collections framework was designed to meet several goals, such as −
´ The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked
lists, trees, and hashtables) were to be highly efficient.
´ The framework had to allow different types of collections to work in a similar manner and with a high degree of
interoperability .
´ The framework had to extend and/or adapt a collection easily.
´ Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard
implementations(i.e. classes) of these interfaces such as LinkedList (implements List), HashSet (implements Set), and
TreeSet (implements Set), are provided that you may use as-is and you may also implement your own collection, if you
choose.
Q8. What is a collection framework?what are its different components?
´ A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks
contain the following −
´ Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated
independently of the details of their representation.
´ Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are
reusable data structures.
´ Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that
implement collection interfaces
´ In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are
not collections in the proper use of the term, but they are fully integrated with collections.
Q9.Briefly outline the use of any 4 collection framework interfaces?
´ The collections framework defines several interfaces. Some examples include:
´ The Collection Interface This enables you to work with groups of objects; it is at the top of the collections hierarchy. The
Collection interface is the foundation upon which the collections framework is built. It declares the core methods such as
add(Object O), remove(Object O), clear(), etc that all collections will have.
´ The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.
´ The Set This extends Collection to handle sets, which must contain unique elements.
´ The SortedSet This extends Set to handle sorted sets.
´ The Map This maps unique keys to values.
Q10.Briefly explain the use of any 4 collection framework classes?
´ Java provides a set of standard collection classes that implement Collection interfaces. Examples include the follwing:
´ LinkedList - The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list
data structure.
´ ArrayList - The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays
that can grow as needed.
´ Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must
know in advance how many elements an array will hold.
´ Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects
are removed, the array may be shrunk.
´ HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
´ A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used
to determine a unique value, called its hash code.
´ The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key
into its hash code is performed automatically.
´ HashMap - The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic
operations, such as get( ) and put( ), to remain constant even for large sets.

You might also like