You are on page 1of 17

KLEF

Department of BES-1
23SC1203-CTOOD INSEM-1 EXAM ANSWER KEY
Date of Exam: 14-03-2024
A.C.Y:2023-24, Even Semester
General Instructions:
• Acknowledge that the suggested answer key is a sample solution and may not
be the only correct approach.
• Recognize and value the different problem-solving approaches and logic used
by students.
• Award marks based on correctness and alternative correct solutions
irrespective of adherence to the suggested key.

SECTION – A (2M)
1. A) Define the term “abstraction” in the context of OOP? [2M]
Abstraction is a process of hiding the implementation details or unnecessary details and showing
only functionality or necessary details to the user.
For example, a Shape class may have abstract methods like calculateArea() and
calculatePerimeter(), allowing specific shapes like Circle and Square to implement these methods
according to their unique properties, without exposing the internal calculations to the user.
1. B) Differentiate between static method and instance method in Java? [2M]

Criteri
Static Method Instance Method
a
Ownership Belongs to the class itself Belongs to instances of the class
Invocation Invoked using class name Invoked using object of the class
Can only access static Can access both static and instance
Access to Fields
variables variables
Allocated memory each time an
Memory Allocated memory once at
object is created
Allocation class loading

1. C) Define an array. How to declare an array in Java. [2M]


Array is a collection of elements of same type. For example, an int array contains integer elements
and a String array contains String elements. The elements of Array are stored in contiguous
locations in the memory.
dataType[] arrayName; // Syntax for declaring an array
int arr[] = new int[10]; // Declaring an array of integers with size 5

Page 1 of 17
1. D) Explain Singleton Class? [2M]
The singleton pattern restricts class instantiation to one object, achieved by a private constructor
preventing external instantiation. A static method returns the instance, creating it if necessary,
while a static variable holds the single instance.

1. E) Explain accessors and mutators in Java? [2M]


Accessor (Getter) methods get private variable values, allowing only reading to keep the object
safe. Mutator (Setters) methods change private variable values, allowing only writing to control
changes and protect the object.

Page 2 of 17
1. F) Describe the ‘extends’ keyword in Java and its role in inheritance. [2M]
In Java 'extends' keyword allows a subclass to be linked to a superclass and inherit its properties
and methods. It encourages the reuse of code and makes it easier to create specialized classes by
building upon pre-existing ones.

SECTION – B (4M)
2. A) Develop a Java Program that prompts the user to enter a three digits integer and
determines whether it is palindrome or not?

import java.util.Scanner;
class TwoA
{
public static void main(String[] args)
{

Scanner in = new Scanner(System.in);


int n = in.nextInt();
String s = ""+n;
if(s.length()!=3)
System.out.println("The integer shoud be of 3 digits");
else
{
int sum = 0;
int i = n;
while(i>0)
{
int r = i % 10;
sum = sum * 10 + r;
i = i / 10;
}
if(sum==n)
System.out.println("The given integer is a
Palindrome");
else
System.out.println("The given integer is not a
Palindrome");
}
}
}

2. B) Assume a class Book with the following attributes – ISBN (long), Title (String), Price
(double) with private access. Draw the class diagram and develop code. Write the accessor,
mutator methods and toString() method.

Page 3 of 17
class Book
{
long ISBN;
String Title;
double price;

long getISBN() {
return ISBN;
}

void setISBN(long i) {
ISBN = i;
}

String getTitle() {
return Title;
}

void setTitle(String t) {
Title = t;
}
double getPrice() {
return price;
}

public String toString() {


return "ISBN: " + ISBN + "\tTitle: " + Title + "\tPrice: " + price;
}
}
Page 4 of 17
2. C) Draw a class diagram modularized to package level and code the class Employee with ID,
name, designation, years of experience and salary as private attributes. Validate the years
of experience and salary using setter methods, Both are to be positive, else set to 0 and return
false. Code the toString() method. Code the main() method that instantiates 2 objects and
obtain the inputs through command line

class Employee
{
private String ID;
private String name;
private String designation;
private int experience;
private double salary;

void setID(String id)


{
ID = id;
}

void setName(String name)


{
this.name = name;
}

void setDesignation(String des)


{
designation = des;
}

boolean setExperience(int exp)


{
if(exp>0)
{
experience = exp;
return true;
Page 5 of 17
}
else
{
experience = 0;
return false;
}
}

boolean setSalary(double salary)


{
if(salary>0)
{
this.salary = salary;
return true;
}
else
{
this.salary = 0;
return false;
}
}
}

public class TwoC {


public static void main(String[] args)
{
if(args.length!=10)
System.out.println("Insufficient or excess number of parameters");
else
{
Employee e1 = new Employee();
e1.setID(args[0]);
e1.setName(args[1]);
e1.setDesignation(args[2]);
e1.setExperience(Integer.parseInt(args[3]));
e1.setSalary(Double.parseDouble(args[4]));
System.out.println(e1);

Employee e2 = new Employee();


e2.setID(args[0]);
e2.setName(args[1]);
e2.setDesignation(args[2]);
e2.setExperience(Integer.parseInt(args[3]));
e2.setSalary(Double.parseDouble(args[4]));
System.out.println(e2);
}
}
}

Page 6 of 17
2. D) Identify the output of the following code

public class Test


{
public static void main(String[] args)
{
new Person().printPerson();
new Student().printPerson();
}
}

class Student extends Person


{
private String getInfo()
{
return “Student”;
}
}

class Person
{
private String getInfo()
{
return “Person”;
}
public void printPerson()
{
System.out.println(getInfo());
}
}

Person
Person

SECTION-C (5M+6M)
3. A) An Armstrong number is a special kind of number in math. It’s a number that equals the
sum of its digits, each raised to a power. For example ,if you have a number like 153, its an
Armstrong number because 1^3+5^3+3^3 equals 153. Write a class Armstrong with 2 static
methods isArmstrong() to check whether a given number “n” is Armstrong or not and
displayArmstrong() to display all Armstrong numbers up to “n”. Access them using main()
method from the same class and use appropriate access specifiers?

package tgan;
import java.util.Scanner;
public class Armstrong {
private static int n;
private static boolean isArmstrong(int a) {
int s=0,temp=a,nd=(int)Math.log10(a)+1;
while(a>0) {
Page 7 of 17
s=s+(int)Math.pow(a%10, nd);
a=a/10;
}
if(s==temp)
return true;
return false;
}
private static void displayAllArmstrong() {
for(int i=1;i<=n;i++)
if(isArmstrong(i)==true)
System.out.println(i);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
displayAllArmstrong();
sc.close();
}
}

3. B) Develop a java program to print following pattern

*****
****
***
**
*

package tgan;
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j,s,n=sc.nextInt();
for(i=1;i<=n;i++)
{
for(s=1;s<=i-1;s++)
System.out.print(" ");
for(j=1;j<=n-i+1;j++)
System.out.print("*");
System.out.println();
}
}
}

(OR)
4. A) The task is to read the number of inches of type double, through console, then convert it to
centimeters and display the result . Modularize to class level , draw the class diagram, and
Page 8 of 17
develop the logic in a static function.(HINT: 1 INCH= 2.54 CENTIMETERS)

package co1;
import java.util.Scanner;
// Class responsible for conversion logic
class Converts
{
// Static function to convert inches to centimeters
public static double inchesToCentimeters(double inches) //Method
{
return inches * 2.54;
}
}

// Main class
public class MainDemo
{

public static void main(String[] x)


{
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of inches: ");


double inches = sc.nextDouble();

double centimeters = Converts.inchesToCentimeters(inches);//Calling StaticMethod using class


name

System.out.println(inches + " inches is equal to " + centimeters + " centimeters.");

sc.close(); // closing scanner class


}
}

4. B) Develop a Java Program to find and average of an array of integers

package p1;
import java.util.Scanner;
Page 9 of 17
public class Average {
public static void main(String[] x){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of Integers");
int n = sc.nextInt();

//Creating an array
int[] a = new int[n];

//Read numbers from user and store it in an array


System.out.println("Enter the Integers one by one : ");

for(int i =0; i<n; i++){


a[i] = sc.nextInt();
}

//Calculate the average


double avg = 0;
for(int i =0; i<n; i++){
avg = avg + a[i];
}

avg = avg/n;
System.out.println("Average of Given integers :: "+avg);
}
}

SECTION-D (5M+6M)
5. A) Draw class diagram for the following scenario-Develop a class Voter with ID, name, and
address as attributes. Address is a reference to Address class with city, state, country, and
pin code as attributes. Code the parameterized constructors, and toString() method in both
the classes. Develop the class VoterDemo with main () method to read details of Voter and
print in the following format: VOTER ID:12345, Name: ABC, Address-[City: Guntur,
State: Andhra Pradesh, Country: India, Pincode: 520078].

import java.util.Scanner;

class Voter {
private int id;
private String name;
private Address address;

public Voter(int id, String name, Address address) {


this.id = id;
this.name = name;
this.address = address;
}

Page 10 of 17
@Override
public String toString() {
return "VOTER ID: " + id + ", Name: " + name + ", Address-" + address;
}
}

class Address {
private String city;
private String state;
private String country;
private int pincode;

public Address(String city, String state, String country, int pincode) {


this.city = city;
this.state = state;
this.country = country;
this.pincode = pincode;
}

@Override
public String toString() {
return "[City: " + city + ", State: " + state + ", Country: " + country + ", Pincode:
" + pincode + "]";
}
}
public class EAVoterDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter voter ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter voter name: ");
String name = scanner.nextLine();
System.out.print("Enter city: ");
String city = scanner.nextLine();
System.out.print("Enter state: ");
String state = scanner.nextLine();
System.out.print("Enter country: ");
String country = scanner.nextLine();
System.out.print("Enter pincode: ");
int pincode = scanner.nextInt();
Address address = new Address(city, state, country, pincode);
Voter voter = new Voter(id, name, address);
System.out.println(voter);
scanner.close();
}

Page 11 of 17
5. B) Write a test program that prompts the user to enter 5 numbers, stores them in an array
list, and displays their sum.

import java.util.ArrayList;
import java.util.Scanner;
public class SumFromArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
// Prompt user for 5 numbers
for (int i = 0; i < 5; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers.add(scanner.nextInt());
}
scanner.close();
// Calculate the sum
int sum = 0;
for (int num : numbers) {
sum += num;
}
// Display the sum
System.out.println("The sum of the entered numbers is: " + sum);
}
}

(OR)
6. A) Draw the Class Diagram and code the class Mobile with following private attributes: model,
brand, warranty(type int) and price(type double). Code the accessors, mutators and
toString() method. Develop the main() method to test the functionality of the class

Page 12 of 17
Class Diagram ---------- 2 marks

<< +Mobile>>
-model:String
-brand:String
-warrenty:int
-price:double

~Mobile(String:m,String:b,int:w,double:p)
+getModel():string
+setModel(String:m):void

+getBrand():string
+setBrand(String:m):void

+getWarrenty():int
+setWarrenty(int:m):void

+getprice():double
+setprice(double:m):void
+toString(void):String

+main(String args[]):void

Code ------- 3marks

package p1;
public class Mobile {

private String model;


private String brand;
private int warrenty;
private double price;

public String getModel() {


return model;
}
public void setModel(String model) {
this.model = model;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
Page 13 of 17
}
public int getWarrenty() {
return warrenty;
}
public void setWarrenty(int warrenty) {
this.warrenty = warrenty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}

Mobile(String m,String b,int w,double p)


{
setModel(m);
setBrand(b);
setWarrenty(w);
setPrice(p);

}
public String toString()
{
return getModel()+" "+getBrand()+" "+getWarrenty()+" "+getPrice();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Mobile m1=new Mobile("narzo50","realme",2,20000);
Mobile m2=new Mobile("iphone14","Apple",2,100000);
System.out.println(m1);
System.out.println(m2);
}

6. B) Explain Polymorphism. Compare and contrast method overloading and method overriding
with examples

6marks

Polymorphism is considered one of the important features of Object-Oriented Programming.


Polymorphism allows us to perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have multiple implementations. The word
“poly” means many and “morphs” means forms, So many forms.

Polymorphism is mainly divided into two types:


Compile-time Polymorphism(function overloading )

Page 14 of 17
Runtime Polymorphism( function overriding)

there are multiple functions with the same name but different parameters then these functions are
said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and
a change in the type of arguments.
The differences between Method Overloading and Method Overriding in Java are as follows:

Method Overloading Method Overriding

Method overloading is a compile-time


Method overriding is a run-time polymorphism.
polymorphism.

Method overriding is used to grant the specific


Method overloading helps to increase the
implementation of the method which is already
readability of the program.
provided by its parent class or superclass.

It is performed in two classes with inheritance


It occurs within the class.
relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.

In method overloading, methods must


In method overriding, methods must have the
have the same name and different
same name and same signature.
signatures.

In method overloading, the return type


In method overriding, the return type must be the
can or can not be the same, but we just
same or co-variant.
have to change the parameter.

Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.

It gives better performance. The reason behind


Poor Performance due to compile time
this is that the binding of overridden methods is
polymorphism.
being done at runtime.

Private and final methods can be


Private and final methods can’t be overridden.
overloaded.

The argument list should be different The argument list should be the same in method
while doing method overloading. overriding.

Page 15 of 17
Ex
package p1;
//function overloading example
public class funover {

public static void main(String[] args) {


// TODO Auto-generated method stub
funover ob =new funover();
ob.add(12);;
ob.add(10, 20);
ob.add(10,30);
}

public void add(int a,int b,int c)


{
System.out.println(a+b+c);
}
public void add(int a)
{
System.out.println(a+10);

}
public void add(int a,int b)
{
System.out.println(a+b);
}

Method overriding
In Java, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent classes.
When a method in a subclass has the same name, the same parameters or signature, and the same
return type(or sub-type) as a method in its super-class, then the method in the subclass is said
to override the method in the super-class.

Ex

//Function overriding
package function_overriding;
class A
{
public void FunA()
{
System.out.println("A");
}
}
public class B extends A{

Page 16 of 17
public void FunA()
{

System.out.println("B");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
B b = new B();
b.FunA();

Page 17 of 17

You might also like