0% found this document useful (0 votes)
163 views22 pages

Scheme - Updated - CIE 1-QP BCS306A SET2

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)
163 views22 pages

Scheme - Updated - CIE 1-QP BCS306A SET2

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

USN

RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT


(Affiliated to Visvesvaraya Technological University, Belagavi & Approved by AICTE, New Delhi)
Chaitanya Layout, JP Nagar 8th Phase, Kothanur, Bengaluru-560076
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CONTINUOUS INTERNAL EVALUATION -I


SCHEME - 2022
Course Title: Object Oriented Programming with JAVA Course Code: BCS306A
Duration: 90 Min. Semester: III Section: A/B/C Date: 9/10/24
Faculty In-charge: Dr SAU, Dr NB & Dr RS Max. Marks: 50

 ANSWER ALL THE QUESTIONS

Q. Marks Level CO PO
No.
Explain array declaration and initialization in Java with
example program.
In Java, an array is a data structure that can store multiple
values of the same type. Arrays in Java are objects, and they
can be declared and initialized in several ways. Let's explore
the steps involved in array declaration and initialization along
with an example program.

1. Array Declaration:
To declare an array, you specify the data type followed by
square brackets []. The syntax is:
dataType[] arrayName;
dataType: This defines the type of elements the array will store
(e.g., int, double, String, etc.).
Q.1 a 6 L2 CO1 1,2,3
arrayName: This is the name of the array
2. Array Initialization:
There are two common ways to initialize an array in Java:

Method 1: Using new Keyword with Size: The size of the array
is specified when you create it using the new keyword.
arrayName = new dataType[size];
numbers = new int[5]; // Initializes an array of size 5

Method 2: Inline Initialization with Values: You can initialize


the array with predefined values directly.
dataType[] arrayName = {value1, value2, value3, ...};
int[] numbers = {1, 2, 3, 4, 5}; // Declares and initializes an
array
Justify “compile once and run anywhere” in Java.
The slogan “Compile Once, Run Anywhere” (CORA) is one
of the core strengths of the Java programming language. This
principle is achieved through the use of bytecode and the Java
Virtual Machine (JVM), making Java platform-independent.
b 4 L1 CO1 1,2,3
How It Works:
Source Code Compilation:

When you write a Java program, it is written in human-


readable source code using .java files.

Page 1 of 22
This source code is then compiled by the Java compiler (javac)
into an intermediate form known as bytecode. The bytecode is
stored in .class files.
Bytecode:

Bytecode is not machine-specific; instead, it is a highly


optimized set of instructions that can be executed on any
machine that has a JVM.
Unlike other programming languages that compile directly
into machine code (which is platform-dependent), Java
compiles into bytecode, which is platform-independent.
Java Virtual Machine (JVM):

The JVM acts as an interpreter between the bytecode and the


machine's native operating system.
Java bytecode can be executed on any platform (Windows,
Linux, Mac OS, etc.) that has the appropriate JVM installed.
The JVM translates the bytecode into machine-specific
instructions at runtime, making Java programs portable across
different operating systems without the need for modification
or recompilation.
Portability:

Due to the bytecode-JVM mechanism, Java achieves its write


once, run anywhere philosophy, meaning:
You compile your Java program once, and the same compiled
.class files (bytecode) can be run on any device or operating
system that supports the JVM.
There is no need to recompile your code for different
platforms.
OR
Detail on the basic structure of a class along with a sample
program.
In Java, a class is a blueprint for creating objects. It
encapsulates data for the object and methods to manipulate
that data. The basic structure of a class includes the following
components:

Access Modifier: Defines the visibility of the class (e.g.,


public, private, protected).
Q.2 a Class Keyword: The class keyword is used to declare a class. 6 L2 CO1 1,2,3
Class Name: The name of the class should start with an
uppercase letter and follow the CamelCase naming
convention.
Attributes (Fields/Variables): These are the data members of
the class that hold the state of an object.
Methods: Functions defined within the class that operate on
the data. They define the behavior of the class.
Constructor: A special method that is called when an object is
instantiated. It initializes the object's attributes.
Explain the principles of object-oriented programming.
b 4 L1 CO1 1,2,3
Encapsulation

Page 2 of 22
Definition: Encapsulation is the mechanism of bundling the
data (variables) and the methods (functions) that operate on
the data into a single unit or class. It also restricts direct
access to some of the object’s components, which is a means
of preventing unintended interference and misuse.
Abstraction
Definition: Abstraction is the process of hiding the
implementation details from the user and exposing only the
essential features. In Java, abstraction is achieved using
abstract classes or interfaces.
Inheritance
Definition: Inheritance is a mechanism where one class
(child/subclass) inherits the properties and behavior (fields
and methods) of another class (parent/superclass). This
promotes code reuse and helps maintain a hierarchical class
structure.
Polymorphism
Definition: Polymorphism allows one interface to be used for
a general class of actions. In Java, polymorphism can be
implemented via method overloading (compile-time) or
method overriding (runtime). The same method can perform
different tasks based on the object calling it.

Write a Java program to sum only first five elements of the


array using for each loop.
public class SumFirstFiveElements {
public static void main(String[] args) {
// Initialize an array with some elements
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Variable to store the sum


int sum = 0;

// Counter to track the number of elements processed


int count = 0;

// For-each loop to iterate through the array


for (int num : numbers) {
Q.3 a 6 L3 CO2 1,2,3
if (count < 5) { // Sum only the first 5 elements
sum += num;
count++;
} else {
break; // Exit the loop once 5 elements are summed
}
}

// Output the result


System.out.println("Sum of the first 5 elements: " + sum);
}
}

Output:
Sum of the first 5 elements: 15

Page 3 of 22
Explain static keyword with respect to class and methods.
In Java, the static keyword is used to indicate that a particular
member (variable or method) belongs to the class itself rather
than to instances of the class (objects). This means that static
members can be accessed without creating an instance of the
class. The static keyword can be applied to variables, methods,
blocks, and nested classes.

1. Static Variables
Definition: Static variables are also known as class variables.
They are shared among all instances of the class. When one
instance modifies a static variable, the change is reflected
across all instances.
Usage: Static variables are typically used for constants or
shared data.
class Counter {
// Static variable
static int count = 0;

// Constructor
Counter() {
count++; // Increment count for each new instance
b 4 L2 CO2 1,2,3
}

// Method to display count


static void displayCount() {
System.out.println("Number of objects created: " +
count);
}
}

class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// Accessing static method without creating an instance


Counter.displayCount(); // Output: Number of objects
created: 3
}
}
Output:
Number of objects created: 3
OR
Write a Java program to sum elements of two 2D array using
for each loop.
public class SumOfTwo2DArrays {
public static void main(String[] args) {
Q.4 a // Initialize two 2D arrays 6 L3 CO2 1,2,3
int[][] array1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
Page 4 of 22
};

int[][] array2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

// Array to store the sum of corresponding elements


int[][] sumArray = new int[3][3];

// Sum corresponding elements of the two arrays


int row = 0;
for (int[] arr1Row : array1) {
int col = 0;
for (int element1 : arr1Row) {
sumArray[row][col] = element1 + array2[row][col];
col++;
}
row++;
}

// Display the sumArray


System.out.println("Sum of elements of the two 2D
arrays:");
for (int[] rowSum : sumArray) {
for (int elementSum : rowSum) {
System.out.print(elementSum + " ");
}
System.out.println();
}
}
}
Output:
Sum of elements of the two 2D arrays:
10 10 10
10 10 10
10 10 10
Explain public and private access specifiers with respect to
class.
In Java, access specifiers (also known as access modifiers)
control the visibility and accessibility of classes, methods,
and variables. The two most commonly used access
specifiers are public and private. Understanding these access
specifiers is crucial for encapsulation, which is one of the
core principles of object-oriented programming.
b 4 L2 CO2 1,2,3
1. Public Access Specifier
Definition: The public access specifier allows the class,
method, or variable to be accessed from any other class in
any package.
Use Case: It is typically used for methods and variables that
should be accessible to all classes, such as API methods or
utility functions.
Page 5 of 22
// Public class
public class PublicExample {
// Public variable
public String name;

// Public constructor
public PublicExample(String name) {
this.name = name;
}

// Public method
public void display() {
System.out.println("Name: " + name);
}
}

// Another class to test access


class Main {
public static void main(String[] args) {
PublicExample obj = new PublicExample("Alice");
obj.display(); // Accessing public method
}
}
Output:
Name: Alice

Private Access Specifier


Definition: The private access specifier restricts the visibility
of the class members (variables and methods) to the class
itself. They cannot be accessed from any other class, not even
subclasses.
Use Case: It is used for variables and methods that are
intended to be hidden from outside access to maintain data
integrity and encapsulation.
// Class with private members
class PrivateExample {
// Private variable
private String secret;

// Constructor to initialize private variable


public PrivateExample(String secret) {
this.secret = secret;
}

// Public method to access the private variable


public void revealSecret() {
System.out.println("Secret: " + secret);
}
}

// Another class to test access


class Main {
public static void main(String[] args) {

Page 6 of 22
PrivateExample obj = new PrivateExample("Hidden
Treasure");

// obj.secret = "New Secret"; // This would cause a


compilation error

// Accessing private variable via public method


obj.revealSecret(); // Valid access through public
method
}
}

Output:
Secret: Hidden Treasure

Explain run time polymorphism providing appropriate


examples.
Run-time polymorphism, also known as dynamic method
dispatch, is a feature in Java that allows a method to perform
different functions based on the object that it is acting upon.
This is achieved through method overriding, where a
subclass provides a specific implementation of a method that
is already defined in its superclass. The decision about which
method to invoke is made at runtime, hence the name "run-
time polymorphism."

Key Concepts
Method Overriding: This occurs when a subclass provides a
specific implementation for a method that is already defined
in its superclass.

Dynamic Method Dispatch: Java uses this mechanism to


determine which overridden method to call at runtime, based
on the object type (not the reference type).
Q.5 a // Superclass 6 L3 CO3 1,2,3
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass Dog
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}

// Subclass Cat
class Cat extends Animal {
@Override
public void sound() {
Page 7 of 22
System.out.println("Cat meows");
}
}

// Main class to demonstrate run-time polymorphism


public class Main {
public static void main(String[] args) {
// Creating objects of the subclasses
Animal myDog = new Dog();
Animal myCat = new Cat();

// Calling the overridden method


myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows

// Using an array of Animal references


Animal[] animals = { new Dog(), new Cat() };

// Calling the overridden method in a loop


for (Animal animal : animals) {
animal.sound();
}
}
}
Output:
Dog barks
Cat meows
Dog barks
Cat meows
Write a Java class program which includes an overloaded
function additions () which calculates sum of numbers with
different data type.
public class AdditionOverload {

// Overloaded method 1: Adds two integers


public int additions(int a, int b) {
return a + b;
}

// Overloaded method 2: Adds three integers


public int additions(int a, int b, int c) {
b return a + b + c; 4 L2 CO3 1,2,3
}

// Overloaded method 3: Adds two double values


public double additions(double a, double b) {
return a + b;
}

// Overloaded method 4: Adds three double values


public double additions(double a, double b, double c) {
return a + b + c;
}

Page 8 of 22
// Overloaded method 5: Adds an integer and a double
public double additions(int a, double b) {
return a + b;
}

// Overloaded method 6: Adds a double and an integer


public double additions(double a, int b) {
return a + b;
}

public static void main(String[] args) {


// Create an object of the class
AdditionOverload obj = new AdditionOverload();

// Test different overloaded methods


System.out.println("Sum of two integers (3, 5): " +
obj.additions(3, 5));
System.out.println("Sum of three integers (1, 2, 3): " +
obj.additions(1, 2, 3));
System.out.println("Sum of two doubles (2.5, 3.7): " +
obj.additions(2.5, 3.7));
System.out.println("Sum of three doubles (1.1, 2.2, 3.3):
" + obj.additions(1.1, 2.2, 3.3));
System.out.println("Sum of int and double (4, 2.5): " +
obj.additions(4, 2.5));
System.out.println("Sum of double and int (1.2, 4): " +
obj.additions(1.2, 4));
}
}
Output:
Sum of two integers (3, 5): 8
Sum of three integers (1, 2, 3): 6
Sum of two doubles (2.5, 3.7): 6.2
Sum of three doubles (1.1, 2.2, 3.3): 6.6
Sum of int and double (4, 2.5): 6.5
Sum of double and int (1.2, 4): 5.2
OR
Write a program to create a class employee with members
name dept, gross salary, basics salary and a method Calculate
Salary () which calculates the total salary using the sum of
above two salary components. Use constructors and this
pointer to set the initial values of the members.
class Employee {
// Data members
String name;
Q.6 a 6 L3 CO3 1,2,3
String dept;
double grossSalary;
double basicSalary;

// Constructor to initialize the data members using this


pointer
public Employee(String name, String dept, double
grossSalary, double basicSalary) {

Page 9 of 22
this.name = name; // Assign the name using 'this'
pointer
this.dept = dept; // Assign the department using
'this' pointer
this.grossSalary = grossSalary; // Assign gross salary
using 'this' pointer
this.basicSalary = basicSalary; // Assign basic salary
using 'this' pointer
}

// Method to calculate the total salary


public double calculateSalary() {
return this.grossSalary + this.basicSalary; // Sum of gross
and basic salary
}

// Method to display employee details


public void displayEmployeeDetails() {
System.out.println("Employee Name: " + this.name);
System.out.println("Department: " + this.dept);
System.out.println("Basic Salary: " + this.basicSalary);
System.out.println("Gross Salary: " + this.grossSalary);
System.out.println("Total Salary: " +
this.calculateSalary());
}

public static void main(String[] args) {


// Create Employee object using the constructor
Employee emp1 = new Employee("John Smith", "IT",
5000.0, 2500.0);

// Display employee details and total salary


emp1.displayEmployeeDetails();
}
}
Output:
Employee Name: John Smith
Department: IT
Basic Salary: 2500.0
Gross Salary: 5000.0
Total Salary: 7500.0
Explain this keyword with respect to objects.
The this Keyword in Java
In Java, the this keyword is a reference variable that refers to
the current object—the object whose method or constructor is
being called. It is commonly used within instance methods
and constructors to differentiate between class attributes
b 4 L2 CO3 1,2,3
(instance variables) and parameters or to pass the current
object as an argument.

Key Uses of this Keyword


Distinguishing Instance Variables from Parameters: When
instance variables have the same name as parameters in a

Page 10 of 22
constructor or method, this helps to clarify which is being
referred to.

Invoking Other Constructors: this can be used to call another


constructor in the same class, a process known as constructor
chaining.

Passing the Current Object: It can be passed as an argument


to other methods or constructors.

Returning the Current Object: this can be returned from a


method to allow method chaining.
class Rectangle {
// Instance variables
private int length;
private int width;

// Constructor
public Rectangle(int length, int width) {
// Using 'this' to distinguish between instance variables
and parameters
this.length = length;
this.width = width;
}

// Method to calculate the area of the rectangle


public int calculateArea() {
return this.length * this.width; // Using 'this' to refer to
instance variables
}

// Method to return the current object


public Rectangle getSelf() {
return this; // Returning the current object
}

public static void main(String[] args) {


Rectangle rect = new Rectangle(10, 5); // Creating a
Rectangle object
System.out.println("Area of rectangle: " +
rect.calculateArea());

// Using the getSelf method


Rectangle anotherRect = rect.getSelf();
System.out.println("Another rectangle area: " +
anotherRect.calculateArea());
}
}

Output:
Area of rectangle: 50
Another rectangle area: 50

Page 11 of 22
How are constructors executed in multilevel inheritance.
Explain briefly about it.
In multilevel inheritance, where a class inherits from a
derived class, which in turn inherits from another base class,
the execution of constructors follows a specific order. When
an object of the most derived class is created, the
constructors are executed in a top-down approach, starting
from the base class down to the most derived class.

Execution Order of Constructors


Base Class Constructor: The constructor of the base class
(the top-level class) is called first.
Intermediate Class Constructor: After the base class
constructor completes execution, the constructor of the
immediate derived class is called.
Most Derived Class Constructor: Finally, the constructor of
the most derived class (the class being instantiated) is
executed.
// Base class
class Animal {
// Constructor of Animal class
public Animal() {
System.out.println("Animal constructor called");
}
}

Q.7 a // Intermediate class 6 L3 CO2 1,2,3


class Mammal extends Animal {
// Constructor of Mammal class
public Mammal() {
System.out.println("Mammal constructor called");
}
}

// Derived class
class Dog extends Mammal {
// Constructor of Dog class
public Dog() {
System.out.println("Dog constructor called");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
// Create an instance of Dog
Dog dog = new Dog();
}
}

Output:
Animal constructor called
Mammal constructor called
Dog constructor called
b Where is the ‘super ‘method used? Explain with example. 4 L2 CO2 1,2,3
Page 12 of 22
The super keyword in Java is used to refer to the immediate
parent class of a class. It is primarily used in three main
scenarios:

To call the parent class constructor.


To access parent class methods.
To access parent class fields.
Using super to Call Parent Class Constructor
When a subclass is instantiated, the constructor of the parent
class is called first. If you want to explicitly call a parent class
constructor from a subclass constructor, you can use the super
keyword.
// Base class
class Animal {
String name;

// Constructor of Animal class


public Animal(String name) {
this.name = name;
System.out.println("Animal name: " + name);
}
}

// Derived class
class Dog extends Animal {
int age;

// Constructor of Dog class


public Dog(String name, int age) {
// Call the constructor of the parent class (Animal)
super(name); // This invokes the Animal constructor
this.age = age;
System.out.println("Dog age: " + age);
}

// Method to display dog details


public void display() {
System.out.println("Dog Name: " + name + ", Age: " +
age);
}
}

public class SuperKeywordExample {


public static void main(String[] args) {
// Create an instance of Dog
Dog dog = new Dog("Buddy", 3);

// Display dog details


dog.display();
}
}

Output:
Animal name: Buddy
Page 13 of 22
Dog age: 3
Dog Name: Buddy, Age: 3
OR
With an example explain Multi level Inheritance.
Multi-level inheritance is a type of inheritance in Java where
a class is derived from a class that is also derived from another
class. In this hierarchy, each class inherits the properties and
methods of its parent class, and the chain continues up to the
base class.

In simpler terms, class A serves as the base class, class B


inherits from class A, and class C inherits from class B,
forming a chain of inheritance.

Example of Multi-Level Inheritance:


In the following example, we'll create three classes:

Class Animal: The base class.


Class Mammal: Inherits from Animal.
Class Dog: Inherits from Mammal.

// Base class
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
Q.8 a 6 L3 CO2 1,2,3
// Derived class inheriting from Animal
class Mammal extends Animal {
public void walk() {
System.out.println("This mammal walks on four legs.");
}
}

// Further derived class inheriting from Mammal


class Dog extends Mammal {
public void bark() {
System.out.println("The dog barks loudly.");
}
}

public class MultiLevelInheritanceDemo {


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

// Calling methods from different levels of inheritance


dog.eat(); // Method inherited from Animal class
dog.walk(); // Method inherited from Mammal class
dog.bark(); // Method from Dog class
}
}

Page 14 of 22
Output:
This animal eats food.
This mammal walks on four legs.
The dog barks loudly.

What are constructors used for? Explain constructors with


proper example.

In Java, constructors are special methods used to initialize


objects when they are created. A constructor is called when an
instance of a class is created and typically used to set the initial
state of an object by assigning values to its fields.

Key Features of Constructors:

Same Name as the Class: A constructor always has the same


name as the class.

No Return Type: Unlike other methods, constructors do not


have a return type, not even void.

Called Automatically: They are invoked automatically when


an object of a class is created using the new keyword.

Types of Constructors:

Default Constructor: A no-argument constructor that Java


provides automatically if no constructors are defined.
b 4 L3 CO2 1,2,3
Parameterized Constructor: A constructor that accepts
parameters to initialize an object with specific values.

class Student {
String name;
int rollNumber;

// Default constructor
public Student() {
name = "Unknown";
rollNumber = 0;
}

public void displayDetails() {


System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}

public static void main(String[] args) {


// Creating an object using the default constructor
Student student1 = new Student();

// Displaying the details of student1


Page 15 of 22
student1.displayDetails();
}
}

Ouput:
Name: Unknown
Roll Number: 0

Develop a JAVA program to create a class named shape.


Create three sub classes namely: circle, triangle and square,
each class has two member functions named draw () and erase
().Use the concept of method overriding.

// Base class named Shape


class Shape {
// Method to draw the shape
public void draw() {
System.out.println("Drawing a shape");
}

// Method to erase the shape


public void erase() {
System.out.println("Erasing a shape");
}
}

// Subclass Circle that extends Shape


class Circle extends Shape {
// Overriding draw method
@Override
Q.9 a public void draw() { 6 L3 CO4 1,2,3,4
System.out.println("Drawing a Circle");
}

// Overriding erase method


@Override
public void erase() {
System.out.println("Erasing a Circle");
}
}

// Subclass Triangle that extends Shape


class Triangle extends Shape {
// Overriding draw method
@Override
public void draw() {
System.out.println("Drawing a Triangle");
}

// Overriding erase method


@Override
public void erase() {
System.out.println("Erasing a Triangle");

Page 16 of 22
}
}

// Subclass Square that extends Shape


class Square extends Shape {
// Overriding draw method
@Override
public void draw() {
System.out.println("Drawing a Square");
}

// Overriding erase method


@Override
public void erase() {
System.out.println("Erasing a Square");
}
}

public class Main {


public static void main(String[] args) {
// Creating Shape objects and demonstrating method
overriding
Shape shape1 = new Circle(); // Polymorphism: Shape
reference to Circle object
shape1.draw();
shape1.erase();

Shape shape2 = new Triangle(); // Polymorphism: Shape


reference to Triangle object
shape2.draw();
shape2.erase();

Shape shape3 = new Square(); // Polymorphism: Shape


reference to Square object
shape3.draw();
shape3.erase();
}
}
Output:
Drawing a Circle
Erasing a Circle
Drawing a Triangle
Erasing a Triangle
Drawing a Square
Erasing a Square
class EvenOddCheck {
public String checkEvenOdd(int num) {
if (num % 2 = 0) {
return "Even";
b } else { 4 L3 CO4 1,2,3,4
return "Odd";
}}
public static void main(String[] args) {
int number = 23;
Page 17 of 22
EvenOddCheck obj = new EvenOddCheck;
String result = obj.checkEvenOdd(number);
System.out.println("The number is " result);
} Debug the code for logical and syntax errors. Correct the
code so it properly checks if the number is even or odd, and
prints the result.

Sol:
Original Errors:
 In the if statement, num % 2 = 0 should be num % 2
== 0. The = operator is for assignment, while == is for
comparison.
 In the main() method, the object new EvenOddCheck
is missing parentheses. It should be new
EvenOddCheck().
 When printing the result, the + operator is missing
between the string and result in System.out.println().

class EvenOddCheck {
// Method to check if the number is even or odd
public String checkEvenOdd(int num) {
if (num % 2 == 0) { // Corrected comparison
operator
return "Even";
} else {
return "Odd";
}
}

public static void main(String[] args) {


int number = 23;
// Corrected object instantiation with parentheses
EvenOddCheck obj = new EvenOddCheck();

// Get the result from the method


String result = obj.checkEvenOdd(number);

// Corrected the print statement with the + operator


to concatenate
System.out.println("The number is " + result);
}
}

Output:
The number is Odd
OR
Write a Java program to create a class called Student that has
Q.10 a attributes for the student's name, roll number, and marks in
three subjects. The class should include methods to calculate 6 L3 CO4 1,2,3,4

Page 18 of 22
the total marks and the average marks of the student. Use
constructors to initialize the values of the attributes.
Additionally, create an array of Student objects and display the
details of each student along with their total and average
marks.

// Student class definition


class Student {
// Attributes of the Student class
private String name;
private int rollNumber;
private int marks1, marks2, marks3;

// Constructor to initialize student details


public Student(String name, int rollNumber, int marks1, int
marks2, int marks3) {
this.name = name;
this.rollNumber = rollNumber;
this.marks1 = marks1;
this.marks2 = marks2;
this.marks3 = marks3;
}

// Method to calculate total marks


public int calculateTotalMarks() {
return marks1 + marks2 + marks3;
}

// Method to calculate average marks


public double calculateAverageMarks() {
return calculateTotalMarks() / 3.0;
}

// Method to display student details


public void displayStudentDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks1: " + marks1);
System.out.println("Marks2: " + marks2);
System.out.println("Marks3: " + marks3);
System.out.println("Total Marks: " +
calculateTotalMarks());
System.out.println("Average Marks: " +
calculateAverageMarks());
System.out.println("-------------------------------");
}
}

// Main class to demonstrate the Student class functionality


public class StudentTest {
public static void main(String[] args) {
// Create an array of Student objects
Student[] students = new Student[3];

Page 19 of 22
// Initializing Student objects
students[0] = new Student("Alice", 101, 85, 90, 88);
students[1] = new Student("Bob", 102, 75, 80, 78);
students[2] = new Student("Charlie", 103, 95, 92, 89);

// Displaying the details of each student


for (Student student : students) {
student.displayStudentDetails();
}
}
}

Output:
Student Name: Alice
Roll Number: 101
Marks1: 85
Marks2: 90
Marks3: 88
Total Marks: 263
Average Marks: 87.66666666666667
-------------------------------
Student Name: Bob
Roll Number: 102
Marks1: 75
Marks2: 80
Marks3: 78
Total Marks: 233
Average Marks: 77.66666666666667
-------------------------------
Student Name: Charlie
Roll Number: 103
Marks1: 95
Marks2: 92
Marks3: 89
Total Marks: 276
Average Marks: 92.0
-------------------------------
class Rectangle {
public int calculateArea(int length) {
int area = length * width;
return;
}
public static void main(String[] args) {
int length = 10;
int width = 5;
b Rectangle rect; 4 L3 CO4 1,2,3,4
int result = calculateArea(length, width);

System.out.println("Area of rectangle: " result);


}
}
Identify the logical and syntax errors. Correct the program so
it calculates the area of the rectangle and prints it correctly.

Page 20 of 22
Solution:
Errors in the Code:
 Logical Error in calculateArea method:
 The method takes only one argument length, but
inside the method, it tries to use an undefined
variable width. It should also accept width as a
parameter.
 The return statement is incorrect, as no value is
being returned. It should return the area.
 Syntax Error in main method:
 The calculateArea method is being called
without creating an object of the Rectangle
class.
 The result is being printed incorrectly. There
should be a + sign to concatenate the string
and the result in System.out.println.
 Returning the result:
 The calculateArea method should return the
computed area.

class Rectangle {
// Method to calculate area of the rectangle
public int calculateArea(int length, int width) {
int area = length * width;
return area; // Return the computed area
}

public static void main(String[] args) {


// Local variables to hold length and width of the
rectangle
int length = 10;
int width = 5;

// Creating an object of the Rectangle class


Rectangle rect = new Rectangle();

// Calling the calculateArea method using the object


int result = rect.calculateArea(length, width);

// Printing the area of the rectangle


System.out.println("Area of rectangle: " + result);
}
}

Output:
Area of rectangle: 50

CO1 Understand the object-oriented concepts through java programming language.


CO2 Apply knowledge of java constructs for developing different program application
CO3 Analyze the given java program to solve specific software problem.
Page 21 of 22
CO4 Proficiency in implementing, compiling, testing and debugging Java program

Page 22 of 22

You might also like