0% found this document useful (0 votes)
38 views

Oops - IT-1 (Answer Key)

Uploaded by

hod
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)
38 views

Oops - IT-1 (Answer Key)

Uploaded by

hod
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/ 16

PART A

1 What is object-oriented programming?

OOP can make software development more reusable, and maintainable, which can make it easier to upgrade

and update the system.

1) OOP is faster and easier to execute.

2) OOP provides a clear structure for the programs.

3) OOP helps to keep the Java code DRY "Don't Repeat Yourself",

4) OOP makes the code easier to maintain, modify and debug.

2 Name the access modifier.

Access modifiers in programming languages like Java are used to control the visibility and accessibility of
classes, methods, and variables. The main access modifiers are:
1. Public: Allows access from anywhere in the program.

2. Private: Restricts access to within the same class only.

3. Protected: Allows access within the same package or subclasses.

3 Write a simple java program to print hello world.

public class HelloWorld {


public static void main(String[] args) {

System.out.println("Hello, World!");

4 Distinguish between object and class

Feature Class Object

Definition Blueprint or template for creating objects Instance of a class

Memory Memory is allocated when an object is


No memory is allocated for a class itself
Allocation created

Usage Defines properties and behaviors Holds actual data and can call methods

Example class Car { } Car myCar = new Car();

Conceptual (exists only in code as a


Existence Physical (exists in memory at runtime)
definition)
5 Illustrate the use of super keywork.

The super keyword in Java is used to refer to the parent class (superclass) of the current object. It can be
used in three ways:

1. Accessing Superclass Constructor: super() is used to call the parent class's constructor.

2. Accessing Superclass Methods: super.method() is used to call a method from the parent class.

3. Accessing Superclass Variables: super.variable is used to access a variable from the parent class
when the subclass has a variable with the same name.

PART B
6ai). Explain in detail about the features of java programming language.

Features of Java Language

1. Simple and Small programming language

Non-programmers also can learn comfortably

Syntax of Java resembles with C and C++

2. Robust and Secure

Robust: (Ability to handle errors, unexpected situations eAiciently, stable execution)

As its not support points, impossible to accidentally reference memory belong to other program.

Secure: Output Of Java compiler is not executable code it's a bytecode.

JVM convert bytecode to machine readable, it will not execute virus infected codes. (Java Virtual

Machine)

Automatic memory management. On C and C++ it's done explicitly by user

Java Applet execution on browser is not allowed to access files system on local machine.

3. Platform independent and Portable

Platform Independent: Java can be executed on various platforms. (Windows, MacOS, Linux)
Write once, run anywhere, anytime forever.

Portability: Java bytecodes can be further used to obtain machine code

Primitive data types used in java are machined independent

4. Object Oriented Programming language

Java is an Object oriented programming language

Support OOPS features like: data encapsulation, inheritance, polymorphism and dynamic biding.

As everything in Java is object, can be extended easily


5. Multithreaded and Interactive

Java support multithreaded program, which can perform many tasks at a time

Help developer to develop more interactive code

6. Compiled and Interpreted

Java can be compiled as well as interpreted

Compiler translates the Java program into bytecode

Interpreter interprets the bytecode into machine code

7. High Performance, Scalability, Monitoring and Manageability


Performance: Use of bytecode and multi-threading helps to improve the performance

Scalability: (System handle workload) J2SE help to increase scalability

Monitoring and Management: Java have number of APIs and Tools for monitoring and management

8. Dynamic and Extensible

Java capable of dynamically linking new class libraries, methods, objects

Java support functions written in C and C++ (native methods)

9. Designed for distributed Systems

In java two diAerent objects on diAerent computers can communicate

Can be achieved by Remote Method Invocation(RMI). Used on Client-Server communication

6A ii) Explain about the fundamental principle of oops with respect to java programming.

The fundamental principles of Object-Oriented Programming (OOP) in Java are encapsulation, inheritance,
polymorphism, and abstraction. Here's a brief explanation of each:

1. Encapsulation

• Encapsulation bundles data (variables) and methods (functions) into a class, restricting direct access
to some components using access modifiers like private. This promotes data security and controlled
access through getters and setters.

• Example:

java

class Student {
private String name;

public String getName() { return name; }

public void setName(String name) { this.name = name; }


}

2. Inheritance
• Inheritance allows a class (subclass) to inherit fields and methods from another class (superclass),
promoting code reuse and method overriding.

• Example:
java

class Animal { void sound() { System.out.println("Animal sound"); } }

class Dog extends Animal { void sound() { System.out.println("Bark"); } }

3. Polymorphism

• Polymorphism enables one interface to be used for different data types. It can be implemented via
method overloading (compile-time) or method overriding (runtime).

• Example:

java

class Shape { void draw() { System.out.println("Drawing a shape"); } }


class Circle extends Shape { void draw() { System.out.println("Drawing a circle"); } }

4. Abstraction

• Abstraction hides the internal details and shows only essential features, achieved via abstract classes
or interfaces.

• Example:

java

abstract class Vehicle { abstract void move(); }

class Car extends Vehicle { void move() { System.out.println("Car is moving"); } }

6b )How would you clarify array and its types?

Arrays in Java

An array in Java is a collection of elements of the same data type stored in contiguous memory locations. It
allows you to group multiple values under a single variable name, making it easier to manage and
manipulate data. Each element in an array can be accessed using its index, which starts at 0.

Characteristics of Arrays:

• Fixed Size: The size of an array is defined when it is created and cannot be changed.
• Homogeneous Elements: All elements in an array must be of the same data type.
• Indexed Access: Elements can be accessed using an index, allowing efficient retrieval and
modification.

Types of Arrays

1. One-Dimensional Array (1D Array)


A one-dimensional array is essentially a list of elements of the same type, which can be visualized as a
single row of elements.

Declaration and Initialization:

• Syntax:

java

dataType[] arrayName = new dataType[size];

• Example:

java

int[] numbers = new int[5]; // Declares an array of integers with 5 elements


numbers[0] = 10; // Initializing elements
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Shorter Initialization: You can also declare and initialize in one line:

java

int[] numbers = {10, 20, 30, 40, 50};

Accessing Elements:

• Access an element using its index:

java

System.out.println(numbers[0]); // Outputs: 10

Example Program:

java

public class OneDimensionalArray {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50}; // Declaring and initializing
System.out.println("Elements in the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]); // Accessing elements
}
}
}

Use Cases:

• One-dimensional arrays are commonly used to store lists of items such as student scores, product
prices, or a list of names.

2. Two-Dimensional Array (2D Array)


A two-dimensional array is an array of arrays, which can be visualized as a table or a matrix with rows and
columns.

Declaration and Initialization:

• Syntax:

java

dataType[][] arrayName = new dataType[rows][columns];

Example Program: Here’s a complete program that declares a two-dimensional array, populates it
dynamically, and prints its elements:

java

public class TwoDimensionalArray {


public static void main(String[] args) {
// Declare a 2D array with 3 rows and 3 columns
int[][] array = new int[3][3];

// Populate the array with values


int value = 1; // Starting value
for (int i = 0; i < array.length; i++) { // Loop through rows
for (int j = 0; j < array[i].length; j++) { // Loop through columns
array[i][j] = value; // Assigning value to the
current element
value++; // Increment value for next
element
}
}

// Print the elements of the 2D array


System.out.println("Elements in the 2D array:");
for (int i = 0; i < array.length; i++) { // Loop through rows
for (int j = 0; j < array[i].length; j++) { // Loop through columns
System.out.print(array[i][j] + " "); // Print each element
}
System.out.println(); // New line for the next
row
}
}
}

Output

When you run the program, it will display:

Elements in the 2D array:


1 2 3
4 5 6
7 8 9

Explanation of the Code:

1. Array Declaration:
o A two-dimensional array array is declared with 3 rows and 3 columns using new
int[3][3].
2. Populating the Array:
o A variable value is initialized to 1 and is incremented for each element assigned in the nested
loops.
o The outer loop iterates through each row, while the inner loop iterates through each column,
filling the array with sequential values.
3. Printing the Array:
o Another set of nested loops is used to print the elements of the array, with formatting to keep
elements of the same row on the same line.

Use Cases:

• Two-dimensional arrays are used in applications such as representing game boards, performing
mathematical operations (like matrices), and managing tabular data.

Conclusion

Arrays are a fundamental data structure in Java that enable efficient data storage and retrieval.
Understanding one-dimensional and two-dimensional arrays is essential for managing collections of data
effectively in programming tasks. They provide a simple way to group data and perform operations like
iteration and access using indices.

7ai) Define constructor with an example

• constructors are special member functions that initialize the objects of a class.

• They have the same name as the class and are called automatically when an object is created.

• The role of a constructor is to provide initial values for the object and set up its state.

• Every class has a constructor. If no constructor is explicitly defined, the compiler provides a default
constructor.

• Constructors do not have a return type (not even void), and they cannot be abstract, static, final, or
synchronized.

Types of Constructors in Java:

1. Default Constructor (No-arg Constructor):


o This constructor takes no arguments and is used to initialize objects with default values.

o The compiler automatically creates it if no other constructors are defined in the class.

2. Parameterized Constructor:

o This constructor takes arguments and allows for setting custom values for object properties
when an object is created.

Example

class Rectangle {
double length;
double width;

// Default constructor
Rectangle() {
length = 1.0; // Default length
width = 1.0; // Default width
}

// Parameterized constructor
Rectangle(double l, double w) {
length = l; // Set the length
width = w; // Set the width
}

// Method to calculate area


double calculateArea() {
return length * width; // Area = length * width
}

// Method to display dimensions and area


void display() {
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + calculateArea());
}
}

public class Main {


public static void main(String[] args) {
// Creating a rectangle using the default constructor
Rectangle rect1 = new Rectangle();
System.out.println("Rectangle 1:");
rect1.display();

// Creating a rectangle using the parameterized constructor


Rectangle rect2 = new Rectangle(5.0, 3.0);
System.out.println("\nRectangle 2:");
rect2.display();
}
}
Output
Rectangle 1:
Length: 1.0
Width: 1.0
Area: 1.0

Rectangle 2:
Length: 5.0
Width: 3.0
Area: 15.0
7aii) How would you explain methods overloading with an example
Method Overloading in Java
Definition:
Method overloading is a feature in Java that allows a class to have more than one method with the same
name, but different parameter lists (either in the number of parameters, types of parameters, or both). It
improves code readability and reusability.
Key Points of Method Overloading:
• The method name remains the same, but the parameter list must differ in type, number, or both.
• Return type can be the same or different, but overloading is determined by the method signature
(name and parameters), not return type.

Syntax of Method Overloading:


class ClassName {
// Overloaded method with different number of parameters
returnType methodName(dataType param1) {
// method body
}

// Overloaded method with different parameter types


returnType methodName(dataType param1, dataType param2) {
// method body
}

// Overloaded method with different sequence of parameters


returnType methodName(dataType param1, differentDataType param2) {
// method body
}
}
Example
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


double add(double a, double b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();

// Call the add method with two integers


int sum1 = calc.add(10, 20);
System.out.println("Sum of two integers: " + sum1); // Output: 30

// Call the add method with three integers


int sum2 = calc.add(10, 20, 30);
System.out.println("Sum of three integers: " + sum2); // Output: 60

// Call the add method with two doubles


double sum3 = calc.add(10.5, 20.5);
System.out.println("Sum of two doubles: " + sum3); // Output: 31.0
}
}
Output
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 31.0
7 bi). Define inheritance and list of inheritance types with example

Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP) in Java. It allows
one class (the child or subclass) to inherit the fields and methods of another class (the parent or superclass).
Inheritance promotes code reusability and establishes a relationship between classes where the subclass can
extend or override the functionality of the superclass.
Types of Inheritance in Java
1. Single Inheritance: A subclass inherits from one superclass.
2. Multilevel Inheritance: A subclass is derived from another subclass.
3. Hierarchical Inheritance: Multiple subclasses inherit from the same superclass.
4. Multiple Inheritance (Through Interfaces): A class can implement multiple interfaces, but Java
does not support direct multiple inheritance through classes.
Types of Inheritance Explanation
1. Single Inheritance: One class derives from a single parent class.
o Example: Class Dog inherits from class Animal.
2. Multilevel Inheritance: A chain of inheritance where one class is derived from a class that is also
derived from another class.
o Example: Class Dog inherits from class Mammal, and class Mammal inherits from class
Animal.
3. Hierarchical Inheritance: Several classes inherit from the same parent class.
o Example: Classes Dog, Cat, and Bird all inherit from class Animal.
4. Multiple Inheritance (Through Interfaces): A class can implement multiple interfaces to inherit
from multiple sources.
o Example: Class Vehicle can implement both Flyable and Drivable interfaces.
o
Syntax(single Inheritance)
// Parent Class (Superclass)
class ParentClass {
// Parent class properties and methods
}

// Child Class (Subclass)


class ChildClass extends ParentClass {
// Child class properties and methods
}
Example of Single Inheritance
// Parent Class
class Animal {
String name = "Animal";

// Method in the parent class


void eat() {
System.out.println(name + " eats food.");
}
}

// Child Class
class Dog extends Animal {
String breed = "Golden Retriever";

// Method in the child class


void bark() {
System.out.println(breed + " barks.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Dog class
Dog myDog = new Dog();

// Call methods from both the parent and child class


myDog.eat(); // Inherited method from Animal class
myDog.bark(); // Method from Dog class
}
}

Output
Animal eats food.
Golden Retriever barks.
Conclusion
Inheritance in Java allows subclasses to inherit and utilize the properties and methods of their parent classes,
providing code reusability and the ability to extend or modify behavior as needed. In single inheritance, a
class inherits from one superclass, making the code cleaner and more maintainable.
7b ii) What is polymorphism explain with an example?
Polymorphism is a core concept of Object-Oriented Programming (OOP) in Java that allows methods to
perform different tasks based on the object that invokes them. It enables one interface to represent different
underlying forms (data types) and allows a single method to behave differently based on the object calling it.
Syntax of Polymorphism
class ClassName {
returnType methodName(parameterType1 param1) {
// Method body
}

returnType methodName(parameterType1 param1, parameterType2 param2) {


// Method body
}
}

Example
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two doubles


double add(double a, double b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();

// Calling overloaded methods


System.out.println("Sum of two integers: " + calc.add(10, 20)); // 30
System.out.println("Sum of three integers: " + calc.add(10, 20, 30)); // 60
System.out.println("Sum of two doubles: " + calc.add(10.5, 20.5)); // 31.0
}
}

Output
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 31.0
8a How would you summarize JVM and Bytecode in Java.
JVM
JVM acts as a run-time engine to run Java applications.
JVM is the one that actually calls the main method present in a Java code.
JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere).
This means a programmer can develop Java code on one
system and can expect it to run on any other Java-enabled
system without any adjustment. This is all possible
because of JVM.
When we compile a .java file, .class files(contains byte
code) with the same class names present in .java file are
generated by the Java compiler.
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment

Bytecode
Bytecode in Java is a set of instructions for the Java Virtual Machine.
Java Virtual Machine, abbreviated as JVM, enables a computer to run code written in Java.
When a Java program is compiled, the bytecode gets generated.
Bytecode is a platform-independent set of instructions and executed by the JVM.
Code that runs on multiple computer architectures without any modification is called platform
independent.
8b Explain java source file structure with an example program
Java source file structure
Java source file structure describes that the Java source code file must follow a schema or structure. In this
article, we will see some of the important guidelines that a Java program must follow.
A Java program has the following structure:
1) package statements: A package in Java is a mechanism to encapsulate a group of classes, sub-packages,
etc.
2) import statements: The import statement is used to import a package, class, or interface.
3) class definition: A class is a user-defined blueprint from which objects are created, and it is a passive
entity.
Example code

// 1. Package statement
package com.mycompany.myapp;

// 2. Import statements
import java.util.Scanner; // Importing the Scanner class from java.util package

// 3. Class definition
public class HelloWorld {

// Class constructor (optional)


public HelloWorld() {
// Constructor body
}

// Main method (entry point of the program)


public static void main(String[] args) {
// Creating an instance of Scanner class
Scanner input = new Scanner(System.in);

// Taking input from the user


System.out.print("Enter your name: ");
String name = input.nextLine();

// Printing a greeting message


System.out.println("Hello, " + name + "! Welcome to Java programming.");
}
}
Output

Enter your name: Bhavesh


Hello, Bhavesh! Welcome to Java programming.

You might also like