Oop1 031329
Oop1 031329
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.
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.
}
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
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 { }
•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.
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
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.
}
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());
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.