0% found this document useful (0 votes)
28 views55 pages

ST TH

The document discusses creating a CountryTime class with attributes for hour, minute, second and country name. It includes setters to validate the time values are within range and a toString method. The main method creates a menu driven program with options to add new CountryTime objects to an array and display the times of all countries.

Uploaded by

Arnold
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)
28 views55 pages

ST TH

The document discusses creating a CountryTime class with attributes for hour, minute, second and country name. It includes setters to validate the time values are within range and a toString method. The main method creates a menu driven program with options to add new CountryTime objects to an array and display the times of all countries.

Uploaded by

Arnold
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/ 55

1.

Develop a class ProductSales with a static array ‘sales’ of size 12 where Oth index stores
the sales on January 1st index stores sales in February….. so on 11 th index stores sales in
December. Create a static find MaximumSalesMonth() which prints the month in which
maximum sales are done, and test this above function main() from the same class

Ans.

Public class ProductSales {

Private static int[] sales = new int[12];

Public static void main(String[] args) {

// Test the function

Sales[0] = 100; // January

Sales[1] = 200; // February

Sales[2] = 150; // March

Sales[3] = 300; // April

Sales[4] = 250; // May

Sales[5] = 400; // June

Sales[6] = 180; // July

Sales[7] = 500; // August

Sales[8] = 450; // September

Sales[9] = 350; // October

Sales[10] = 600; // November

Sales[11] = 700; // December

findMaximumSalesMonth();

Public static void findMaximumSalesMonth() {


Int maxSales = sales[0];

Int maxMonthIndex = 0;

For (int I = 1; I < sales.length; i++) {

If (sales[i] > maxSales) {

maxSales = sales[i];

maxMonthIndex = I;

String[] months = {“January”, “February”, “March”, “April”, “May”, “June”, “July”,


“August”, “September”, “October”, “November”, “December”};

System.out.println(“Month with maximum sales: “ + months[maxMonthIndex]);

2.Create a class Utility with three static methods add () the first add () will take 2
arguments, add them, and return the result, second add () will take 3 arguments, add them,
and return the result, third add () will accept an array of integers, add elements in the array
and return the result. Invoke the all the three overloaded methods from main () within the
same class (use hard coded input)

Ans.

Public class Utility {

Public static void main(String[] args) {

// Test the overloaded add methods

Int result1 = add(5, 10);

System.out.println(“Result of adding two numbers: “ + result1);


Int result2 = add(3, 7, 12);

System.out.println(“Result of adding three numbers: “ + result2);

Int[] array = {2, 4, 6, 8};

Int result3 = add(array);

System.out.println(“Result of adding elements in the array: “ + result3);

Public static int add(int a, int b) {

Return a + b;

Public static int add(int a, int b, int c) {

Return a + b + c;

Public static int add(int[] array) {

Int sum = 0;

For (int num : array) {

Sum += num;

Return sum;

}
3.Develop a class Utility with three overloaded static methods with the method name
findSmallest (). The first method will take two arguments and find the smallest among them
ad return that value. The second method will take three arguments and find smallest
among them. The third method will accept an array and find the smallest value in the array
and return it. Call these three overloaded methods and test their functionality from the
main () of the Demo class which belong to another package.

Ans.

Public class Utility {

Public static int findSmallest(int a, int b) {

Return Math.min(a, b);

Public static int findSmallest(int a, int b, int c) {

Return Math.min(Math.min(a, b), c);

Public static int findSmallest(int[] array) {

Int min = array[0];

For (int I = 1; I < array.length; i++) {

If (array[i] < min) {

Min = array[i];

Return min;

}
4.Develop Java code with 2 methods in MyFirstClass a) factorial () b) is Strong() Strong
number is a special number whose sum of factorial of digits is equal to the original number.
For example: 145 is strong number. Since 11+41 +51 145. The method expects an integer as
argument and then returns true if the number is strong, otherwise returns false.

Ans

Public class MyFirstClass {

Public static void main(String[] args) {

Int num1 = 145;

Int num2 = 123;

System.out.println(num1 + “ is Strong? “ + isStrong(num1));

System.out.println(num2 + “ is Strong? “ + isStrong(num2));

Public static int factorial(int n) {

If (n == 0 || n == 1) {

Return 1;

Int fact = 1;

For (int I = 2; I <= n; i++) {

Fact *= I;

Return fact;

Public static boolean isStrong(int num) {

Int sum = 0;
Int temp = num;

While (temp > 0) {

Int digit = temp % 10;

Sum += factorial(digit);

Temp /= 10;

Return sum == num;

5. Draw the class diagram and develop a class Point2D with private attributes x and y of
type double and a class Point3D which inherits Point2D and has a private attribute z. Write
constructors, toString() methods in both classes and a main() method in another class to
create object of Point3D to print all values of x, y and z.

Ans.

Class diagram

| Point2D |

| - x: double |

| - y: double |

| + Point2D(x: double, y: double)|

| + getX(): double |

| + setX(x: double): void |

| + getY(): double |

| + setY(y: double): void |

| + toString(): String |
| Point3D |

| - z: double |

| + Point3D(x: double, y: double,|

| z: double) |

| + getZ(): double |

| + setZ(z: double): void |

| + toString(): String |

Implement

// Point2D.java

Public class Point2D {

Private double x;

Private double y;

Public Point2D(double x, double y) {

This.x = x;

This.y = y;

Public double getX() {

Return x;

Public void setX(double x) {

This.x = x;

}
Public double getY() {

Return y;

Public void setY(double y) {

This.y = y;

@Override

Public String toString() {

Return “(“ + x + “, “ + y + “)”;

Java

// Point3D.java

Public class Point3D extends Point2D {

Private double z;

Public Point3D(double x, double y, double z) {

Super(x, y);

This.z = z;

Public double getZ() {

Return z;
}

Public void setZ(double z) {

This.z = z;

@Override

Public String toString() {

Return “(“ + getX() + “, “ + getY() + “, “ + z + “)”;

-Java

// Point3D.java

Public class Point3D extends Point2D {

Private double z;

Public Point3D(double x, double y, double z) {

Super(x, y);

This.z = z;

Public double getZ() {


Return z;

Public void setZ(double z) {

This.z = z;

@Override

Public String toString() {

Return “(“ + getX() + “, “ + getY() + “, “ + z + “)”;

-java

// Main.java

Public class Main {

Public static void main(String[] args) {

Point3D point3D = new Point3D(1.0, 2.0, 3.0);

System.out.println(“Point3D: “ + point3D);

6.A complex number is a number in the form a + bi, where a and b are real numbers and I is
(-1)^1/2. The numbers a and b are known as the real part and imaginary part of the complex
number, respectively. You can perform addition, subtraction for complex numbers using
the following formula

(a+bi) + (c+di) = (a+c)+(b+ d)I and


(a+bi)(c+di) = (ac)+(bd)I,

Create a class Complex that performs the above operations. It has 2 double attributes a, b
that represent real and imaginary part of the complex number and constructor,
gettertoString() method that formats as a+ib. The methods are add(x:Complex): Complex,
sub(x: Complex): Complex. In the main() method of ComplexDemo class, create 2 objects
of Complex class that demonstrate the functionality of above operations and display the
result.

Ans.

Public class Complex {

Private double a; // real part

Private double b; // imaginary part

Public Complex(double a, double b) {

This.a = a;

This.b = b;

Public Complex add(Complex x) {

Double realPart = this.a + x.a;

Double imagPart = this.b + x.b;

Return new Complex(realPart, imagPart);

Public Complex sub(Complex x) {

Double realPart = this.a – x.a;

Double imagPart = this.b – x.b;

Return new Complex(realPart, imagPart);


}

@Override

Public String toString() {

If (b >= 0) {

Return a + “ + “ + b + “I”;

} else {

Return a + “ – “ + (-b) + “I”;

Code-

Public class ComplexDemo {

Public static void main(String[] args) {

Complex complex1 = new Complex(2, 3);

Complex complex2 = new Complex(4, -1);

// Addition

Complex sum = complex1.add(complex2);

System.out.println(“Sum: “ + sum);

// Subtraction

Complex difference = complex1.sub(complex2);

System.out.println(“Difference: “ + difference);

}
}

7.Draw class diagram and define a class Country Time with private attributes hr, min, sec of
type integer and countryName of type String. Write setters by validating hr (0-23), min (0-
59) and sec (0- 59) and toString() to print in the following format – Current Time in India is 09
hrs 30 mins 45 secs. The main() method must be able to store data in an array each storing
data of a country and is menu driven with the following options:

1. Add new Country Time,


2. Display Time of all countries.

Ans.

| CountryTime |

| - hr: int |

| - min: int |

| - sec: int |

| - countryName: String |

| + CountryTime() |

| + CountryTime(hr: int, min: int|

| , sec: int, |

| countryName: |

| String) |

| + getHr(): int |

| + setHr(hr: int): void |

| + getMin(): int |

| + setMin(min: int): void |

| + getSec(): int |

| + setSec(sec: int): void |

| + getCountryName(): String |
| + setCountryName(countryName: |

| String): |

| void |

| + toString(): String |

Implementation

Public class CountryTime {

Private int hr;

Private int min;

Private int sec;

Private String countryName;

Public CountryTime() {

// Default constructor

Public CountryTime(int hr, int min, int sec, String countryName) {

This.hr = hr;

This.min = min;

This.sec = sec;

This.countryName = countryName;

Public int getHr() {

Return hr;

}
Public void setHr(int hr) {

If (hr >= 0 && hr <= 23) {

This.hr = hr;

} else {

System.out.println(“Invalid hour. Hour must be between 0 and 23.”);

Public int getMin() {

Return min;

Public void setMin(int min) {

If (min >= 0 && min <= 59) {

This.min = min;

} else {

System.out.println(“Invalid minute. Minute must be between 0 and 59.”);

Public int getSec() {

Return sec;

Public void setSec(int sec) {


If (sec >= 0 && sec <= 59) {

This.sec = sec;

} else {

System.out.println(“Invalid second. Second must be between 0 and 59.”);

Public String getCountryName() {

Return countryName;

Public void setCountryName(String countryName) {

This.countryName = countryName;

@Override

Public String toString() {

Return “Current Time in “ + countryName + “ is “ + String.format(“%02d”, hr) + “ hrs “ +

String.format(“%02d”, min) + “ mins “ + String.format(“%02d”, sec) + “ secs.”;

8.Draw the class diagram and develop logic as per the following specifications-An E-
commerce startup must record the following information of Product ID, manufacturer,
yearOfManufacture, warranty, price. Define the parameterized constructor and toString()
method. The ProductDemo must store data in an array and has main() method which is
menu driven with the following options:
1. Add Product information
2. Print details of all Products
3. Search based on ID

Ans.

| Product |

| - productId: int |

| - manufacturer: String |

| - yearOfManufacture: int |

| - warranty: int |

| - price: double |

| + Product(productId: int, |

| manufacturer: |

| String, |

| yearOfManufacture: |

| int, |

| warranty: int, |

| price: double) |

| + getProductId(): int |

| + setProductId(productId: |

| int): void |

| + getManufacturer(): String |

| + setManufacturer(manufacturer

| String): void |

| + getYearOfManufacture(): int |

| + setYearOfManufacture(yearOfManufacture

| int): void |
| + getWarranty(): int |

| + setWarranty(warranty: int): |

| void |

| + getPrice(): double |

| + setPrice(price: double): |

| void |

| + toString(): String |

Implementation

Public class Product {

Private int productId;

Private String manufacturer;

Private int yearOfManufacture;

Private int warranty;

Private double price;

Public Product(int productId, String manufacturer, int yearOfManufacture, int warranty,


double price) {

This.productId = productId;

This.manufacturer = manufacturer;

This.yearOfManufacture = yearOfManufacture;

This.warranty = warranty;

This.price = price;

Public int getProductId() {


Return productId;

Public void setProductId(int productId) {

This.productId = productId;

Public String getManufacturer() {

Return manufacturer;

Public void setManufacturer(String manufacturer) {

This.manufacturer = manufacturer;

Public int getYearOfManufacture() {

Return yearOfManufacture;

Public void setYearOfManufacture(int yearOfManufacture) {

This.yearOfManufacture = yearOfManufacture;

Public int getWarranty() {

Return warranty;

}
Public void setWarranty(int warranty) {

This.warranty = warranty;

Public double getPrice() {

Return price;

Public void setPrice(double price) {

This.price = price;

@Override

Public String toString() {

Return “Product ID: “ + productId +

“\nManufacturer: “ + manufacturer +

“\nYear of Manufacture: “ + yearOfManufacture +

“\nWarranty: “ + warranty + “ years” +

“\nPrice: $” + price;

Implementation

Import java.util.Scanner;
Public class ProductDemo {

Private static final int MAX_PRODUCTS = 100;

Private static Product[] products = new Product[MAX_PRODUCTS];

Private static int productCount = 0;

Private static Scanner scanner = new Scanner(System.in);

Public static void main(String[] args) {

Char choice;

Do {

System.out.println(“\nMenu:”);

System.out.println(“1. Add Product information”);

System.out.println(“2. Print details of all Products”);

System.out.println(“3. Search based on ID”);

System.out.println(“4. Exit”);

System.out.print(“Enter your choice: “);

Choice = scanner.next().charAt(0);

Switch (choice) {

Case ‘1’:

addProduct();

break;

case ‘2’:

printAllProducts();

break;

case ‘3’:

searchProductById();
break;

case ‘4’:

System.out.println(“Exiting…”);

Break;

Default:

System.out.println(“Invalid choice!”);

} while (choice != ‘4’);

Private static void addProduct() {

If (productCount < MAX_PRODUCTS) {

System.out.print(“Enter Product ID: “);

Int productId = scanner.nextInt();

Scanner.nextLine(); // Consume newline

System.out.print(“Enter Manufacturer: “);

String manufacturer = scanner.nextLine();

System.out.print(“Enter Year of Manufacture: “);

Int yearOfManufacture = scanner.nextInt();

System.out.print(“Enter Warranty (in years): “);

Int warranty = scanner.nextInt();

System.out.print(“Enter Price: “);

Double price = scanner.nextDouble();

Products[productCount++] = new Product(productId, manufacturer,


yearOfManufacture, warranty, price);
System.out.println(“Product added successfully!”);

} else {

System.out.println(“Maximum products reached. Cannot add more.”);

Private static void printAllProducts() {

If (productCount == 0) {

System.out.println(“No products available.”);

} else {

System.out.println(“Details of all Products:”);

For (int I = 0; I < productCount; i++) {

System.out.println(“\nProduct “ + (I + 1) + “:”);

System.out.println(products[i]);

Private static void searchProductById() {

If (productCount == 0) {

System.out.println(“No products available for search.”);

} else {

System.out.print(“Enter Product ID to search: “);

Int searchId = scanner.nextInt();

Boolean found = false;

For (int I = 0; I < productCount; i++) {


If (products[i].getProductId() == searchId) {

System.out.println(“Product found:”);

System.out.println(products[i]);

Found = true;

Break;

If (!found) {

System.out.println(“Product with ID “ + searchId + “ not found.”);

9.Develop an interface MyCalculator with 4 methods add(), sub(), mul() and div(). Each of
the above methods return an integer value. A class IntegerCalculator implements the
interface and has 2 private attributes x and y. Write the main() method in Calculator Demo
class to demonstrate the abilities of IntegerCalculator

Ans.

Public interface MyCalculator {

Int add(int x, int y);

Int sub(int x, int y);

Int mul(int x, int y);

Int div(int x, int y);

Implementation

Public class IntegerCalculator implements MyCalculator {


@Override

Public int add(int x, int y) {

Return x + y;

@Override

Public int sub(int x, int y) {

Return x – y;

@Override

Public int mul(int x, int y) {

Return x * y;

@Override

Public int div(int x, int y) {

If (y != 0) {

Return x / y;

} else {

System.out.println(“Error: Division by zero!”);

Return Integer.MIN_VALUE; // Return a special value to indicate error

Calculator demo-
Public class CalculatorDemo {

Public static void main(String[] args) {

IntegerCalculator calculator = new IntegerCalculator();

Int num1 = 10;

Int num2 = 5;

System.out.println(“Addition: “ + calculator.add(num1, num2));

System.out.println(“Subtraction: “ + calculator.sub(num1, num2));

System.out.println(“Multiplication: “ + calculator.mul(num1, num2));

System.out.println(“Division: “ + calculator.div(num1, num2));

10.Draw the class diagram and develop a class CricketPlayer with the following private
attributes Name, country, totalRuns and rating. Code the constructor and necessary
methods. The main()

Method of Demo class must store data of cricket players in a collection and sort them in
Descending order based on totalRuns

Ans.

| CricketPlayer |

| - name: String |

| - country: String |

| - totalRuns: int |

| - rating: double |

| + CricketPlayer(name: String, |

| country: String,|

| totalRuns: int, |
| rating: double)|

| + getName(): String |

| + setName(name: String): void |

| + getCountry(): String |

| + setCountry(country: String)

| void |

| + getTotalRuns(): int |

| + setTotalRuns(totalRuns: int)

| void |

| + getRating(): double |

| + setRating(rating: double): |

| void |

| + toString(): String |

Implementation

Public class CricketPlayer {

Private String name;

Private String country;

Private int totalRuns;

Private double rating;

Public CricketPlayer(String name, String country, int totalRuns, double rating) {

This.name = name;

This.country = country;

This.totalRuns = totalRuns;

This.rating = rating;

}
Public String getName() {

Return name;

Public void setName(String name) {

This.name = name;

Public String getCountry() {

Return country;

Public void setCountry(String country) {

This.country = country;

Public int getTotalRuns() {

Return totalRuns;

Public void setTotalRuns(int totalRuns) {

This.totalRuns = totalRuns;

Public double getRating() {


Return rating;

Public void setRating(double rating) {

This.rating = rating;

@Override

Public String toString() {

Return “CricketPlayer{“ +

“name=’” + name + ‘\’’ +

“, country=’” + country + ‘\’’ +

“, totalRuns=” + totalRuns +

“, rating=” + rating +

‘}’;

Demo

Import java.util.ArrayList;

Import java.util.Collections;

Import java.util.Comparator;

Import java.util.List;

Public class Demo {

Public static void main(String[] args) {

List<CricketPlayer> players = new ArrayList<>();


// Adding players to the list

Players.add(new CricketPlayer(“Sachin Tendulkar”, “India”, 18426, 9.4));

Players.add(new CricketPlayer(“Ricky Ponting”, “Australia”, 13704, 8.2));

Players.add(new CricketPlayer(“Kumar Sangakkara”, “Sri Lanka”, 14234, 8.9));

Players.add(new CricketPlayer(“Jacques Kallis”, “South Africa”, 11579, 9.1));

// Sorting players in descending order based on total runs

Collections.sort(players, new Comparator<CricketPlayer>() {

@Override

Public int compare(CricketPlayer p1, CricketPlayer p2) {

Return Integer.compare(p2.getTotalRuns(), p1.getTotalRuns());

});

// Printing sorted players

System.out.println(“Players sorted in descending order of total runs:”);

For (CricketPlayer player : players) {

System.out.println(player);

11.The census committee maintains data of states in India. The task is to draw the class
diagram and develop the class State with name, capital and literacy Rate as the private
attributes. Code the parameterized constructor and toString() method. Develop the main()
method in Demo class to store data of states in an ArrayList and is menu driven with the
following options
a) Add new State information,
b) Search based on state name

c)Sort by literacyRate in descending order. (Use Comparable or Comparator)

Ans.

| State |

| - name: String |

| - capital: String |

| - literacyRate: double |

| + State(name: String, |

| capital: String, |

| literacyRate: double) |

| + getName(): String |

| + setName(name: String): void |

| + getCapital(): String |

| + setCapital(capital: String)

| void |

| + getLiteracyRate(): double |

| + setLiteracyRate(literacyRate

| double): void |

| + toString(): String |

Implementation

Public class State {

Private String name;

Private String capital;

Private double literacyRate;


Public State(String name, String capital, double literacyRate) {

This.name = name;

This.capital = capital;

This.literacyRate = literacyRate;

Public String getName() {

Return name;

Public void setName(String name) {

This.name = name;

Public String getCapital() {

Return capital;

Public void setCapital(String capital) {

This.capital = capital;

Public double getLiteracyRate() {

Return literacyRate;

}
Public void setLiteracyRate(double literacyRate) {

This.literacyRate = literacyRate;

@Override

Public String toString() {

Return “State{“ +

“name=’” + name + ‘\’’ +

“, capital=’” + capital + ‘\’’ +

“, literacyRate=” + literacyRate +

‘}’;

Demo class

Import java.util.ArrayList;

Import java.util.Collections;

Import java.util.Comparator;

Import java.util.Scanner;

Public class Demo {

Public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

ArrayList<State> states = new ArrayList<>();

Char choice;

Do {
System.out.println(“\nMenu:”);

System.out.println(“a) Add new State information”);

System.out.println(“b) Search based on state name”);

System.out.println(“c) Sort by literacyRate in descending order”);

System.out.println(“d) Quit”);

System.out.print(“Enter your choice: “);

Choice = scanner.next().charAt(0);

Switch (choice) {

Case ‘a’:

addState(states);

break;

case ‘b’:

searchState(states);

break;

case ‘c’:

sortStatesByLiteracyRate(states);

break;

case ‘d’:

System.out.println(“Exiting…”);

Break;

Default:

System.out.println(“Invalid choice!”);

} while (choice != ‘d’);

}
Private static void addState(ArrayList<State> states) {

Scanner scanner = new Scanner(System.in);

System.out.print(“Enter state name: “);

String name = scanner.nextLine();

System.out.print(“Enter capital: “);

String capital = scanner.nextLine();

System.out.print(“Enter literacy rate: “);

Double literacyRate = scanner.nextDouble();

States.add(new State(name, capital, literacyRate));

System.out.println(“State information added successfully.”);

Private static void searchState(ArrayList<State> states) {

Scanner scanner = new Scanner(System.in);

System.out.print(“Enter state name to search: “);

String searchName = scanner.nextLine();

Boolean found = false;

For (State state : states) {

If (state.getName().equalsIgnoreCase(searchName)) {

System.out.println(“State found:”);

System.out.println(state);

Found = true;

Break;
}

If (!found) {

System.out.println(“State with name “ + searchName + “ not found.”);

Private static void sortStatesByLiteracyRate(ArrayList<State> states) {

Collections.sort(states, new Comparator<State>() {

@Override

Public int compare(State s1, State s2) {

Return Double.compare(s2.getLiteracyRate(), s1.getLiteracyRate());

});

System.out.println(“States sorted by literacy rate in descending order:”);

For (State state : states) {

System.out.println(state);

12.Create a GUI window which contains two JTextField and a JButton. When the button is
clicked the system must take the string from the textfield2 and compare the string present
in the textfield1. If both are equal pop out a dialog box saying, “both are equal”, if first string
is lexicographically larger than the second then pop out a dialog box saying, “first string is
larger than the second”. Otherwise,

Ans.
Import javax.swing.*;

Import java.awt.*;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;

Public class StringComparatorGUI extends JFrame implements ActionListener {

Private JTextField textField1;

Private JTextField textField2;

Private JButton compareButton;

Public StringComparatorGUI() {

setTitle(“String Comparator”);

setSize(300, 150);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

textField1 = new JTextField(20);

textField2 = new JTextField(20);

compareButton = new JButton(“Compare”);

compareButton.addActionListener(this);

JPanel panel = new JPanel();

Panel.setLayout(new GridLayout(3, 1));

Panel.add(new JLabel(“String 1:”));

Panel.add(textField1);
Panel.add(new JLabel(“String 2:”));

Panel.add(textField2);

Panel.add(compareButton);

Add(panel);

@Override

Public void actionPerformed(ActionEvent e) {

String str1 = textField1.getText();

String str2 = textField2.getText();

If (str1.equals(str2)) {

JOptionPane.showMessageDialog(this, “Both strings are equal”);

} else if (str1.compareTo(str2) > 0) {

JOptionPane.showMessageDialog(this, “First string is larger than the second”);

} else {

JOptionPane.showMessageDialog(this, “Second string is larger than the first”);

Public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

StringComparatorGUI frame = new StringComparatorGUI();

Frame.setVisible(true);

});
}

13.Create Student class with attributes ID, name, branch, and gender, develop setters,
getters and toString (), such that the setter methods must throw when InvalidIDException
when Invalid ID (-ve number) is given, InvalidNameException when name has special
characters or digits, InvalidBranchException must be thrown when the given branch is not
among these lists of branches. The valid branches are CSE, AI&DS, CS&IT, BT, EEE, ECE,
and ME. Test your code by creating objects of students in main () of the Demo class.

Ans.

// Custom exception for invalid ID

Class InvalidIDException extends Exception {

Public InvalidIDException(String message) {

Super(message);

// Custom exception for invalid name

Class InvalidNameException extends Exception {

Public InvalidNameException(String message) {

Super(message);

// Custom exception for invalid branch

Class InvalidBranchException extends Exception {

Public InvalidBranchException(String message) {

Super(message);
}

Public class Student {

Private int ID;

Private String name;

Private String branch;

Private String gender;

Public Student(int ID, String name, String branch, String gender) throws
InvalidIDException, InvalidNameException, InvalidBranchException {

setID(ID);

setName(name);

setBranch(branch);

this.gender = gender;

Public int getID() {

Return ID;

Public void setID(int ID) throws InvalidIDException {

If (ID < 0) {

Throw new InvalidIDException(“Invalid ID: “ + ID);

This.ID = ID;
}

Public String getName() {

Return name;

Public void setName(String name) throws InvalidNameException {

If (!name.matches(“[a-zA-Z ]+”)) {

Throw new InvalidNameException(“Invalid name: “ + name);

This.name = name;

Public String getBranch() {

Return branch;

Public void setBranch(String branch) throws InvalidBranchException {

String[] validBranches = {“CSE”, “AI&DS”, “CS&IT”, “BT”, “EEE”, “ECE”, “ME”};

Boolean isValidBranch = false;

For (String validBranch : validBranches) {

If (branch.equals(validBranch)) {

isValidBranch = true;

break;

}
If (!isValidBranch) {

Throw new InvalidBranchException(“Invalid branch: “ + branch);

This.branch = branch;

Public String getGender() {

Return gender;

Public void setGender(String gender) {

This.gender = gender;

@Override

Public String toString() {

Return “Student{“ +

“ID=” + ID +

“, name=’” + name + ‘\’’ +

“, branch=’” + branch + ‘\’’ +

“, gender=’” + gender + ‘\’’ +

‘}’;

Public static void main(String[] args) {

Try {
// Valid student

Student student1 = new Student(1001, “John Doe”, “CSE”, “Male”);

System.out.println(student1);

// Invalid ID

Student student2 = new Student(-1002, “Alice”, “CS&IT”, “Female”);

System.out.println(student2);

} catch (InvalidIDException | InvalidNameException | InvalidBranchException e) {

System.out.println(e.getMessage());

14.Write a program that will reverse the sequence of letters in each word from the given
String. For example: If the given String is, “To be or not to be would become “oT eb ro ton ot
eb.

Ans.

Public class ReverseWords {

Public static String reverseWordsInString(String input) {

// Split the input string into words

String[] words = input.split(“ “);

// StringBuilder to store the result

StringBuilder result = new StringBuilder();

// Iterate through each word

For (String word : words) {


// Reverse the word and append it to the result

Result.append(reverseWord(word)).append(“ “);

// Remove the trailing space and return the result

Return result.toString().trim();

// Method to reverse a word

Private static String reverseWord(String word) {

StringBuilder reversed = new StringBuilder();

// Iterate through each character in the word in reverse order

For (int I = word.length() – 1; I >= 0; i--) {

// Append each character to the StringBuilder

Reversed.append(word.charAt(i));

// Return the reversed word

Return reversed.toString();

Public static void main(String[] args) {

String input = “To be or not to be”;

String result = reverseWordsInString(input);

System.out.println(“Original: “ + input);

System.out.println(“Reversed: “ + result);

}
}

15. Draw class diagram and develop logic as per the following specifications: The class City
has name, area, state, population as attributes. The attributes area (in sq. m) and
population are of type long. Code the constructor, setters and toString() method. The setter
methods must generate an exception if the area is less than 10. And the population is less
than 100. The main() method must store data of cities in a collection and is menu driven
with the following options:

1. Add new city,

2. Sort by population,

3. Sort by area. (Hint: Use Comparator Interface)

Ans.

| City |

| - name: String |

| - area: long |

| - state: String |

| - population: long |

| + City(name: String, |

| area: long, |

| state: String, |

| population: long) |

| + getName(): String |

| + setName(name: String): void |

| + getArea(): long |

| + setArea(area: long): void |

| + getState(): String |

| + setState(state: String): |

| void |
| + getPopulation(): long |

| + setPopulation(population: |

| long): void |

| + toString(): String |

Implementation

Public class City {

Private String name;

Private long area;

Private String state;

Private long population;

Public City(String name, long area, String state, long population) throws
InvalidAreaException, InvalidPopulationException {

setName(name);

setArea(area);

setState(state);

setPopulation(population);

Public String getName() {

Return name;

Public void setName(String name) {

This.name = name;

}
Public long getArea() {

Return area;

Public void setArea(long area) throws InvalidAreaException {

If (area < 10) {

Throw new InvalidAreaException(“Area must be at least 10 sq. m”);

This.area = area;

Public String getState() {

Return state;

Public void setState(String state) {

This.state = state;

Public long getPopulation() {

Return population;

Public void setPopulation(long population) throws InvalidPopulationException {

If (population < 100) {


Throw new InvalidPopulationException(“Population must be at least 100”);

This.population = population;

@Override

Public String toString() {

Return “City{“ +

“name=’” + name + ‘\’’ +

“, area=” + area +

“, state=’” + state + ‘\’’ +

“, population=” + population +

‘}’;

Custom exception-----

Class InvalidAreaException extends Exception {

Public InvalidAreaException(String message) {

Super(message);

Class InvalidPopulationException extends Exception {

Public InvalidPopulationException(String message) {

Super(message);

}
}

Demo class---

Import java.util.ArrayList;

Import java.util.Collections;

Import java.util.Comparator;

Import java.util.Scanner;

Public class Demo {

Public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

ArrayList<City> cities = new ArrayList<>();

Char choice;

Do {

System.out.println(“\nMenu:”);

System.out.println(“1. Add new city”);

System.out.println(“2. Sort by population”);

System.out.println(“3. Sort by area”);

System.out.println(“4. Quit”);

System.out.print(“Enter your choice: “);

Choice = scanner.next().charAt(0);

Switch (choice) {

Case ‘1’:

addCity(scanner, cities);

break;
case ‘2’:

sortByPopulation(cities);

break;

case ‘3’:

sortByArea(cities);

break;

case ‘4’:

System.out.println(“Exiting…”);

Break;

Default:

System.out.println(“Invalid choice!”);

} while (choice != ‘4’);

Private static void addCity(Scanner scanner, ArrayList<City> cities) {

Scanner.nextLine(); // Consume newline

System.out.print(“Enter city name: “);

String name = scanner.nextLine();

System.out.print(“Enter area (sq. m): “);

Long area = scanner.nextLong();

Scanner.nextLine(); // Consume newline

System.out.print(“Enter state: “);

String state = scanner.nextLine();

System.out.print(“Enter population: “);

Long population = scanner.nextLong();


Try {

Cities.add(new City(name, area, state, population));

System.out.println(“City added successfully.”);

} catch (InvalidAreaException | InvalidPopulationException e) {

System.out.println(e.getMessage());

Private static void sortByPopulation(ArrayList<City> cities) {

Collections.sort(cities, Comparator.comparingLong(City::getPopulation));

System.out.println(“Cities sorted by population:”);

For (City city : cities) {

System.out.println(city);

Private static void sortByArea(ArrayList<City> cities) {

Collections.sort(cities, Comparator.comparingLong(City::getArea));

System.out.println(“Cities sorted by area:”);

For (City city : cities) {

System.out.println(city);

}
16.Assume a class Book the following private instance members

a) ISBN (long) – 10 digits,


b) Title (String)-length must be less than 50,
c) Price (double) – must be a positive value.

Define a parameterizedconstructor and setters to validate the inputs. The setters raise
Exception.

The exceptions must be handled in the main() method of BookDemo class during object

Instantiation.

Ans.

// Custom exception for invalid ISBN

Class InvalidISBNException extends Exception {

Public InvalidISBNException(String message) {

Super(message);

// Custom exception for invalid title

Class InvalidTitleException extends Exception {

Public InvalidTitleException(String message) {

Super(message);

// Custom exception for invalid price

Class InvalidPriceException extends Exception {

Public InvalidPriceException(String message) {

Super(message);
}

Public class Book {

Private long ISBN;

Private String title;

Private double price;

Public Book(long ISBN, String title, double price) throws InvalidISBNException,


InvalidTitleException, InvalidPriceException {

setISBN(ISBN);

setTitle(title);

setPrice(price);

Public long getISBN() {

Return ISBN;

Public void setISBN(long ISBN) throws InvalidISBNException {

If (String.valueOf(ISBN).length() != 10) {

Throw new InvalidISBNException(“Invalid ISBN: “ + ISBN);

This.ISBN = ISBN;

}
Public String getTitle() {

Return title;

Public void setTitle(String title) throws InvalidTitleException {

If (title.length() >= 50) {

Throw new InvalidTitleException(“Title length must be less than 50 characters”);

This.title = title;

Public double getPrice() {

Return price;

Public void setPrice(double price) throws InvalidPriceException {

If (price <= 0) {

Throw new InvalidPriceException(“Price must be a positive value”);

This.price = price;

@Override

Public String toString() {

Return “Book{“ +

“ISBN=” + ISBN +
“, title=’” + title + ‘\’’ +

“, price=” + price +

‘}’;

Public static void main(String[] args) {

Try {

Book book = new Book(1234567890, “Sample Book”, 20.0);

System.out.println(book);

} catch (InvalidISBNException | InvalidTitleException | InvalidPriceException e) {

System.out.println(e.getMessage());

You might also like