ST TH
ST TH
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.
findMaximumSalesMonth();
Int maxMonthIndex = 0;
maxSales = sales[i];
maxMonthIndex = I;
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.
Return a + b;
Return a + b + c;
Int sum = 0;
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.
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
If (n == 0 || n == 1) {
Return 1;
Int fact = 1;
Fact *= I;
Return fact;
Int sum = 0;
Int temp = num;
Sum += factorial(digit);
Temp /= 10;
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 |
| + getX(): double |
| + getY(): double |
| + toString(): String |
| Point3D |
| - z: double |
| z: double) |
| + getZ(): double |
| + toString(): String |
Implement
// Point2D.java
Private double x;
Private double y;
This.x = x;
This.y = y;
Return x;
This.x = x;
}
Public double getY() {
Return y;
This.y = y;
@Override
Java
// Point3D.java
Private double z;
Super(x, y);
This.z = z;
Return z;
}
This.z = z;
@Override
-Java
// Point3D.java
Private double z;
Super(x, y);
This.z = z;
This.z = z;
@Override
-java
// Main.java
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
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.
This.a = a;
This.b = b;
@Override
If (b >= 0) {
Return a + “ + “ + b + “I”;
} else {
Code-
// Addition
System.out.println(“Sum: “ + sum);
// Subtraction
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:
Ans.
| CountryTime |
| - hr: int |
| - min: int |
| - sec: int |
| - countryName: String |
| + CountryTime() |
| , sec: int, |
| countryName: |
| String) |
| + getHr(): int |
| + getMin(): int |
| + getSec(): int |
| + getCountryName(): String |
| + setCountryName(countryName: |
| String): |
| void |
| + toString(): String |
Implementation
Public CountryTime() {
// Default constructor
This.hr = hr;
This.min = min;
This.sec = sec;
This.countryName = countryName;
Return hr;
}
Public void setHr(int hr) {
This.hr = hr;
} else {
Return min;
This.min = min;
} else {
Return sec;
This.sec = sec;
} else {
Return countryName;
This.countryName = countryName;
@Override
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
This.productId = productId;
This.manufacturer = manufacturer;
This.yearOfManufacture = yearOfManufacture;
This.warranty = warranty;
This.price = price;
This.productId = productId;
Return manufacturer;
This.manufacturer = manufacturer;
Return yearOfManufacture;
This.yearOfManufacture = yearOfManufacture;
Return warranty;
}
Public void setWarranty(int warranty) {
This.warranty = warranty;
Return price;
This.price = price;
@Override
“\nManufacturer: “ + manufacturer +
“\nPrice: $” + price;
Implementation
Import java.util.Scanner;
Public class ProductDemo {
Char choice;
Do {
System.out.println(“\nMenu:”);
System.out.println(“4. Exit”);
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!”);
} else {
If (productCount == 0) {
} else {
System.out.println(“\nProduct “ + (I + 1) + “:”);
System.out.println(products[i]);
If (productCount == 0) {
} else {
System.out.println(“Product found:”);
System.out.println(products[i]);
Found = true;
Break;
If (!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.
Implementation
Return x + y;
@Override
Return x – y;
@Override
Return x * y;
@Override
If (y != 0) {
Return x / y;
} else {
Calculator demo-
Public class CalculatorDemo {
Int num2 = 5;
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 |
| + getCountry(): String |
| + setCountry(country: String)
| void |
| + getTotalRuns(): int |
| + setTotalRuns(totalRuns: int)
| void |
| + getRating(): double |
| + setRating(rating: double): |
| void |
| + toString(): String |
Implementation
This.name = name;
This.country = country;
This.totalRuns = totalRuns;
This.rating = rating;
}
Public String getName() {
Return name;
This.name = name;
Return country;
This.country = country;
Return totalRuns;
This.totalRuns = totalRuns;
This.rating = rating;
@Override
Return “CricketPlayer{“ +
“, totalRuns=” + totalRuns +
“, rating=” + rating +
‘}’;
Demo
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.Comparator;
Import java.util.List;
@Override
});
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
Ans.
| State |
| - name: String |
| - capital: String |
| - literacyRate: double |
| + State(name: String, |
| capital: String, |
| literacyRate: double) |
| + getName(): String |
| + getCapital(): String |
| + setCapital(capital: String)
| void |
| + getLiteracyRate(): double |
| + setLiteracyRate(literacyRate
| double): void |
| + toString(): String |
Implementation
This.name = name;
This.capital = capital;
This.literacyRate = literacyRate;
Return name;
This.name = name;
Return capital;
This.capital = capital;
Return literacyRate;
}
Public void setLiteracyRate(double literacyRate) {
This.literacyRate = literacyRate;
@Override
Return “State{“ +
“, literacyRate=” + literacyRate +
‘}’;
Demo class
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.Comparator;
Import java.util.Scanner;
Char choice;
Do {
System.out.println(“\nMenu:”);
System.out.println(“d) Quit”);
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!”);
}
Private static void addState(ArrayList<State> states) {
If (state.getName().equalsIgnoreCase(searchName)) {
System.out.println(“State found:”);
System.out.println(state);
Found = true;
Break;
}
If (!found) {
@Override
});
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 StringComparatorGUI() {
setTitle(“String Comparator”);
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
compareButton.addActionListener(this);
Panel.add(textField1);
Panel.add(new JLabel(“String 2:”));
Panel.add(textField2);
Panel.add(compareButton);
Add(panel);
@Override
If (str1.equals(str2)) {
} else {
SwingUtilities.invokeLater(() -> {
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.
Super(message);
Super(message);
Super(message);
}
Public Student(int ID, String name, String branch, String gender) throws
InvalidIDException, InvalidNameException, InvalidBranchException {
setID(ID);
setName(name);
setBranch(branch);
this.gender = gender;
Return ID;
If (ID < 0) {
This.ID = ID;
}
Return name;
If (!name.matches(“[a-zA-Z ]+”)) {
This.name = name;
Return branch;
If (branch.equals(validBranch)) {
isValidBranch = true;
break;
}
If (!isValidBranch) {
This.branch = branch;
Return gender;
This.gender = gender;
@Override
Return “Student{“ +
“ID=” + ID +
‘}’;
Try {
// Valid student
System.out.println(student1);
// Invalid ID
System.out.println(student2);
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.
Result.append(reverseWord(word)).append(“ “);
Return result.toString().trim();
Reversed.append(word.charAt(i));
Return reversed.toString();
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:
2. Sort by population,
Ans.
| City |
| - name: String |
| - area: long |
| - state: String |
| - population: long |
| + City(name: String, |
| area: long, |
| state: String, |
| population: long) |
| + getName(): String |
| + getArea(): long |
| + getState(): String |
| + setState(state: String): |
| void |
| + getPopulation(): long |
| + setPopulation(population: |
| long): void |
| + toString(): String |
Implementation
Public City(String name, long area, String state, long population) throws
InvalidAreaException, InvalidPopulationException {
setName(name);
setArea(area);
setState(state);
setPopulation(population);
Return name;
This.name = name;
}
Public long getArea() {
Return area;
This.area = area;
Return state;
This.state = state;
Return population;
This.population = population;
@Override
Return “City{“ +
“, area=” + area +
“, population=” + population +
‘}’;
Custom exception-----
Super(message);
Super(message);
}
}
Demo class---
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.Comparator;
Import java.util.Scanner;
Char choice;
Do {
System.out.println(“\nMenu:”);
System.out.println(“4. Quit”);
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!”);
System.out.println(e.getMessage());
Collections.sort(cities, Comparator.comparingLong(City::getPopulation));
System.out.println(city);
Collections.sort(cities, Comparator.comparingLong(City::getArea));
System.out.println(city);
}
16.Assume a class Book the following private instance members
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.
Super(message);
Super(message);
Super(message);
}
setISBN(ISBN);
setTitle(title);
setPrice(price);
Return ISBN;
If (String.valueOf(ISBN).length() != 10) {
This.ISBN = ISBN;
}
Public String getTitle() {
Return title;
This.title = title;
Return price;
If (price <= 0) {
This.price = price;
@Override
Return “Book{“ +
“ISBN=” + ISBN +
“, title=’” + title + ‘\’’ +
“, price=” + price +
‘}’;
Try {
System.out.println(book);
System.out.println(e.getMessage());