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

CTOOD

The document contains solutions to coding questions involving Java programming concepts like: 1. Writing a method to check if an integer is even or odd using the modulo (%) operator and incorporating it into a program that takes user input and prints the results. 2. Using conditionals like if-else to check ranges of even/odd integers and print appropriate messages. 3. Defining a Cuboid class with properties like length, breadth, height and a volume calculation method, then creating objects and printing volumes. 4. Explaining arrays in Java including declaration, types (one and multi-dimensional), and accessing elements. 5. Creating a SavingsAccount class with static interest rate and instance balance variables,

Uploaded by

DHARAM TEJ D
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)
84 views

CTOOD

The document contains solutions to coding questions involving Java programming concepts like: 1. Writing a method to check if an integer is even or odd using the modulo (%) operator and incorporating it into a program that takes user input and prints the results. 2. Using conditionals like if-else to check ranges of even/odd integers and print appropriate messages. 3. Defining a Cuboid class with properties like length, breadth, height and a volume calculation method, then creating objects and printing volumes. 4. Explaining arrays in Java including declaration, types (one and multi-dimensional), and accessing elements. 5. Creating a SavingsAccount class with static interest rate and instance balance variables,

Uploaded by

DHARAM TEJ D
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

CTOOD SEM-IN 1 SOLUTION

Q1. Write a method isEven() that uses the remainder operator (%) to determine
whether an integer is even.The method should take an integer argument and return
true if the integer is even and false otherwise.1ncorporate this method into an
application that inputs a sequence of integers (one at a time) and determines whether
cach is even or odd.

import java.util.Scanner;

public class EvenOddChecker {


public static boolean isEven(int num) {
return num % 2 == 0;
}

public static void main(String[] args) {


Scanner input = new Scanner(System.in);

while (true) {
System.out.print("Enter an integer (or 'q' to quit): ");
if (input.hasNextInt()) {
int num = input.nextInt();
System.out.println(num + " is " + (isEven(num) ? "even" : "odd"));
} else {
String quit = input.next();
if (quit.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
break;
} else {
System.out.println("Invalid input, please try again.");
}
}
}

input.close();
}
}

CTOOD SEM-IN 1 SOLUTION 1


Q2. Given an integer, perform the following conditional actions: If is odd, print Weird. If
is even and in the inclusive range of to, print NotWeird. If is even and in the inclusive
range of to ,print Weird If is even and greater than, print NotWeird Complete the stub
code to print whether or not is weird.

public class Solution {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if(n%2==0)
{
if(n>=2 && n<=5)
{
System.out.println("Not Weird");
}
else if(n>=6 && n<=20)
{
System.out.println("Weird");
}
else
System.out.println("Not Weird");
}
else
System.out.println("Weird");

scanner.close();
}
}

Q3. Create a Cuboid class with 3 public instance variables length, breadth and height
of type double,and a method volume (0. Create choice 2 objects with different values
obtained by command line arguments andprint the volume ofeach. (The program must
take 6 values asinput).

import java.util.Scanner;
public class Cuboid {

CTOOD SEM-IN 1 SOLUTION 2


private double length;
private double breadth;
private double height;
public Cuboid(double length, double breadth, double height) {
this.length = length;
this.breadth = breadth;
this.height = height;
}

public double getLength() {


return length;
}

public void setLength(double length) {


this.length = length;
}

public double getBreadth() {


return breadth;
}

public void setBreadth(double breadth) {


this.breadth = breadth;
}

public double getHeight() {


return height;
}

public void setHeight(double height) {


this.height = height;
}

public double volume() {


return length * breadth * height;
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double length1 = scanner.nextDouble();
double breadth1 = scanner.nextDouble();
double height1 = scanner.nextDouble();

Cuboid cuboid1 = new Cuboid(length1, breadth1, height1);

double length2 = scanner.nextDouble();


double breadth2 = scanner.nextDouble();
double height2 = scanner.nextDouble();

Cuboid cuboid2 = new Cuboid(length2, breadth2, height2);

System.out.println("Volume of Cuboid 1: " + cuboid1.volume());


System.out.println("Volume of Cuboid 2: " + cuboid2.volume());

CTOOD SEM-IN 1 SOLUTION 3


scanner.close();
}
}

Q4. What is an array in java? Whatare the types of anarray? How to declare and use
arrays?
→An array in Java is a data structure that stores a fixed-size, ordered collection of
elements of the
same data type. An array is declared using a square bracket notation [ ] and the type
of the
elements it will store.
Two types of array are :
1. One-dimensional arrays: An array that stores elements in a single row or column.

2. Multidimensional arrays: An array that stores elements in a matrix-like format with


multiple rows and columns.

To declare an array in Java : int[] myArray = new int[5];

To access an element in the array : myArray[0] = 10;

To retrieve the value of the third element in the array : int x = myArray[2];

Q5. Create class SavingsAccount. Use a static variable annual Interest Rate to store
the annualinterest rate for all account holders. Each object ofthe class contains a
private instance variable savings Balance indicating the amount the saver currently
has on deposit. Provide method calculate Monthly lnterest to calculate the monthly
interest by multiplying the savingsBalance by annualInterestRate divided by 12-this

CTOOD SEM-IN 1 SOLUTION 4


interest should be added to savings- Balance.Provide a static method
modifyInterestRatethat sets the annualInterestRate to a new value. Write a program to
test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of
$2000.00 and $3000.00,respectively. Set annualInterestRate to 4 %,then calculate the
monthly interest and print the new balances for both savers. Then set the
annualInterestRate to 5%,calculate
the next month's interest and print the new balances for both savers.

public class SavingsAccount {


private static double annualInterestRate;
private double savingsBalance;

public SavingsAccount(double balance) {


this.savingsBalance = balance;
}

public void calculateMonthlyInterest() {


double monthlyInterest = (savingsBalance * annualInterestRate) / 12;
savingsBalance += monthlyInterest;
}

public static void modifyInterestRate(double newRate) {


annualInterestRate = newRate;
}

public double getSavingsBalance() {


return savingsBalance;
}

public static void main(String[] args) {


SavingsAccount saver1 = new SavingsAccount(2000.00);
SavingsAccount saver2 = new SavingsAccount(3000.00);
SavingsAccount(3000.00);
SavingsAccount.modifyInterestRate(0.04);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.println("Saver 1 balance after 1 month: "+saver1.getSavingsBalance());
System.out.println("Saver 2 balance after 1 month: "+saver2.getSavingsBalance());

SavingsAccount.modifyInterestRate(0.05);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.println("Saver 1 balance after 2 months: "+saver1.getSavingsBalance());
System.out.println("Saver 2 balance after 2 months: "+saver2.getSavingsBalance());
}
}

CTOOD SEM-IN 1 SOLUTION 5


Q7. Draw class Diagram and develop the class Book withISBN, title, choice price as
private attributes. Code theaccessors, mutators and toString() method. The main
method() must read the data through command line argument.

public class Book {


private String ISBN;
private String title;
private double price;
public Book(String ISBN, String title, double price) {
this.ISBN = ISBN;
this.title = title;
this.price = price;
}

public String getISBN() {


return ISBN;
}

public void setISBN(String ISBN) {


this.ISBN = ISBN;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public String toString() {


return "ISBN: " + ISBN + ", Title: " + title + ", Price: $" + price;
}

public static void main(String[] args) {


if (args.length != 3) {
System.out.println("Usage: java Book <ISBN> <title> <price>");

CTOOD SEM-IN 1 SOLUTION 6


return;
}
String ISBN = args[0];
String title = args[1];
double price = Double.parseDouble(args[2]);
Book book = new Book(ISBN, title, price);
System.out.println(book.toString());
}
}

→ Class Diagram:

Q8. What is constructor and what are the different types of constructors?

→ In OOPS construct is a method use to initialize object of a class the name of the
class and constructor is always same.

Types of constructor are :

CTOOD SEM-IN 1 SOLUTION 7


Default Constructor→ Default constructor is the constructor which doesn’t take
any argument. It has no parameters. It is also called a zero-argument constructor.

→ Java,automatically creates default constructor if there is no default or


parameterized constructor written by user, and (like C++) the default constructor
automatically calls parent default constructor.

Paramiterized Constructor→Parametrized constructor is a special type of


constructor where an object is created, and further parameters are passed to
distinct objects.

→ Parametrized constructor is a special type of constructor where an object is


created, and further parameters are passed to distinct objects.

Copy Constructor→ A copy constructor is a member function that initializes an


object using another object of the same class.

Destructor→ A destructor is also a special member function as a constructor.


Destructor destroys the class objects created by the constructor.

Static Constructor→ A static constructor is used to initialize any static data, or


to perform a particular action that needs performed once only. It is called
automatically before the first instance is created or any static members are
referenced.

Private Constructor→ Private constructors are used in class that contains only
static members. The private constructor is always declared by using
a  private  keyword.

Q9. Create a class 'Student' with three data memberswhich are name, ageand
address. The constructorof the class assigns default vaues name as "unknown", age
as '0' and address as "not
available". It has two memberswith the same name 'setlnfo'. First choice method has
two parameters for name and age and assigns the same where as the second
method takes has three parameters which are assigned to name, age and address
respectively. Print the name,
age and address of 5 students.

CTOOD SEM-IN 1 SOLUTION 8


public class Student {


private String name;
private int age;
private String address;

public Student() {
[this.name](http://this.name/) = "unknown";
this.age = 0;
this.address = "not available";
}

public void setInfo(String name, int age) {


[this.name](http://this.name/) = name;
this.age = age;
}

public void setInfo(String name, int age, String address) {


[this.name](http://this.name/) = name;
this.age = age;
this.address = address;
}

public void printInfo() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
System.out.println("------------------------");
}
}

public class Main {


public static void main(String[] args) {
Student[] students = new Student[5];
for(int i=0; i<5; i++) {
students[i] = new Student();
}

//set info using setInfo method with two parameters


students[0].setInfo("belal", 990);
students[1].setInfo("azam", 888);

//set info using setInfo method with three parameters


students[2].setInfo("ankit", 98, " bihar.");
students[3].setInfo("paul", 21, "Andhrapradesh");
students[4].setInfo("gautam", 22, "bihar");
for(int i=0; i<5; i++) {
students[i].printInfo();
}
}
}

CTOOD SEM-IN 1 SOLUTION 9


Q10. Create a class called Invoice that a hardware store might use to represent an
invoice for an item sold at the store. An Invoice should include four pieces of
information as instance variables——a part number (type string), a part description
(type String), a quantity of the item being purchased (type int) and a price per item
(double). Your class should have a constructor that initializes the four instance
variables. Provide a set and a get method for each instance variable. In
addition,provide a method named getlnvoiceAmount that calculates the invoice
amount (i.e.,
multiplies the quantity by the price per item), then returns the amount as a double
value. Ifthe quantity is not positive, it should be set to 0. Ifthe price per item is not
positive, it should be set to
0.0. Write a test application named InvoiceTest that demonstrates class Invoice's
capabilities.

public class Invoice {


private String partNumber;
private String partDescription;
private int quantity;
private double pricePerItem;
public Invoice(String partNumber, String partDescription, int quantity, double pricePer
Item) {
this.partNumber = partNumber;
this.partDescription = partDescription;
this.quantity = quantity;
this.pricePerItem = pricePerItem;
}

public String getPartNumber() {


return partNumber;
}

public void setPartNumber(String partNumber) {


this.partNumber = partNumber;
}

public String getPartDescription() {


return partDescription;
}

public void setPartDescription(String partDescription) {


this.partDescription = partDescription;

CTOOD SEM-IN 1 SOLUTION 10


}

public int getQuantity() {


return quantity;
}

public void setQuantity(int quantity) {


if (quantity > 0) {
this.quantity = quantity;
} else {
this.quantity = 0;
}
}

public double getPricePerItem() {


return pricePerItem;
}

public void setPricePerItem(double pricePerItem) {


if (pricePerItem > 0) {
this.pricePerItem = pricePerItem;
} else {
this.pricePerItem = 0.0;
}
}

public double getInvoiceAmount() {


return quantity * pricePerItem;
}
}
public class InvoiceTest {
public static void main(String[] args) {
Invoice invoice = new Invoice("12345", "Hammer", 2, 14.99);
System.out.println("Part number: " + invoice.getPartNumber());
System.out.println("Part description: " + invoice.getPartDescription());
System.out.println("Quantity: " + invoice.getQuantity());
System.out.println("Price per item: " + invoice.getPricePerItem());
System.out.println("Invoice amount: " + invoice.getInvoiceAmount());
System.out.println();

// Test negative quantity and pricePerItem


invoice.setQuantity(-2);
invoice.setPricePerItem(-14.99);
System.out.println("Quantity after setting to -2: " + invoice.getQuantity());
System.out.println("Price per item after setting to -14.99: " + invoice.getPricePer
Item());
System.out.println("Invoice amount after setting quantity to -2 and pricePerItem to
-14.99: " + invoice.getInvoiceAmount());
}
}

CTOOD SEM-IN 1 SOLUTION 11


Q11. Design a class named Rectangle to represent a rectangle. The class contains:
Two double data fields named width and height that specify the width and height of
the rectangle. The default values
are 1 for both width and height. A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified width and height. A method
named getArea() that
retums the area of this rectangle. A method named getPerimeter() that returns the
perimeter. Draw the UML diagram for the class and then implement the class. Write a
test program that creates two Rectangle objects—one with width 4 and height 40 and
the other with width 3.5 and height 35.9. Display the width, height, area, and
perimeter of each rectangle in this order.

public class Rectangle {


private double width;
private double height;
public Rectangle() {
width = 1.0;
height = 1.0;
}

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

public double getWidth() {


return width;
}

public void setWidth(double width) {


this.width = width;
}

public double getHeight() {


return height;
}

public void setHeight(double height) {


this.height = height;
}

public double getArea() {


return width * height;
}

CTOOD SEM-IN 1 SOLUTION 12


public double getPerimeter() {
return 2 * (width + height);
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(4.0, 40.0);
Rectangle r2 = new Rectangle(3.5, 35.9);
System.out.println("Rectangle 1:");
System.out.println("Width: " + r1.getWidth());
System.out.println("Height: " + r1.getHeight());
System.out.println("Area: " + r1.getArea());
System.out.println("Perimeter: " + r1.getPerimeter());

System.out.println();

System.out.println("Rectangle 2:");
System.out.println("Width: " + r2.getWidth());
System.out.println("Height: " + r2.getHeight());
System.out.println("Area: " + r2.getArea());
System.out.println("Perimeter: " + r2.getPerimeter());
}
}

Q12. Design a class named Triangle that extends GeometricObject. The class
contains: Three double data fields named sidel, side2, and side3 with default values I
.0 to denote three sides of the triangle. A no-arg constructor that creates a default
triangle.
> A constructor that creates a triangle with the specified sidel , side2,
and side3. The accessor methods for all three data fields.
> A method named getArea() that returns the area of this triangle.

> A method named getPerimeter() that returns the perimeter of this


triangle.

> A method named toString() that returns a string


description for the triangle. The toString() method is implemented
as follows: return "Triangle: side1 — " + side1+ " side2= " + side2+” side3 = " + side3;
Draw the UML diagrams for the classes Triangle and GeometricObject and implement
the classes. Write a test program that prompts the user to enter three sides of the
triangle, a color, and a Boolean value to indicate whether the triangle is filled. The

CTOOD SEM-IN 1 SOLUTION 13


program should create a Triangle object with these sides and set the color and filled
properties using the input. The program should display the area, perimeter, color, and
true or false to indicate whether it is filled or not.

public class GeometricObject {


private String color;
private boolean filled;
public GeometricObject() {
color = "white";
filled = false;
}

public GeometricObject(String color, boolean filled) {


this.color = color;
this.filled = filled;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}

public boolean isFilled() {


return filled;
}

public void setFilled(boolean filled) {


this.filled = filled;
}

public String toString() {


return "color: " + color + ", filled: " + filled;
}
}

public class Triangle extends GeometricObject {


private double sidel;
private double side2;
private double side3;
public Triangle() {
sidel = 1.0;
side2 = 1.0;
side3 = 1.0;
}

public Triangle(double sidel, double side2, double side3) {


this.sidel = sidel;
this.side2 = side2;
this.side3 = side3;
}

CTOOD SEM-IN 1 SOLUTION 14


public double getSidel() {
return sidel;
}

public void setSidel(double sidel) {


this.sidel = sidel;
}

public double getSide2() {


return side2;
}

public void setSide2(double side2) {


this.side2 = side2;
}

public double getSide3() {


return side3;
}

public void setSide3(double side3) {


this.side3 = side3;
}

public double getArea() {


double s = (sidel + side2 + side3) / 2.0;
return Math.sqrt(s * (s - sidel) * (s - side2) * (s - side3));
}

public class Main {


public static void main(String[] args) {
// Create a new Triangle object
Triangle triangle = new Triangle();

// Set the triangle's properties


triangle.setSidel(3);
triangle.setSide2(4);
triangle.setSide3(5);
triangle.setColor("red");
triangle.setFilled(true);

// Print out the triangle's details


System.out.println("Triangle details:");
System.out.println(triangle.toString());
System.out.println("Area: " + triangle.getArea());
}
}

→ Class Diagram:

CTOOD SEM-IN 1 SOLUTION 15


CTOOD SEM-IN 1 SOLUTION 16

You might also like