[go: up one dir, main page]

0% found this document useful (0 votes)
44 views69 pages

Part 1

Java codes

Uploaded by

layifok614
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views69 pages

Part 1

Java codes

Uploaded by

layifok614
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

1. Implement a program to manage a list of students using the Iterator interface in Java.

The program should allow the user to perform the following operations:

Add a student to the list.

Remove a student from the list.

Display all students in the list.

Replace the grade of any student

Each student should have attributes like name, roll number, and grade. Implement a Student class to
represent a student, and a StudentManager class to manage the list of students using iterators.\

1-Mohit-2-A-3-4-2-B-3-2-2-3-5

import java.util.ArrayList;

import java.util.Iterator;

import java.util.Scanner;

// Class representing a Student with attributes name, roll number, and grade

class Student {

private String name;

private int rollNumber;

private char grade;

// Constructor to initialize a Student object

public Student(String name, int rollNumber, char grade) {

this.name = name;

this.rollNumber = rollNumber;

this.grade = grade;

}
// Getter methods for Student attributes

public String getName() {

return name;

public int getRollNumber() {

return rollNumber;

public char getGrade() {

return grade;

// Setter method to update the grade of the Student

public void setGrade(char grade) {

this.grade = grade;

// Overriding toString method to display Student details

@Override

public String toString() {

return "Student{" +

"name='" + name + '\'' +

", rollNumber=" + rollNumber +

", grade=" + grade +

'}';
}

// Class to manage a collection of Student objects

class StudentManager {

private ArrayList<Student> students;

// Constructor to initialize the StudentManager with an empty list of students

public StudentManager() {

students = new ArrayList<>();

// Method to add a Student to the list

public void addStudent(Student student) {

students.add(student);

// Method to remove a Student from the list based on roll number

public void removeStudent(int rollNumber) {

Iterator<Student> iterator = students.iterator();

while (iterator.hasNext()) {

Student student = iterator.next();

if (student.getRollNumber() == rollNumber) {

iterator.remove();

System.out.println("Student with roll number " + rollNumber + " removed.");

return;
}

System.out.println("Student with roll number " + rollNumber + " not found.");

// Method to display all students in the list

public void displayStudents() {

if (students.isEmpty()) {

System.out.println("No students in the list.");

} else {

for (Student student : students) {

System.out.println(student);

// Method to replace the grade of a Student based on roll number

public void replaceGrade(int rollNumber, char newGrade) {

for (Student student : students) {

if (student.getRollNumber() == rollNumber) {

student.setGrade(newGrade);

System.out.println("Grade updated for student with roll number " + rollNumber);

return;

System.out.println("Student with roll number " + rollNumber + " not found.");


}

// Main class containing the entry point of the program

public class Main {

public static void main(String[] args) {

StudentManager studentManager = new StudentManager();

Scanner scanner = new Scanner(System.in);

int choice;

do {

// Displaying the menu options

System.out.println("\n1. Add Student");

System.out.println("2. Remove Student");

System.out.println("3. Display Students");

System.out.println("4. Replace Student Grade");

System.out.println("5. Exit");

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

choice = scanner.nextInt();

scanner.nextLine(); // consume the newline

// Handling user choices using a switch statement

switch (choice) {

case 1:

// Adding a new student

System.out.print("Enter name: ");


String name = scanner.nextLine();

System.out.print("Enter roll number: ");

int rollNumber = scanner.nextInt();

System.out.print("Enter grade: ");

char grade = scanner.next().charAt(0);

Student student = new Student(name, rollNumber, grade);

studentManager.addStudent(student);

break;

case 2:

// Removing a student based on roll number

System.out.print("Enter roll number of the student to remove: ");

int removeRollNumber = scanner.nextInt();

studentManager.removeStudent(removeRollNumber);

break;

case 3:

// Displaying all students

studentManager.displayStudents();

break;

case 4:

// Replacing a student's grade

System.out.print("Enter roll number of the student to replace grade: ");

int replaceRollNumber = scanner.nextInt();

System.out.print("Enter new grade: ");

char newGrade = scanner.next().charAt(0);

studentManager.replaceGrade(replaceRollNumber, newGrade);

break;
case 5:

// Exiting the program

System.out.println("Exiting...");

break;

default:

// Handling invalid choices

System.out.println("Invalid choice. Please try again.");

} while (choice != 5); // Loop until the user chooses to exit

// Closing the scanner

scanner.close();

}
2. Write a Java program to manage employees in a company. The company has
different types of employees, including full-time employees and part-time employees. Each employee
has a name, employee ID, and hourly rate.

Full-time employees have additional attributes such as salary and benefits, (Use super keyword)

while part-time employees have attributes for the number of hours worked and overtime rate. (Use super
keyword)

Your task is to implement a Java program using inheritance to represent these different types of
employees and their attributes. Additionally, the program should provide functionality to calculate the
monthly salary for each type of employee.

John-101-50-5000- 800-jane-102-20-100-5

import java.util.Scanner;

// Base class representing a generic Employee

class Employee {

protected String name;

protected int employeeID;

protected double hourlyRate;

// Constructor to initialize an Employee object

public Employee(String name, int employeeID, double hourlyRate) {

this.name = name;

this.employeeID = employeeID;

this.hourlyRate = hourlyRate;

}
// Getter methods for Employee attributes

public String getName() {

return name;

public int getEmployeeID() {

return employeeID;

public double getHourlyRate() {

return hourlyRate;

// Method to calculate monthly salary, to be overridden by subclasses

public double calculateMonthlySalary() {

return 0; // Base class does not calculate salary

// Subclass representing a Full-Time Employee

class FullTimeEmployee extends Employee {

private double salary;

private double benefits;

// Constructor to initialize a Full-Time Employee object

public FullTimeEmployee(String name, int employeeID, double hourlyRate, double salary, double
benefits) {
super(name, employeeID, hourlyRate);

this.salary = salary;

this.benefits = benefits;

// Getter methods for Full-Time Employee specific attributes

public double getSalary() {

return salary;

public double getBenefits() {

return benefits;

// Method to calculate monthly salary for Full-Time Employee

@Override

public double calculateMonthlySalary() {

return salary + benefits;

// Overriding toString method to display Full-Time Employee details

@Override

public String toString() {

return "FullTimeEmployee{" +

"name='" + name + '\'' +

", employeeID=" + employeeID +


", hourlyRate=" + hourlyRate +

", salary=" + salary +

", benefits=" + benefits +

'}';

// Subclass representing a Part-Time Employee

class PartTimeEmployee extends Employee {

private int hoursWorked;

private double overtimeRate;

// Constructor to initialize a Part-Time Employee object

public PartTimeEmployee(String name, int employeeID, double hourlyRate, int hoursWorked, double
overtimeRate) {

super(name, employeeID, hourlyRate);

this.hoursWorked = hoursWorked;

this.overtimeRate = overtimeRate;

// Getter methods for Part-Time Employee specific attributes

public int getHoursWorked() {

return hoursWorked;

public double getOvertimeRate() {

return overtimeRate;
}

// Method to calculate monthly salary for Part-Time Employee

@Override

public double calculateMonthlySalary() {

return (hoursWorked * hourlyRate) + (hoursWorked * overtimeRate);

// Overriding toString method to display Part-Time Employee details

@Override

public String toString() {

return "PartTimeEmployee{" +

"name='" + name + '\'' +

", employeeID=" + employeeID +

", hourlyRate=" + hourlyRate +

", hoursWorked=" + hoursWorked +

", overtimeRate=" + overtimeRate +

'}';

// Main class containing the entry point of the program

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


// Input for Full-Time Employee details

System.out.println("Enter details for Full-Time Employee:");

System.out.print("Name: ");

String ftName = scanner.nextLine();

System.out.print("Employee ID: ");

int ftEmployeeID = scanner.nextInt();

System.out.print("Hourly Rate: ");

double ftHourlyRate = scanner.nextDouble();

System.out.print("Salary: ");

double ftSalary = scanner.nextDouble();

System.out.print("Benefits: ");

double ftBenefits = scanner.nextDouble();

// Creating a Full-Time Employee object

FullTimeEmployee fullTimeEmployee = new FullTimeEmployee(ftName, ftEmployeeID,


ftHourlyRate, ftSalary, ftBenefits);

// Input for Part-Time Employee details

System.out.println("\nEnter details for Part-Time Employee:");

System.out.print("Name: ");

scanner.nextLine(); // Consume the remaining newline

String ptName = scanner.nextLine();

System.out.print("Employee ID: ");

int ptEmployeeID = scanner.nextInt();

System.out.print("Hourly Rate: ");

double ptHourlyRate = scanner.nextDouble();

System.out.print("Hours Worked: ");


int ptHoursWorked = scanner.nextInt();

System.out.print("Overtime Rate: ");

double ptOvertimeRate = scanner.nextDouble();

// Creating a Part-Time Employee object

PartTimeEmployee partTimeEmployee = new PartTimeEmployee(ptName, ptEmployeeID,


ptHourlyRate, ptHoursWorked, ptOvertimeRate);

// Output details and calculated monthly salary for Full-Time Employee

System.out.println("\nFull-Time Employee Details:");

System.out.println(fullTimeEmployee);

System.out.println("Monthly Salary: " + fullTimeEmployee.calculateMonthlySalary());

// Output details and calculated monthly salary for Part-Time Employee

System.out.println("\nPart-Time Employee Details:");

System.out.println(partTimeEmployee);

System.out.println("Monthly Salary: " + partTimeEmployee.calculateMonthlySalary());

// Closing the scanner

scanner.close();

}
3. You are required to design a system for managing different types of shapes. The
system should be able to calculate the area and perimeter of various shapes such as circles, rectangles, and
triangles. Each shape has different methods to calculate its area and perimeter. (Use abstract methods-
calculateArea(), calculatePerimeter(), displayDetails()). Your task is to implement a Java program using

polymorphism to represent these different types of shapes and calculate their area and perimeter.
Additionally, the program should provide functionality to display the details of each shape.

5-4-7-3-4-5

import java.util.Scanner;

// Abstract base class for all shapes

abstract class Shape {

public abstract double calculateArea();

public abstract double calculatePerimeter();

public abstract void displayDetails();

}
// Class for Circle, extending the Shape class

class Circle extends Shape {

private double radius;

// Constructor to initialize the radius

public Circle(double radius) {

this.radius = radius;

// Getter for radius

public double getRadius() {

return radius;

// Implementation of calculateArea method for Circle

@Override

public double calculateArea() {

return Math.PI * radius * radius;

// Implementation of calculatePerimeter method for Circle

@Override

public double calculatePerimeter() {

return 2 * Math.PI * radius;

}
// Display details of the Circle

@Override

public void displayDetails() {

System.out.println("Shape: Circle");

System.out.println("Radius: " + radius);

System.out.println("Area: " + calculateArea());

System.out.println("Perimeter: " + calculatePerimeter());

// Class for Rectangle, extending the Shape class

class Rectangle extends Shape {

private double length;

private double width;

// Constructor to initialize length and width

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

// Getter for length

public double getLength() {

return length;

}
// Getter for width

public double getWidth() {

return width;

// Implementation of calculateArea method for Rectangle

@Override

public double calculateArea() {

return length * width;

// Implementation of calculatePerimeter method for Rectangle

@Override

public double calculatePerimeter() {

return 2 * (length + width);

// Display details of the Rectangle

@Override

public void displayDetails() {

System.out.println("Shape: Rectangle");

System.out.println("Length: " + length);

System.out.println("Width: " + width);

System.out.println("Area: " + calculateArea());

System.out.println("Perimeter: " + calculatePerimeter());


}

// Class for Triangle, extending the Shape class

class Triangle extends Shape {

private double sideA;

private double sideB;

private double sideC;

// Constructor to initialize the sides of the triangle

public Triangle(double sideA, double sideB, double sideC) {

this.sideA = sideA;

this.sideB = sideB;

this.sideC = sideC;

// Getter for side A

public double getSideA() {

return sideA;

// Getter for side B

public double getSideB() {

return sideB;

}
// Getter for side C

public double getSideC() {

return sideC;

// Implementation of calculateArea method for Triangle using Heron's formula

@Override

public double calculateArea() {

double s = (sideA + sideB + sideC) / 2;

return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));

// Implementation of calculatePerimeter method for Triangle

@Override

public double calculatePerimeter() {

return sideA + sideB + sideC;

// Display details of the Triangle

@Override

public void displayDetails() {

System.out.println("Shape: Triangle");

System.out.println("Side A: " + sideA);

System.out.println("Side B: " + sideB);

System.out.println("Side C: " + sideC);

System.out.println("Area: " + calculateArea());


System.out.println("Perimeter: " + calculatePerimeter());

// Main class to execute the program

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input for Circle

System.out.println("Enter details for Circle:");

System.out.print("Radius: ");

double radius = scanner.nextDouble();

Shape circle = new Circle(radius); // Create Circle instance

// Input for Rectangle

System.out.println("\nEnter details for Rectangle:");

System.out.print("Length: ");

double length = scanner.nextDouble();

System.out.print("Width: ");

double width = scanner.nextDouble();

Shape rectangle = new Rectangle(length, width); // Create Rectangle instance

// Input for Triangle

System.out.println("\nEnter details for Triangle:");

System.out.print("Side A: ");
double sideA = scanner.nextDouble();

System.out.print("Side B: ");

double sideB = scanner.nextDouble();

System.out.print("Side C: ");

double sideC = scanner.nextDouble();

Shape triangle = new Triangle(sideA, sideB, sideC); // Create Triangle instance

// Output results for Circle

System.out.println("\nCircle Details:");

circle.displayDetails();

System.out.println();

// Output results for Rectangle

System.out.println("Rectangle Details:");

rectangle.displayDetails();

System.out.println();

// Output results for Triangle

System.out.println("Triangle Details:");

triangle.displayDetails();

// Close the scanner

scanner.close();

}
4. Implement a program for a temperature converter. The program should convert
temperatures between Celsius and Fahrenheit. However, there are certain constraints:

I. The temperature value should be within a valid range (-273.15°C to 1000°C).

Ii. The conversion should only be performed if the input temperature is within the valid range.

Your task is to implement a Java program that handles these constraints using custom exceptions. Define
a custom exception class InvalidTemperatureException to handle the case when the input temperature is
outside the valid range.

25-77
import java.util.Scanner;

// Custom exception class for invalid temperatures

class InvalidTemperatureException extends Exception {

public InvalidTemperatureException(String message) {

super(message);

// Class for temperature conversion methods

class TemperatureConverter {

// Method to convert Celsius to Fahrenheit

public static double celsiusToFahrenheit(double celsius) throws InvalidTemperatureException {

// Check if the input temperature is out of range

if (celsius < -273.15 || celsius > 1000) {

throw new InvalidTemperatureException("Temperature out of range: " + celsius + "°C");

// Convert Celsius to Fahrenheit

return (celsius * 9/5) + 32;

// Method to convert Fahrenheit to Celsius

public static double fahrenheitToCelsius(double fahrenheit) throws InvalidTemperatureException {

// Convert Fahrenheit to Celsius


double celsius = (fahrenheit - 32) * 5/9;

// Check if the converted temperature is out of range

if (celsius < -273.15 || celsius > 1000) {

throw new InvalidTemperatureException("Temperature out of range: " + fahrenheit + "°F");

return celsius;

// Main class containing the entry point of the program

public class Main {

public static void main(String[] args) {

// Create a Scanner object to take input from the user

Scanner scanner = new Scanner(System.in);

try {

// Take Celsius input from the user

System.out.print("Enter temperature in Celsius: ");

double celsius = scanner.nextDouble();

// Convert the input Celsius temperature to Fahrenheit

double fahrenheit = TemperatureConverter.celsiusToFahrenheit(celsius);

// Print the converted temperature

System.out.println(celsius + "°C = " + fahrenheit + "°F");

// Take Fahrenheit input from the user

System.out.print("Enter temperature in Fahrenheit: ");


fahrenheit = scanner.nextDouble();

// Convert the input Fahrenheit temperature to Celsius

celsius = TemperatureConverter.fahrenheitToCelsius(fahrenheit);

// Print the converted temperature

System.out.println(fahrenheit + "°F = " + celsius + "°C");

} catch (InvalidTemperatureException e) {

// Handle the custom exception and print the error message

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

} catch (Exception e) {

// Handle other exceptions (e.g., invalid input) and print a generic error message

System.err.println("Invalid input. Please enter a valid temperature.");

// Close the scanner

scanner.close();

}
5. Implement a Java program for calculating the area of geometric shapes. The
program should support calculating the area of a rectangle, a square, and a circle. Each shape has a
different method to calculate its area. Your task is to implement a Java program that demonstrates method
overloading by providing multiple versions of the calculateArea() method to calculate the area of each
shape. (Use method overloading)

4-7-5-5

import java.util.Scanner;

class AreaCalculator {

// Calculate area of a rectangle

public double calculateArea(double length, double width) {

return length * width;

// Calculate area of a square

public double calculateArea(double side) {

return side * side;

// Calculate area of a circle


public double calculateArea(double radius, boolean isCircle) {

if (isCircle) {

return Math.PI * radius * radius;

} else {

throw new IllegalArgumentException("Invalid argument for circle area calculation.");

public static void main(String[] args) {

// Create a Scanner object for taking user input

Scanner scanner = new Scanner(System.in);

// Create an AreaCalculator object to perform area calculations

AreaCalculator calculator = new AreaCalculator();

// Take input for rectangle dimensions from the user

System.out.print("Enter length of the rectangle: ");

double rectangleLength = scanner.nextDouble(); // Read rectangle length

System.out.print("Enter width of the rectangle: ");

double rectangleWidth = scanner.nextDouble(); // Read rectangle width

// Calculate the area of the rectangle

double rectangleArea = calculator.calculateArea(rectangleLength, rectangleWidth);

System.out.println("Rectangle area: " + rectangleArea); // Print the rectangle area

// Take input for square dimensions from the user


System.out.print("Enter side of the square: ");

double squareSide = scanner.nextDouble(); // Read square side length

// Calculate the area of the square

double squareArea = calculator.calculateArea(squareSide);

System.out.println("Square area: " + squareArea); // Print the square area

// Take input for circle dimensions from the user

System.out.print("Enter radius of the circle: ");

double circleRadius = scanner.nextDouble(); // Read circle radius

// Calculate the area of the circle

double circleArea = calculator.calculateArea(circleRadius, true);

System.out.println("Circle area: " + circleArea); // Print the circle area

// Close the scanner to free up resources

scanner.close();

}
6. implement a Java program to represent a simple calculator. The calculator should
have the following features:

A. Addition of two numbers

B. Subtraction of two numbers

C. Multiplication of two numbers

D. Division of two numbers

Additionally, the program should initialize a constant value for the value of PI (3.14) and print a welcome
message when an instance of the calculator is created. (static block)

Print “New calculator instance” using the instance block.

Your task is to implement a Java program that demonstrates the use of constructors, static block, and
instance block to achieve these features.

20-10

import java.util.Scanner;

class Calculator {

// Constant value for PI


public static final double PI;

// Static block to initialize PI and print welcome message

static {

PI = 3.14;

System.out.println("Welcome to the Calculator program!");

// Instance block to print a message when a new instance is created

System.out.println("New calculator instance");

// Constructor

public Calculator() {

// Constructor logic if needed

// Addition of two numbers

public double add(double a, double b) {

return a + b;

// Subtraction of two numbers

public double subtract(double a, double b) {

return a - b;
}

// Multiplication of two numbers

public double multiply(double a, double b) {

return a * b;

// Division of two numbers

public double divide(double a, double b) {

if (b == 0) {

throw new ArithmeticException("Cannot divide by zero");

return a / b;

public static void main(String[] args) {

// Create a Scanner object to read input from the user

Scanner scanner = new Scanner(System.in);

// Create an instance of the Calculator class

Calculator calculator = new Calculator();

// Take input from the user

System.out.print("Enter first number: ");

double num1 = scanner.nextDouble(); // Read the first number

System.out.print("Enter second number: ");


double num2 = scanner.nextDouble(); // Read the second number

// Perform calculations and display results

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

System.out.println("Subtraction: " + calculator.subtract(num1, num2));

System.out.println("Multiplication: " + calculator.multiply(num1, num2));

try {

// Handle division by zero

System.out.println("Division: " + calculator.divide(num1, num2));

} catch (ArithmeticException e) {

System.err.println(e.getMessage()); // Print error message if division by zero occurs

// Display the value of PI

System.out.println("Value of PI: " + Calculator.PI);

// Close the scanner to free up resources

scanner.close();

}
7. Implement a Java program to represent a shape hierarchy. The program should have
interfaces for different types of shapes, such as Drawable for shapes that can be drawn and Resizable for
shapes that can be resized.

Interface Drawable has draw() method

Interface Resizable has resize(double factor) method

Implement classes for specific shapes such as circle, rectangle and demonstrate multiple inheritance by
implementing both Drawable and Resizable interfaces in appropriate classes.

Circle implements both interfaces and implements both methods

Rectangle implements only Drawable interface and implements draw() method.

5-4-7-5

import java.util.Scanner;

// Interface for shapes that can be drawn

interface Drawable {

void draw(); // Method to draw the shape

// Interface for shapes that can be resized


interface Resizable {

void resize(double factor); // Method to resize the shape

// Circle class implementing both Drawable and Resizable interfaces

class Circle implements Drawable, Resizable {

private double radius; // Radius of the circle

// Constructor to initialize the circle with a given radius

public Circle(double radius) {

this.radius = radius;

@Override

public void draw() {

// Method implementation to draw a circle

System.out.println("Drawing a circle with radius: " + radius);

@Override

public void resize(double factor) {

// Method implementation to resize the circle by a given factor

radius *= factor;

System.out.println("Resized circle to new radius: " + radius);

}
// Getter method for the radius

public double getRadius() {

return radius;

// Rectangle class implementing only the Drawable interface

class Rectangle implements Drawable {

private double length; // Length of the rectangle

private double width; // Width of the rectangle

// Constructor to initialize the rectangle with given length and width

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public void draw() {

// Method implementation to draw a rectangle

System.out.println("Drawing a rectangle with length: " + length + " and width: " + width);

// Getter method for the length of the rectangle

public double getLength() {

return length;
}

// Getter method for the width of the rectangle

public double getWidth() {

return width;

public class ShapeHierarchyDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input for Circle

System.out.print("Enter radius for circle: ");

double circleRadius = scanner.nextDouble();

Circle circle = new Circle(circleRadius);

// Input for Rectangle

System.out.print("Enter length for rectangle: ");

double rectangleLength = scanner.nextDouble();

System.out.print("Enter width for rectangle: ");

double rectangleWidth = scanner.nextDouble();

Rectangle rectangle = new Rectangle(rectangleLength, rectangleWidth);

// Draw shapes

circle.draw(); // Draw the circle


rectangle.draw(); // Draw the rectangle

// Resize circle

System.out.print("Enter resize factor for circle: ");

double resizeFactor = scanner.nextDouble();

circle.resize(resizeFactor); // Resize the circle by the factor entered

circle.draw(); // Draw the resized circle

scanner.close(); // Close the scanner

8. Implement a Java program to perform basic operations on arrays. The program


should support the following operations:

A. Initialize an array with given elements.

B. Find the sum of all elements in the array.

C. Find the maximum element in the array.


D. Find the minimum element in the array.

E. Sort the elements of the array in ascending order.

F. Reverse the elements of the array.

5-1-2-3-4-5

import java.util.Arrays;

import java.util.Scanner;

public class ArrayOperations {

private int[] array;

// Initialize an array with given elements

public void initializeArray(int[] elements) {

array = elements.clone();

// Find the sum of all elements in the array

public int findSum() {

int sum = 0;

for (int num : array) {

sum += num;

return sum;

}
// Find the maximum element in the array

public int findMax() {

int max = array[0];

for (int num : array) {

if (num > max) {

max = num;

return max;

// Find the minimum element in the array

public int findMin() {

int min = array[0];

for (int num : array) {

if (num < min) {

min = num;

return min;

// Sort the elements of the array in ascending order

public void sortArray() {

Arrays.sort(array);

}
// Reverse the elements of the array

public void reverseArray() {

int n = array.length;

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

int temp = array[i];

array[i] = array[n - i - 1];

array[n - i - 1] = temp;

// Display the array

public void displayArray() {

System.out.println(Arrays.toString(array));

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

ArrayOperations arrayOps = new ArrayOperations();

// Take input for array elements from the user

System.out.print("Enter the number of elements in the array: ");

int n = scanner.nextInt();

int[] elements = new int[n];

System.out.println("Enter the elements of the array:");

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


elements[i] = scanner.nextInt();

// Initialize array with user input

arrayOps.initializeArray(elements);

System.out.println("Initialized Array:");

arrayOps.displayArray();

// Find the sum of all elements

System.out.println("Sum of elements: " + arrayOps.findSum());

// Find the maximum element

System.out.println("Maximum element: " + arrayOps.findMax());

// Find the minimum element

System.out.println("Minimum element: " + arrayOps.findMin());

// Sort the array

arrayOps.sortArray();

System.out.println("Sorted Array:");

arrayOps.displayArray();

// Reverse the array

arrayOps.reverseArray();

System.out.println("Reversed Array:");

arrayOps.displayArray();
scanner.close(); // Close the scanner

9. Implement a Java program to perform basic operations on strings. The program should support the
following operations:

A. Concatenate two strings.

B. Find the length of a string.

C. Convert a string to uppercase.

D. Convert a string to lowercase.

E. Check if a string contains a specific substring.

F. Replace a substring with another substring in a string.


Digvijayy-Jadhav-gvi-jay-jayy

import java.util.Scanner;

public class StringOperations {

// Concatenate two strings

public String concatenateStrings(String str1, String str2) {

return str1 + str2;

// Find the length of a string

public int getStringLength(String str) {

return str.length();

// Convert a string to uppercase

public String convertToUpperCase(String str) {

return str.toUpperCase();

// Convert a string to lowercase


public String convertToLowerCase(String str) {

return str.toLowerCase();

// Check if a string contains a specific substring

public boolean containsSubstring(String str, String substring) {

return str.contains(substring);

// Replace a substring with another substring in a string

public String replaceSubstring(String str, String oldSubstring, String newSubstring) {

return str.replace(oldSubstring, newSubstring);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

StringOperations stringOps = new StringOperations();

// Get user input for the first string

System.out.print("Enter the first string: ");

String str1 = scanner.nextLine();

// Get user input for the second string

System.out.print("Enter the second string: ");

String str2 = scanner.nextLine();


// Concatenate two strings and display the result

String concatenated = stringOps.concatenateStrings(str1, str2);

System.out.println("Concatenated String: " + concatenated);

// Find the length of the first string and display it

int length = stringOps.getStringLength(str1);

System.out.println("Length of String: " + length);

// Convert the first string to uppercase and display it

String upperCase = stringOps.convertToUpperCase(str1);

System.out.println("Uppercase String: " + upperCase);

// Convert the first string to lowercase and display it

String lowerCase = stringOps.convertToLowerCase(str1);

System.out.println("Lowercase String: " + lowerCase);

// Get user input for the substring to check in the first string

System.out.print("Enter a substring to check in the first string: ");

String substring = scanner.nextLine();

// Check if the first string contains the specified substring and display the result

boolean contains = stringOps.containsSubstring(str1, substring);

System.out.println("Contains '" + substring + "': " + contains);

// Get user input for the substring to replace and the new substring

System.out.print("Enter the substring to replace in the first string: ");


String oldSubstring = scanner.nextLine();

System.out.print("Enter the new substring to replace with: ");

String newSubstring = scanner.nextLine();

// Replace the specified substring with the new substring in the first string and display the result

String replaced = stringOps.replaceSubstring(str1, oldSubstring, newSubstring);

System.out.println("Replaced String: " + replaced);

scanner.close(); // Close the scanner

}
10. You are tasked with creating a Java program that counts the number of unique words in a given text
using a HashSet. Requirements: WordCounter Class:

Create a WordCounter class that includes the following:

A method countUniqueWords(String text) that takes a text as input and returns thecount of unique words.
Use a HashSet to store unique words. Consider a word as any sequence of characters separated by
whitespace. Main Application: Implement a main application that demonstrates the functionality of the
WordCounter class.Allow the user to input a text string. Use the WordCounter class to count and display
the number of unique words in the input text.

Sample Output : Enter a text string: This is a simple Java program. Java is powerful and simple.
Number of unique words: 8

This is a simple Java program. Java is powerful and simple.

import java.util.HashSet;

import java.util.Scanner;

// WordCounter class to count unique words in a text

class WordCounter {

// Method to count unique words in the given text

public int countUniqueWords(String text) {

// Replace punctuation marks with whitespace and convert to lowercase

text = text.replaceAll("[^a-zA-Z ]", "").toLowerCase();

// Split the text into words using whitespace as delimiter

String[] words = text.split("\\s+");


// Create a HashSet to store unique words

HashSet<String> uniqueWords = new HashSet<>();

// Add each word to the HashSet

for (String word : words) {

uniqueWords.add(word);

// Return the size of the HashSet, which represents the count of unique words

return uniqueWords.size();

public class Main {

public static void main(String[] args) {

// Create an instance of the WordCounter class

WordCounter wordCounter = new WordCounter();

// Get input text from the user

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a text string: ");

String text = scanner.nextLine();

// Count the number of unique words using the WordCounter class

int uniqueWordCount = wordCounter.countUniqueWords(text);


// Display the result

System.out.println("Number of unique words: " + uniqueWordCount);

scanner.close();

11. a. Check that given number is Armstrong or not.Eg-153=1 3 +5 3 +3 3 =1+225+27=153

b. Write a Java program to check whether two strings are anagram or not?

RACE and CARE are anagram strings.

c. Take two DOB in string format from user .Compare it and display the

messages as “Younger”, ”Elder” or “Same age”.


d. Check that given no. is prime or not.

a. Check that given number is Armstrong or not.Eg-153=1 3 +5 3 +3 3 =1+225+27=153

153

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isArmstrong(number)) {

System.out.println(number + " is an Armstrong number.");

} else {

System.out.println(number + " is not an Armstrong number.");

scanner.close();

// Function to check if a number is Armstrong or not


public static boolean isArmstrong(int num) {

int originalNum, remainder, result = 0;

originalNum = num;

while (originalNum != 0) {

remainder = originalNum % 10;

result += Math.pow(remainder, String.valueOf(num).length());

originalNum /= 10;

return result == num;

b. Write a Java program to check whether two strings are anagram or not?

RACE and CARE are anagram strings.


import java.util.Arrays;

import java.util.Scanner;

public class AnagramChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter first string: ");

String str1 = scanner.nextLine().toLowerCase();

System.out.print("Enter second string: ");

String str2 = scanner.nextLine().toLowerCase();

if (areAnagrams(str1, str2)) {

System.out.println("The strings \"" + str1 + "\" and \"" + str2 + "\" are anagrams.");

} else {

System.out.println("The strings \"" + str1 + "\" and \"" + str2 + "\" are not anagrams.");

scanner.close();

// Function to check if two strings are anagrams or not

public static boolean areAnagrams(String str1, String str2) {

char[] charArray1 = str1.toCharArray();

char[] charArray2 = str2.toCharArray();

Arrays.sort(charArray1);
Arrays.sort(charArray2);

return Arrays.equals(charArray1, charArray2);

c. Take two DOB in string format from user .Compare it and display the

messages as “Younger”, ”Elder” or “Same age”.

2004-09-02

2004-09-04

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

import java.util.Scanner;

public class DateOfBirthComparison {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

System.out.print("Enter first date of birth (yyyy-MM-dd): ");

String dob1Str = scanner.nextLine();

System.out.print("Enter second date of birth (yyyy-MM-dd): ");

String dob2Str = scanner.nextLine();

LocalDate dob1 = LocalDate.parse(dob1Str, formatter);

LocalDate dob2 = LocalDate.parse(dob2Str, formatter);

if (dob1.isBefore(dob2)) {

System.out.println("First person is elder.");

} else if (dob1.isAfter(dob2)) {

System.out.println("Second person is elder.");

} else {

System.out.println("Both persons have same age.");

scanner.close();

}
d. Check that given no. is prime or not.

import java.util.Scanner;

public class PrimeNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isPrime(number)) {

System.out.println(number + " is a prime number.");

} else {

System.out.println(number + " is not a prime number.");

scanner.close();

// Function to check if a number is prime or not

public static boolean isPrime(int num) {


if (num <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) {

return false;

return true;

}}

12. a. Create arrayList, add the integer elements in arrayList using asList().Remove the
duplicate values and return an arrayList containing unique values. Implement the logic inside
removeDuplicates() method. Test the functionalities using the main () method of the Tester class. Sample
Input and Output---------10, 20, 10, 15,40,15,40 --- 10,20,15,40.

b. Create any arraylist and perform following operations-

I. check if an element exists in ArrayList?

II. add element at particular index of ArrayList?

III. remove element at particular index of ArrayList?

IV. sort a given array list.(collections.sort())

V. reverse elements in an array list.

VI. compare two array lists.

VII. find first and last occurrence of repeated elements.

input:

Enter integer elements separated by spaces:

12345671

Unique elements: [1, 2, 3, 4, 5, 6, 7]

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList

7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 1


Enter an element to check if it exists in ArrayList: 1

Element 1 exists in ArrayList: true

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList

7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 2

Enter an index to add an element to the ArrayList: 2

Enter the element to add: 4

ArrayList after adding element 4 at index 2: [1, 2, 4, 3, 4, 5, 6, 7, 1]

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList

7. Compare two ArrayLists


8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 3

Enter an index to remove an element from the ArrayList: 2

ArrayList after removing element at index 2: [1, 2, 3, 4, 5, 6, 7, 1]

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList

7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 5

ArrayList after sorting: [1, 1, 2, 3, 4, 5, 6, 7]

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList


7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 6

ArrayList after reversing: [7, 6, 5, 4, 3, 2, 1, 1]

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList

7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 7

ArrayList and list2 are equal: false

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList


7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 8

Enter the element to find its first and last occurrences in the ArrayList: 1

First occurrence of 1: 0

Last occurrence of 1: 0

Choose operation:

1. Check if an element exists in ArrayList

2. Add element at a particular index of ArrayList

3. Remove element at a particular index of ArrayList

4. Replace element at a particular index of ArrayList

5. Sort the ArrayList

6. Reverse the elements in the ArrayList

7. Compare two ArrayLists

8. Find first and last occurrence of repeated elements

9. Exit

Enter your choice: 9

Exiting...

code:
import java.util.*;

public class ArrayListop {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Part a: Remove duplicates from ArrayList

System.out.println("Enter integer elements separated by spaces:");

ArrayList<Integer> arrayList = new ArrayList<>();

// Read input elements from the user and add them to the ArrayList

String[] elements = scanner.nextLine().split(" ");

for (String element : elements) {

arrayList.add(Integer.parseInt(element));

// Part a: Remove duplicates from ArrayList

ArrayList<Integer> uniqueList = removeDuplicates(arrayList);

System.out.println("Unique elements: " + uniqueList);

// Part b: Various operations on ArrayList

while (true) {

// Display menu options for the user to choose an operation

System.out.println("\nChoose operation:");

System.out.println("1. Check if an element exists in ArrayList");

System.out.println("2. Add element at a particular index of ArrayList");


System.out.println("3. Remove element at a particular index of ArrayList");

System.out.println("4. Replace element at a particular index of ArrayList");

System.out.println("5. Sort the ArrayList");

System.out.println("6. Reverse the elements in the ArrayList");

System.out.println("7. Compare two ArrayLists");

System.out.println("8. Find first and last occurrence of repeated elements");

System.out.println("9. Exit");

// Get the user's choice

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

int choice = scanner.nextInt();

switch (choice) {

case 1:

// Check if an element exists in the ArrayList

System.out.print("Enter an element to check if it exists in ArrayList: ");

int elementToCheck = scanner.nextInt();

System.out.println("Element " + elementToCheck + " exists in ArrayList: " +


arrayList.contains(elementToCheck));

break;

case 2:

// Add an element at a particular index in the ArrayList

System.out.print("Enter an index to add an element to the ArrayList: ");

int indexToAdd = scanner.nextInt();

System.out.print("Enter the element to add: ");

int elementToAdd = scanner.nextInt();

if (indexToAdd >= 0 && indexToAdd <= arrayList.size()) {


arrayList.add(indexToAdd, elementToAdd);

System.out.println("ArrayList after adding element " + elementToAdd + " at index " +


indexToAdd + ": " + arrayList);

} else {

System.out.println("Invalid index.");

break;

case 3:

// Remove an element at a particular index in the ArrayList

System.out.print("Enter an index to remove an element from the ArrayList: ");

int indexToRemove = scanner.nextInt();

if (indexToRemove >= 0 && indexToRemove < arrayList.size()) {

arrayList.remove(indexToRemove);

System.out.println("ArrayList after removing element at index " + indexToRemove + ": "


+ arrayList);

} else {

System.out.println("Invalid index.");

break;

case 4:

// Replace an element at a particular index in the ArrayList

System.out.print("Enter an index to replace an element in the ArrayList: ");

int indexToReplace = scanner.nextInt();

System.out.print("Enter the new element: ");

int newElement = scanner.nextInt();

if (indexToReplace >= 0 && indexToReplace < arrayList.size()) {

arrayList.set(indexToReplace, newElement);
System.out.println("ArrayList after replacing element at index " + indexToReplace + "
with " + newElement + ": " + arrayList);

} else {

System.out.println("Invalid index.");

break;

case 5:

// Sort the ArrayList

Collections.sort(arrayList);

System.out.println("ArrayList after sorting: " + arrayList);

break;

case 6:

// Reverse the elements in the ArrayList

Collections.reverse(arrayList);

System.out.println("ArrayList after reversing: " + arrayList);

break;

case 7:

// Compare two ArrayLists

ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

System.out.println("ArrayList and list2 are equal: " + arrayList.equals(list2));

break;

case 8:

// Find the first and last occurrence of repeated elements

ArrayList<Integer> repeatedList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 3, 5, 4));

System.out.print("Enter the element to find its first and last occurrences in the ArrayList: ");

int elementToFind = scanner.nextInt();

int firstOccurrence = repeatedList.indexOf(elementToFind);


int lastOccurrence = repeatedList.lastIndexOf(elementToFind);

if (firstOccurrence != -1) {

System.out.println("First occurrence of " + elementToFind + ": " + firstOccurrence);

System.out.println("Last occurrence of " + elementToFind + ": " + lastOccurrence);

} else {

System.out.println(elementToFind + " is not in the list.");

break;

case 9:

// Exit the program

System.out.println("Exiting...");

scanner.close();

System.exit(0);

break;

default:

// Handle invalid choices

System.out.println("Invalid choice!");

// Part a: Remove duplicates from ArrayList

public static ArrayList<Integer> removeDuplicates(ArrayList<Integer> arrayList) {

ArrayList<Integer> uniqueList = new ArrayList<>();

// Iterate through the original list and add elements to the uniqueList if they are not already present
for (Integer num : arrayList) {

if (!uniqueList.contains(num)) {

uniqueList.add(num);

return uniqueList;

You might also like