Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Answer---Object Oriented Programming-2022

Object oriented

Uploaded by

PRADIP PAUL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Answer---Object Oriented Programming-2022

Object oriented

Uploaded by

PRADIP PAUL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Object Oriented Programming

Paper Code: PCC-CS503

Group-A
(Very Short Answer Type Question; 1-Mark Question)

(I) In which memory a String is stored, when we create a string using new operator?
Heap memory

(II) ________________ is an abstract machine. It is a specification that provides runtime


environment in which java bytecode can be executed.
Java Virtual Machine (JVM)

(III) Which of the following keywords are used to control access to a class Member?
A) new
B) abstract
C) public
D) interface
C) public

(IV) An abstract class, which declared with the “abstract” keyword, cannot be instantiated. True
or False?
True

(V) Out of the following which one is not correctly matched?


A) JAVA - Object Oriented Language
B) FORTRAN - Object Oriented Language
C) C++ - Object Oriented Language
D) BASIC - Procedural Language
B) FORTRAN - Object Oriented Language

(VI) "A package is a collection of classes, interfaces and sub-packages"


The above statement is true or false?
True

(VII) Which of the following statements is valid array declaration?


A) int number ()
B) float average [ ]
C) int marks
D) count int[ ]
B) float average [ ]

(VIII) Java virtual machine is ________________. Fill in the blank.


A) platform dependent totally
B) independent
C) depends on machine architecture only
D) depends on OS only
B) independent

(IX) Which method is used to set the graphics current color to the specified color in the graphics
class?
setColor()
(X) Java is robust because ________________ . Fill in the blank.
A) it is object oriented
B) garbage collection is present
C) inheritance is present
D) exception handling
B) garbage collection is present

(XI) Consider the following 2 statements(S1 and S2).


(S1) C++ uses compiler only.
(S2) Java uses compiler and interpreter both.
Above statements are true or false?
True (S1 is false, S2 is true)

(XII) What is the length of the application box made by the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
A) 20
B) 50
C) 100
D) System dependent
D) System dependent

Group-B
(Short Answer Type Question; 5-Mark Question)

2. What is qualified association? Describe with an example.


 Qualified Association is a type of association in object-oriented design where a class refers
to another class with an additional qualification or condition. It is often represented with a
role or multiplicity constraint on the associated class.
Example: A Car class can have a qualified association with a Driver class, where each driver has a
unique driver ID.
class Driver {
int driverId;
String name;
}
class Car {
Driver driver; // Qualified association with Driver class
}
3. What is an object? Why Java is called an object-oriented language? Write the
difference between procedural oriented programming and object oriented
programming.
 Object: An object is an instance of a class, containing both data (attributes) and methods
(functions) that operate on that data. Objects model real-world entities.
 Java as Object-Oriented Language: Java is called object-oriented because it uses objects and
classes to structure and organize code. It follows the principles of object-oriented
programming such as encapsulation, inheritance, and polymorphism.

Difference between procedural oriented programming and object oriented programming


Procedural-Oriented Programming
Aspect Object-Oriented Programming (OOP)
(POP)
Focuses on functions or procedures Focuses on objects that encapsulate both data
Focus
that operate on data. and behavior.
Data Data is separate from functions; Data and functions (methods) are bundled
Organization functions operate on global data. together into objects.
Data is encapsulated within objects and
Data Handling Data is often passed between functions.
manipulated through methods.
Top-down approach; large tasks are
Bottom-up approach; objects are designed
Methodology broken into smaller tasks using
first, and then their interactions are defined.
functions.
Code Reusability is achieved by calling the Reusability is achieved through inheritance,
Reusability same function multiple times. polymorphism, and method overriding.
Supports inheritance, allowing classes to
Inheritance Does not support inheritance. inherit behaviors and properties from other
classes.
Supports encapsulation by keeping data
No built-in mechanism for
Encapsulation hidden and providing controlled access
encapsulation; data is accessed directly.
through getter and setter methods.
Supports polymorphism, where one method
Polymorphism Does not support polymorphism. can have different behaviors depending on
the object type.
Functions are used to break down the Objects are modular units that represent real-
Modularity program into smaller parts, but data world entities, leading to better organization
remains separate. and flexibility.
Example
C, FORTRAN, BASIC. Java, C++, Python, C#.
Languages
Simpler and easier to understand for More scalable and easier to maintain,
Advantages
small programs. especially for large and complex applications.
Poor at handling large and complex
Requires more upfront planning and design.
software systems, as it becomes hard to
Disadvantages Complex systems may become more difficult
manage the interrelationship between
to manage.
functions.
4. Explain static keyword with suitable Java code.
 The static keyword is used in Java to indicate that a particular field, method, or block belongs
to the class rather than to instances of the class. This means it can be accessed without creating
an object of the class.
Example:
class Counter {
static int count = 0; // Static variable

static void increment() { // Static method


count++;
}
}
public class Main {
public static void main(String[] args) {
Counter.increment(); // Accessing static method without object
System.out.println(Counter.count); // Output: 1
}
}

5. What is dynamic method dispatch in Java? Explain with an example.


 Dynamic Method Dispatch is a mechanism in Java where a method call is resolved at
runtime rather than compile-time. It is used in method overriding and allows Java to decide
which method to call based on the object that invokes the method, even if the reference is of
a superclass type.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Parent class reference, child class object
animal.sound(); // Output: Dog barks (Dynamic method dispatch)
}
}
6. What is AWT? What is Event Listener?
 AWT (Abstract Window Toolkit): AWT is a set of APIs provided by Java for building
graphical user interfaces (GUIs). It includes components like buttons, text fields, and
windows.
 Event Listener: An Event Listener in Java is an interface used to receive and handle events
(such as mouse clicks, key presses, etc.) that occur on GUI components. It "listens" for an
event and responds when the event occurs.
Example:
import java.awt.*;
import java.awt.event.*;

public class ButtonExample extends Frame implements ActionListener {


Button b;

ButtonExample() {
b = new Button("Click Me");
b.setBounds(30, 50, 80, 30);
b.addActionListener(this);
add(b);
setSize(200, 200);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


System.out.println("Button clicked!");
}

public static void main(String[] args) {


new ButtonExample();
}
}
Group-C
(Long Answer Type Question; 15-Mark Question)
7. Discuss the differences between the following:
7(i) ‘throw’ and ‘throws’ clause:
Comparison ‘throw’ ‘throws’
Used to explicitly throw an exception Used in method signatures to declare
Purpose
from a method or block of code. exceptions that a method might throw.
Usage throw is followed by an exception object. throws is followed by exception types.
public void myMethod() throws
Example throw new ArithmeticException("Error");
IOException {}
Can be used inside methods or blocks of
Location Used only in method declaration.
code.
Transfers control to the catch block or Passes responsibility of handling the
Responsibility
default handler. exception to the calling method.
7(ii) final and finally:
Comparison ‘final’ ‘finally’
Used to define constants, prevent Used to define a block of code that will
Purpose method overriding, or prevent class always execute after a try-catch block,
inheritance. regardless of exception.
Can be used with variables, methods, Always used as a block following try-
Usage
and classes. catch.
finally { System.out.println("Always
Example final int MAX = 100;
executed"); }
Code in the finally block always
Once assigned, the value of a final
Effect executes, even if an exception is
variable cannot be changed.
thrown.

7(iii) Abstract classes and Interfaces:


Comparison Abstract Classes Interfaces
Provides a partial abstraction and can Provides a full abstraction (before Java 8) and
urpose have both abstract and concrete only declares method signatures, which must
methods. be implemented by the classes.
Can have both abstract (without
Only contains abstract methods (in Java
Usage implementation) and concrete
versions before 8).
methods (with implementation).
A class can inherit only one abstract A class can implement multiple interfaces
Inheritance
class (single inheritance). (multiple inheritance).
abstract class Animal { abstract void
Example interface Animal { void sound(); }
sound(); }
Fields Can have instance variables (fields). Can only have constants (static final fields).
Constructors Can have constructors. Cannot have constructors.

8. Write short notes of the following:


8(i) Link and Association:
 Link: A link is a connection between two objects in the context of object-oriented design,
representing an instance of an association between objects.
 Association: Association is a structural relationship between two or more objects. It defines
how objects are related to each other. For example, a Student and a Course might have a
many-to-many association.
Example:
class Student {
Course course; // association between Student and Course
}

8(ii) Thread Life-Cycle: The Thread Life Cycle defines the states a thread goes through in its life.
It includes the following states:
i. New: A thread is in this state when it is created but has not yet started.
ii. Runnable: A thread is in this state when it is ready to run but may be waiting for CPU time.
iii. Blocked: A thread is in this state when it is waiting for a resource that is currently
unavailable.
iv. Waiting: A thread is in this state when it is waiting indefinitely for another thread to perform
a specific action.
v. Timed Waiting: A thread is in this state when it is waiting for a specific amount of time.
vi. Terminated: A thread is in this state when it has completed execution.
8(iii) Abstraction: It is one of the core concepts in object-oriented programming (OOP), where only
the essential details of an object are shown to the user, and the implementation details are hidden.
The goal of abstraction is to reduce complexity by hiding unnecessary implementation details and
showing only the functionality to the user.
Types of Abstraction in Java:
1. Abstract Classes:
o An abstract class is a class that cannot be instantiated directly. It may contain both
abstract methods (methods without implementation) and concrete methods (methods
with implementation).
o It provides a way to define a common structure or behavior that can be shared across
multiple derived classes.
o Subclasses of the abstract class must provide implementations for the abstract
methods
2. Interfaces:
o An interface in Java is similar to an abstract class, but all methods in an interface are by default
abstract (before Java 8). Interfaces can be implemented by classes, and a class can
implement multiple interfaces.
o Unlike abstract classes, interfaces cannot contain instance fields (only constants) and
cannot have constructor methods.
o Interfaces allow you to define methods without specifying their behavior. The
behavior must be implemented by the classes that implement the interface.
Example: Using an Abstract Class
abstract class Shape {
abstract void draw();
void area() { System.out.println("Area calculated."); }
}

class Circle extends Shape {


void draw() { System.out.println("Circle drawn"); }
}

class Rectangle extends Shape {


void draw() { System.out.println("Rectangle drawn"); }
}

public class Main {


public static void main(String[] args) {
Shape s1 = new Circle();
s1.draw();
s1.area();

Shape s2 = new Rectangle();


s2.draw();
s2.area();
}
}
9. Write short notes of the following:
9(i) Dynamic Method Dispatch: Dynamic Method Dispatch is a process in Java where a call to an
overridden method is resolved at runtime rather than at compile-time. This allows Java to support
runtime polymorphism. The actual method that gets invoked is based on the object type, not the
reference type.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Dog(); // Dynamic method dispatch
animal.sound(); // Output: Dog barks
}
}

9(ii) Dynamic Binding: Dynamic Binding is the process of resolving method calls at runtime. It
occurs when a method is called on an object, but the specific method to be executed is determined
based on the object's actual class at runtime. This supports polymorphism and method overriding.
9(iii) Encapsulation: Encapsulation is a fundamental concept in object-oriented programming
where the internal details of an object are hidden and only accessible through public methods. This
helps in restricting direct access to an object's state and ensures that it is modified only in controlled
ways.
Example:
class Person {
private String name; // private field

public String getName() { // public method


return name;
}

public void setName(String name) { // public method


this.name = name;
}
}
10. Create a package and write a Java file with four methods for four basic arithmetic operations:
a. ArithmeticOperations.java (inside package arithmetic)
package arithmetic;

public class ArithmeticOperations {

public int add(int a, int b) {


return a + b;
}

public int subtract(int a, int b) {


return a - b;
}

public int multiply(int a, int b) {


return a * b;
}

public double divide(int a, int b) {


if (b != 0) {
return (double) a / b;
} else {
System.out.println("Cannot divide by zero");
return 0;
}
}
}
b. Main.java (outside the package)
import arithmetic.ArithmeticOperations;

public class Main {


public static void main(String[] args) {
ArithmeticOperations obj = new ArithmeticOperations();

System.out.println("Addition: " + obj.add(10, 5));


System.out.println("Subtraction: " + obj.subtract(10, 5));
System.out.println("Multiplication: " + obj.multiply(10, 5));
System.out.println("Division: " + obj.divide(10, 5));
}
}
11. (a) What are exceptions? Explain the user-defined exceptions and system-defined exceptions
with suitable examples.
Exceptions: Exceptions are runtime anomalies or errors that disrupt the normal flow of a program.
In Java, exceptions are represented by classes that extend Throwable. They are divided into checked
exceptions (which must be handled) and unchecked exceptions (runtime exceptions).
 User-Defined Exceptions: These are exceptions created by the programmer to handle
specific error scenarios. They are typically subclasses of Exception.
Example:
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

 System-Defined Exceptions: These are exceptions that are predefined in Java, like
NullPointerException, ArrayIndexOutOfBoundsException, etc.

11. (b) Briefly explain the use of “this” and “super” keywords.
 this: Refers to the current object. It is used to differentiate between instance variables and
local variables or to call a constructor of the current class.
o Example:
class Person {
String name;
Person(String name) {
this.name = name; // this refers to the instance variable
}
}
 super: Refers to the superclass of the current object. It can be used to access superclass
methods or constructors.
o Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calls the superclass method
System.out.println("Dog barks");
}
}

11. (c) Difference between == operator and equals() method in the context of string objects.
 == operator: The == operator compares the references (memory addresses) of two string
objects, not their actual contents. It returns true if both references point to the same object.
Example:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);
// Output: false (

You might also like