0% found this document useful (0 votes)
7 views22 pages

TermWork Java ANISH

The document contains a series of Java programming problems and their solutions, covering various concepts such as character frequency counting, number replacement, string operations, class design for employee tax details, shape calculations, bank account management, animal sound abstraction, sorting algorithms, and student percentage calculation with exception handling. Each problem includes an objective, code implementation, and expected output. The solutions demonstrate fundamental programming principles including inheritance, polymorphism, and exception handling.

Uploaded by

golu desai
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)
7 views22 pages

TermWork Java ANISH

The document contains a series of Java programming problems and their solutions, covering various concepts such as character frequency counting, number replacement, string operations, class design for employee tax details, shape calculations, bank account management, animal sound abstraction, sorting algorithms, and student percentage calculation with exception handling. Each problem includes an objective, code implementation, and expected output. The solutions demonstrate fundamental programming principles including inheritance, polymorphism, and exception handling.

Uploaded by

golu desai
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/ 22

Gaurav joshi MCA-B Roll_no:05

Problem Statement 1. Write a Java Program to input any string and count the number
of occurrences of each Character.

Objective: To develop a Java program that takes a string as input and counts the
occurrences of each character in the string.

Code: import java.util.HashMap;

import java.util.Scanner;

class CharacterFrequency {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

String input = scanner.nextLine().toUpperCase();

HashMap<Character, Integer> charCountMap = new HashMap<>();

for (char ch : input.toCharArray()) {

if (ch != ' ') {

charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1); } }

System.out.println("\nCharacter Frequencies:");

for (char ch : charCountMap.keySet()) {

System.out.println(ch + "=" + charCountMap.get(ch)); }

scanner.close(); } }

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 2. Write a Java program that prints the numbers from 1 to 50.
But for multiples of three print "T" instead of the number and for the multiples of five print
"F". For numbers which are multiples of both three and five print "TF".

Objective: To develop a Java program that prints numbers from 1 to 50 while replacing:
 Multiples of 3 with "T"

 Multiples of 5 with "F"

 Multiples of both 3 and 5 with "TF"

Code: public class MultipleReplacement {


public static void main(String[] args) {

for (int i = 1; i <= 50; i++) {

if (i % 3 == 0 && i % 5 == 0) {

System.out.print("TF ");

} else if (i % 3 == 0) {

System.out.print("T ");

} else if (i % 5 == 0) {

System.out.print("F ");

} else {

System.out.print(i + " ");

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 3. Write a program in Java to perform various string operations.


i. Convert string into integer and vice versa.
ii. Convert string into lower to upper and vice versa.
iii. Extract number of characters from a string.
iv. Compare two string and print the result.
v. Search a substring in a string and replace it with another string.
vi. Count number of vowels, digits, special character, lower and upper alphabets,
words in an input string.

Objective: To develop a Java program that performs various string operations,


demonstrating the use of string manipulation techniques and built-in methods in Java.

Code: import java.util.Scanner;

public class StringOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

String numberStr = scanner.nextLine();

int number = Integer.parseInt(numberStr);

System.out.println("Converted to Integer: " + number);

String convertedStr = String.valueOf(number);

System.out.println("Converted back to String: " + convertedStr);

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

String inputStr = scanner.nextLine();

System.out.println("Uppercase: " + inputStr.toUpperCase());

System.out.println("Lowercase: " + inputStr.toLowerCase());

System.out.println("Number of characters in the string: " + inputStr.length());

System.out.print("Enter another string to compare: ");

String anotherStr = scanner.nextLine();

if (inputStr.equals(anotherStr)) {

System.out.println("Strings are equal.");

} else {

System.out.println("Strings are not equal.");

}
Gaurav joshi MCA-B Roll_no:05

System.out.print("Enter the substring to search: ");

String searchStr = scanner.nextLine();

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

String replaceStr = scanner.nextLine();

String modifiedStr = inputStr.replace(searchStr, replaceStr);

System.out.println("Modified String: " + modifiedStr);

int vowels = 0, digits = 0, specialChars = 0, upperCase = 0, lowerCase = 0, words = 0;

String vowelsList = "AEIOUaeiou";

for (char ch : inputStr.toCharArray()) {

if (Character.isDigit(ch)) digits++;

else if (Character.isUpperCase(ch)) upperCase++;

else if (Character.isLowerCase(ch)) lowerCase++;

else if (!Character.isLetterOrDigit(ch) && ch != ' ') specialChars++;

if (vowelsList.indexOf(ch) != -1) vowels++; }

words = inputStr.trim().split("\\s+").length; // Count words by splitting on spaces

System.out.println("Vowels: " + vowels);

System.out.println("Digits: " + digits);

System.out.println("Special Characters: " + specialChars);

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

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

System.out.println("Words: " + words);

scanner.close();

}
Gaurav joshi MCA-B Roll_no:05

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 4. Define a class employee having the following description:


Data Members Description

Pan To store personal account number

Name To store name

TaxIncome To store annual taxable income

Tax To store tax that is calculated

InputInfo() Store the pan number,name,taxableincome

TaxCalc() Calculate tax for an employee

DisplayInfo() Output details of an employee

Objective: To design a Java class Employee that stores and manages employee tax
details.

Code: import java.util.Scanner;

class Employee {

private String pan;

private String name;

private double taxIncome;

private double tax;

public void InputInfo() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter PAN Number: ");

pan = scanner.nextLine();

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

name = scanner.nextLine();

System.out.print("Enter Annual Taxable Income: ");

taxIncome = scanner.nextDouble();

TaxCalc(); }

public void TaxCalc() {

if (taxIncome <= 250000) {

tax = 0; // No tax
Gaurav joshi MCA-B Roll_no:05

} else if (taxIncome <= 300000) {

tax = (taxIncome - 250000) * 0.10;

} else if (taxIncome <= 400000) {

tax = 5000 + (taxIncome - 300000) * 0.20;

} else {

tax = 25000 + (taxIncome - 400000) * 0.30;

public void DisplayInfo() {

System.out.println("\nEmployee Tax Details:");

System.out.println("PAN Number: " + pan);

System.out.println("Name: " + name);

System.out.println("Annual Taxable Income: " + taxIncome);

System.out.println("Calculated Tax: " + tax);

public class EmployeeTax {

public static void main(String[] args) {

Employee emp = new Employee(); // Create an object of Employee class

emp.InputInfo(); // Take input from user

emp.DisplayInfo(); // Display employee details with tax

}
Gaurav joshi MCA-B Roll_no:05

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 5. Write a Java program to create a class called Shape with
methods called getPeri() and getArea(). Create a subclass called Circle that overrides the
getPeri() and getArea() methods to calculate the perimeter and area of a circle.

Objective: To develop a Java program that demonstrates inheritance and method


overriding by creating a base class Shape with methods for calculating perimeter and area,
and a subclass Circle that overrides these methods to compute the perimeter and area of a
circle.

Code: import java.util.Scanner;

class Shape {

public double getPeri() {

return 0; }

public double getArea() {

return 0;

class Circle extends Shape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double getPeri() {

return 2 * Math.PI * radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

public void display() {

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

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

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


Gaurav joshi MCA-B Roll_no:05

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

public class ShapeDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

double radius = scanner.nextDouble();

Circle circle = new Circle(radius);

circle.display();

scanner.close();

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 6. Write a Java program to create a class known as "Bank" with
methods called deposit() and withdraw(). Create a subclass called CustAccount that
overrides the withdraw() method. Make sure that withdrawal is not possible if balance in the
account is less than Rs. 250.

Objective: To develop a Java program that demonstrates inheritance and method


overriding using a Bank class and its subclass CustAccount.

Code: import java.util.Scanner;

class Bank {

protected double balance;

public Bank(double initialBalance) {

this.balance = initialBalance;

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

System.out.println("Rs" + amount + " deposited successfully.");

} else {

System.out.println("Invalid deposit amount!");

public void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

System.out.println("Rs" + amount + " withdrawn successfully.");

} else {

System.out.println("Insufficient balance or invalid amount!");

public void displayBalance() {

System.out.println("Current Balance: Rs" + balance);


Gaurav joshi MCA-B Roll_no:05

class CustAccount extends Bank {

// Constructor to initialize balance using superclass constructor

public CustAccount(double initialBalance) {

super(initialBalance);

@Override

public void withdraw(double amount) {

if (amount > 0 && (balance - amount) >= 250) {

balance -= amount;

System.out.println("₹" + amount + " withdrawn successfully.");

} else {

System.out.println("Withdrawal failed! Minimum balance of Rs250 must be


maintained.");

public class BankApplication {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter initial deposit amount: ");

double initialDeposit = scanner.nextDouble();

CustAccount customer = new CustAccount(initialDeposit);

int choice;

do {

System.out.println("\n--- Bank Menu ---");

System.out.println("1. Deposit");

System.out.println("2. Withdraw");

System.out.println("3. Check Balance");


Gaurav joshi MCA-B Roll_no:05

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

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

choice = scanner.nextInt();

switch (choice) {

case 1:

System.out.print("Enter deposit amount: ");

double depositAmount = scanner.nextDouble();

customer.deposit(depositAmount);

break;

case 2:

System.out.print("Enter withdrawal amount: ");

double withdrawAmount = scanner.nextDouble();

customer.withdraw(withdrawAmount);

break;

case 3:

customer.displayBalance();

break;

case 4:

System.out.println("Thank you for banking with us!");

break;

default:

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

} while (choice != 4);

scanner.close();

OUTPUT:
Gaurav joshi MCA-B Roll_no:05
Gaurav joshi MCA-B Roll_no:05

Problem Statement 7. Write a Java program to create an abstract class Animal with
an abstract method called sound(). Create subclasses Tiger and Dog that extend the Animal
class and implement the sound() method to make a specific sound for each animal.

Objective: To develop a Java program that demonstrates the concept of abstraction using
abstract classes and methods.

Code: abstract class Animal {

abstract void sound(); }

class Tiger extends Animal {

@Override

void sound() {

System.out.println("Tiger roars!"); }

class Dog extends Animal {

@Override

void sound() {

System.out.println("Dog barks!");

public class AnimalSounds {

public static void main(String[] args) {

Animal tiger = new Tiger();

Animal dog = new Dog();

tiger.sound();

dog.sound();

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 8. Write a Java program to create an interface Sortable with a


method sort (int[] array) that sorts an array of integers. Now create two classes Bubble and
Selection that implement the Sortable interface and provide their own implementations of
the sort() method.

Objective: To develop a Java program that demonstrates the use of interfaces and
polymorphism by implementing different sorting algorithms.

Code: import java.util.Arrays;


interface Sortable {

void sort(int[] array);

class Bubble implements Sortable {

@Override

public void sort(int[] array) {

int n = array.length;

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

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

if (array[j] > array[j + 1]) {

int temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

System.out.println("Sorted using Bubble Sort: " + Arrays.toString(array));

class Selection implements Sortable {

@Override

public void sort(int[] array) {

int n = array.length;

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


Gaurav joshi MCA-B Roll_no:05

int minIndex = i;

for (int j = i + 1; j < n; j++) {

if (array[j] < array[minIndex]) {

minIndex = j;

int temp = array[minIndex];

array[minIndex] = array[i];

array[i] = temp;

System.out.println("Sorted using Selection Sort: " + Arrays.toString(array));

public class SortingExample {

public static void main(String[] args) {

int[] array1 = {64, 34, 25, 12, 22, 11, 90};

int[] array2 = array1.clone(); // Cloning array for different sorting

Sortable bubbleSort = new Bubble();

bubbleSort.sort(array1); // Applying Bubble Sort

Sortable selectionSort = new Selection();

selectionSort.sort(array2); // Applying Selection Sort

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 9. Write a program in Java to calculate the percentage of a


student by taking input max-marks from command line arguments, marks obtained from
user at run time. Now handle all possible exception that can occurred in this program and
display appropriate message accordingly.

Objective: To develop a Java program that calculates the percentage of a student.

Code: import java.util.Scanner;


public class StudentPercentage {

public static void main(String[] args) {

try {

if (args.length == 0) {

throw new IllegalArgumentException("Error: Maximum marks not provided as a


command-line argument.");

int maxMarks = Integer.parseInt(args[0]);

if (maxMarks <= 0) {

throw new IllegalArgumentException("Error: Maximum marks should be greater


than zero.");

Scanner scanner = new Scanner(System.in);

System.out.print("Enter marks obtained: ");

int obtainedMarks = scanner.nextInt();

if (obtainedMarks < 0 || obtainedMarks > maxMarks) {

throw new IllegalArgumentException("Error: Obtained marks must be between 0


and " + maxMarks);

double percentage = ((double) obtainedMarks / maxMarks) * 100;

System.out.println("\nStudent Result:");

System.out.println("Maximum Marks: " + maxMarks);

System.out.println("Marks Obtained: " + obtainedMarks);

System.out.println("Percentage: " + percentage + "%");

scanner.close();
Gaurav joshi MCA-B Roll_no:05

} catch (NumberFormatException e) {

System.out.println("Error: Please enter a valid number for maximum marks.");

} catch (IllegalArgumentException e) {

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

} catch (Exception e) {

System.out.println("An unexpected error occurred: " + e.getMessage());

OUTPUT:
Gaurav joshi MCA-B Roll_no:05

Problem Statement 10. Write a program in Java to accept and print the employee
details during runtime. The details will include employee id, name, designation, dept_ Id. The
program should raise an exception if user inputs incomplete or incorrect data. The entered
value should meet the following conditions:

(i) Employee name should be in uppercase and alphabets only.


(ii) Employee designation should be “Manager”, “Clerk” or “Peon” only.
(iii) Department id should be an integer between 1 and 5. If the above conditions are
not true, then the application should raise an exception and execute statements
from appropriate catch classes.

Objective: To develop a Java program that accepts and validates employee details at
runtime while ensuring proper exception handling.

Code: import java.util.Scanner;


class InvalidEmployeeDataException extends Exception {

public InvalidEmployeeDataException(String message) {

super(message);

class Employee {

private int empId;

private String name;

private String designation;

private int deptId;

public void acceptDetails() throws InvalidEmployeeDataException {

Scanner scanner = new Scanner(System.in);

try {

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

empId = Integer.parseInt(scanner.nextLine());

System.out.print("Enter Employee Name (Uppercase Letters Only): ");

name = scanner.nextLine();

if (!name.matches("[A-Z]+")) {

throw new InvalidEmployeeDataException("Invalid Name! Name should contain


uppercase alphabets only.");
Gaurav joshi MCA-B Roll_no:05

System.out.print("Enter Designation (Manager/Clerk/Peon): ");

designation = scanner.nextLine();

if (!designation.equals("Manager") && !designation.equals("Clerk") && !


designation.equals("Peon")) {

throw new InvalidEmployeeDataException("Invalid Designation! Must be


'Manager', 'Clerk' or 'Peon'.");

System.out.print("Enter Department ID (1-5): ");

deptId = Integer.parseInt(scanner.nextLine());

if (deptId < 1 || deptId > 5) {

throw new InvalidEmployeeDataException("Invalid Department ID! Must be


between 1 and 5.");

} catch (NumberFormatException e) {

throw new InvalidEmployeeDataException("Invalid input! Employee ID and


Department ID must be numbers.");

public void displayDetails() {

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

System.out.println("Employee ID: " + empId);

System.out.println("Name: " + name);

System.out.println("Designation: " + designation);

System.out.println("Department ID: " + deptId);

public class EmployeeManagement {

public static void main(String[] args) {

Employee emp = new Employee();

try {

emp.acceptDetails();
Gaurav joshi MCA-B Roll_no:05

emp.displayDetails();

} catch (InvalidEmployeeDataException e) {

System.out.println("Error: " + e.getMessage());

OUTPUT:

You might also like