0% found this document useful (0 votes)
42 views104 pages

Practical Programs

Java Practical Programs SPPU

Uploaded by

pakask52
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)
42 views104 pages

Practical Programs

Java Practical Programs SPPU

Uploaded by

pakask52
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/ 104

Practical Programs Core Java

Assignment 1:

Practice Set:

1. Write a java Program to check whether given String is


Palindrome or not
→ import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
if (isPalindrome(input)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

2. Write a Java program which accepts three integer values


and prints the maximum and minimum.
→ import java.util.Scanner;
public class MaxMin {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter three integers:");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int max = Math.max(a, Math.max(b, c));
int min = Math.min(a, Math.min(b, c));
System.out.println("Maximum: " + max);
System.out.println("Minimum: " + min);
} }
3. Write a Java program to accept a number from the
command prompt and generate a multiplication table of a
number.
→ public class MultiplicationTable {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a number as a
command line argument.");
return;
}
int number = Integer.parseInt(args[0]);
System.out.println("Multiplication table for " + number +
":");
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number *
i));
}
}
}

4. Write a Java program to display Fibonacci series.


→ import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of terms in the
Fibonacci series:");
int n = scanner.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci series: " + a + " " + b);
for (int i = 2; i < n; i++) {
int next = a + b;
System.out.print(" " + next);
a = b;
b = next;
}
}
}

5. Write a Java program to calculate the sum of digits of a


number.
→ import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scanner.nextInt();
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
System.out.println("Sum of digits: " + sum);
}
}

6. Write a Java program to accept a year and check if it is a


leap year or not.
→ import java.util.Scanner;
public class LeapYearCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a year:");
int year = scanner.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 ==
0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
7. Write a Java program to display characters from A to Z
using a loop.
→ public class DisplayCharacters {
public static void main(String[] args) {
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
}
}
}

8. Write a Java program to accept two numbers using


command line argument and calculate addition, subtraction,
multiplication and division.
→ public class ArithmeticOperations {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers as
command line arguments.");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 * num2));
System.out.println("Division: " + ((num2 != 0) ?
((double)num1 / num2) : "Undefined (division by zero)"));
}
}

9. Write a java Program to calculate the sum of the first and


last digit of a number.
→ import java.util.Scanner;
public class SumFirstLastDigit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scanner.nextInt();
int lastDigit = number % 10;
int firstDigit = number;
while (firstDigit >= 10) {
firstDigit /= 10;
}
int sum = firstDigit + lastDigit;
System.out.println("Sum of first and last digit: " + sum);
}
}
10. Write a java program to calculate the sum of even
numbers from an array.
→ import java.util.Scanner;
public class SumOfEvenNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements in the
array:");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
int sum = 0;
for (int num : array) {
if (num % 2 == 0) {
sum += num;
}
}
System.out.println("Sum of even numbers: " + sum);
}
}
Set A:

1. Write a java Program to check whether a given number is


Prime or Not.
→ import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("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.");
}
}
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;
}
}

2. Write a java Program to display all the perfect numbers


between 1 to n.
→ import java.util.Scanner;
public class PerfectNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (int i = 1; i <= n; i++) {
if (isPerfect(i)) {
System.out.println(i);
}
}
}
public static boolean isPerfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
}

3. Write a java Program to accept employee names from a


user and display it in reverse order.
→ import java.util.Scanner;
public class ReverseEmployeeNames {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of employees:");
int n = scanner.nextInt();
scanner.nextLine();
String[] names = new String[n];
System.out.println("Enter the employee names:");
for (int i = 0; i < n; i++) {
names[i] = scanner.nextLine();
}
System.out.println("Employee names in reverse order:");
for (int i = n - 1; i >= 0; i--) {
System.out.println(names[i]);
}
}
}
4. Write a java program to display all the even numbers from
an array. (Use Command Line arguments)
→ public class EvenNumbers {
public static void main(String[] args) {
System.out.println("Even numbers from the given
array:");
for (String arg : args) {
int number = Integer.parseInt(arg);
if (number % 2 == 0) {
System.out.println(number);
}
}
}
}

5. Write a java program to display the vowels from a given


string
→ import java.util.Scanner;
public class DisplayVowels {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
System.out.println("Vowels in the given string:");
for (char ch : input.toCharArray()) {
if (isVowel(ch)) {
System.out.print(ch + " ");
}
}
}
public static boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch
== 'u';
}
}

Set B:

1. Write a java program to accept city names and display them


in ascending order.
→ import java.util.Arrays;
import java.util.Scanner;
public class SortCities {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of cities:");
int n = scanner.nextInt();
scanner.nextLine();
String[] cities = new String[n];
System.out.println("Enter the city names:");
for (int i = 0; i < n; i++) {
cities[i] = scanner.nextLine();
}
Arrays.sort(cities);
System.out.println("City names in ascending order:");
for (String city : cities) {
System.out.println(city);
}
}
}

2. Write a java program to accept n numbers from a user


store only Armstrong numbers in an array and display it.
→ import java.util.ArrayList;
import java.util.Scanner;
public class ArmstrongNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int n = scanner.nextInt();
ArrayList<Integer> armstrongNumbers = new
ArrayList<>();
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
if (isArmstrong(number)) {
armstrongNumbers.add(number);
}
}
System.out.println("Armstrong numbers:");
for (int num : armstrongNumbers) {
System.out.println(num);
}
}
public static boolean isArmstrong(int num) {
int original = num;
int sum = 0;
int digits = String.valueOf(num).length();
while (num != 0) {
int remainder = num % 10;
sum += Math.pow(remainder, digits);
num /= 10;
}
return sum == original;
}
}
3. Write a java program to search given name into the array,
if it is found then display its index otherwise display
appropriate message.
→ import java.util.Scanner;
public class SearchName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of names:");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline
String[] names = new String[n];
System.out.println("Enter the names:");
for (int i = 0; i < n; i++) {
names[i] = scanner.nextLine();
}
System.out.println("Enter the name to search:");
String searchName = scanner.nextLine();
int index = -1;
for (int i = 0; i < n; i++) {
if (names[i].equalsIgnoreCase(searchName)) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("Name found at index: " + index);
} else {
System.out.println("Name not found.");
}
}
}

4. Write a java program to display following pattern:


5
45
345
2345
12345
→ public class Pattern1 {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
for (int j = i; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
5. Write a java program to display the following pattern.
1
01
010
1010
→ public class Pattern2 {
public static void main(String[] args) {
int rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
if ((i + j) % 2 == 0) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println();
}
}
}
Set C:

1. Write a java program to count the frequency of each


character in a given string.
→ import java.util.HashMap;
import java.util.Scanner;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
HashMap<Character, Integer> frequencyMap = new
HashMap<>();
for (char ch : input.toCharArray()) {
frequencyMap.put(ch, frequencyMap.getOrDefault(ch,
0) + 1);
}
System.out.println("Character frequencies:");
for (char ch : frequencyMap.keySet()) {
System.out.println(ch + ": " + frequencyMap.get(ch));
}
}
}
2. Write a java program to display each word in reverse order
from a string array.
→ import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of words:");
int n = scanner.nextInt();
scanner.nextLine();
String[] words = new String[n];
System.out.println("Enter the words:");
for (int i = 0; i < n; i++) {
words[i] = scanner.nextLine();
}
System.out.println("Words in reverse order:");
for (String word : words) {
System.out.println(new
StringBuilder(word).reverse().toString());
}
}
}
3. Write a java program for union of two integer arrays.
→ import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArrayUnion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements in the
first array:");
int n1 = scanner.nextInt();
int[] array1 = new int[n1];
System.out.println("Enter elements of the first array:");
for (int i = 0; i < n1; i++) {
array1[i] = scanner.nextInt();
}
System.out.println("Enter the number of elements in the
second array:");
int n2 = scanner.nextInt();
int[] array2 = new int[n2];
System.out.println("Enter elements of the second
array:");
for (int i = 0; i < n2; i++) {
array2[i] = scanner.nextInt();
}
Set<Integer> unionSet = new HashSet<>();
for (int num : array1) {
unionSet.add(num);
}
for (int num : array2) {
unionSet.add(num);
}
System.out.println("Union of the two arrays:");
for (int num : unionSet) {
System.out.print(num + " ");
}
}
}

4. Write a java program to display the transpose of a given


matrix.
→ import java.util.Scanner;
public class MatrixTranspose {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of rows and
columns of the matrix:");
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int[][] transpose = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("Transpose of the matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}

5. Write a java program to display alternate character from a


given string
→ import java.util.Scanner;
public class AlternateCharacters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
System.out.println("Alternate characters in the string:");
for (int i = 0; i < input.length(); i += 2) {
System.out.print(input.charAt(i));
}
}
}
Assignment 2:

Practice Set:

1. Write a Java program for the implementation of reference


variables.
→ public class ReferenceExample {
int x = 10;
public static void main(String[] args) {
ReferenceExample ref1 = new ReferenceExample();
ReferenceExample ref2 = ref1;
System.out.println("ref1.x = " + ref1.x);
System.out.println("ref2.x = " + ref2.x);
ref2.x = 20;
System.out.println("After modifying ref2.x:");
System.out.println("ref1.x = " + ref1.x);
System.out.println("ref2.x = " + ref2.x);
}
}

2. Write a Java program to keep the count of objects created


of a class. Display the count each time when the object is
created.
→ public class ObjectCounter {
static int count = 0;
ObjectCounter() {
count++;
System.out.println("Object created, count = " + count);
}
public static void main(String[] args) {
ObjectCounter obj1 = new ObjectCounter();
ObjectCounter obj2 = new ObjectCounter();
ObjectCounter obj3 = new ObjectCounter();
}
}

3. Write a Java program to convert integer primitive data.


(use toString())
→ public class IntToString {
public static void main(String[] args) {
int num = 123;
String str = Integer.toString(num);
System.out.println("String representation: " + str);
}
}

4. Write a Java program to calculate sum of digits of a


number using Recursion
→ public class SumOfDigits {
public static int sumDigits(int n) {
if (n == 0) {
return 0;
} return n % 10 + sumDigits(n / 10);
}
public static void main(String[] args) {
int number = 12345;
int sum = sumDigits(number);
System.out.println("Sum of digits: " + sum);
}
}

5. Write a Java program for the implementation of this


keyword.
→ public class ThisExample {
int a, b;
ThisExample(int a, int b) {
this.a = a;
this.b = b;
}
void display() {
System.out.println("a = " + a + ", b = " + b);
}
public static void main(String[] args) {
ThisExample obj = new ThisExample(10, 20);
obj.display();
}
}

Set A:

1. Write a Java program to calculate power of a number using


recursion
→ public class PowerCalculator {
public static int power(int base, int exp) {
if (exp == 0) {
return 1;
}
return base * power(base, exp - 1);
}
public static void main(String[] args) {
int base = 2;
int exp = 3;
int result = power(base, exp);
System.out.println(base + "^" + exp + " = " + result);
}
}

2. Write a Java program to display Fibonacci series using


function.
→ public class FibonacciSeries {
public static void printFibonacci(int count) {
int n1 = 0, n2 = 1, n3;
System.out.print(n1 + " " + n2);
for (int i = 2; i < count; ++i) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
public static void main(String[] args) {
int count = 10;
System.out.print("Fibonacci series: ");
printFibonacci(count);
}
}

3. Write a Java program to calculate area of Circle, Trangle &


Rectangle (Use Method Overloading)
→ public class AreaCalculator {
static double area(double radius) {
return Math.PI * radius * radius;
}
static double area(double base, double height) {
return 0.5 * base * height;
}
static double area(double length, double width) {
return length * width;
}
public static void main(String[] args) {
System.out.println("Area of Circle: " + area(7));
System.out.println("Area of Triangle: " + area(5, 10));
System.out.println("Area of Rectangle: " + area(4, 6));
}
}

4. Write a Java program to Copy data of one object to


another Object
→ public class CopyObject {
int data;
CopyObject(int data) {
this.data = data;
}
CopyObject(CopyObject obj) {
this.data = obj.data;
}
public static void main(String[] args) {
CopyObject obj1 = new CopyObject(100);
CopyObject obj2 = new CopyObject(obj1);
System.out.println("Data in obj1: " + obj1.data);
System.out.println("Data in obj2: " + obj2.data);
}
}

5. Write a Java program to calculate factorial of a number


using recursion.
→ public class FactorialCalculator {
public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is " +
result);
}
}
Set B:

1. Define a class person(pid,pname,age,gender). Define Default


and parameterized constructor. Overload the constructor.
Accept the 5 person details and display it. (use this keyword)
→ import java.util.Scanner;
public class Person {
int pid;
String pname;
int age;
String gender;
Person() {
this.pid = 0;
this.pname = "Unknown";
this.age = 0;
this.gender = "Unknown";
}
Person(int pid, String pname, int age, String gender) {
this.pid = pid;
this.pname = pname;
this.age = age;
this.gender = gender;
}
void display() {
System.out.println("PID: " + pid + ", Name: " + pname + ",
Age: " + age + ", Gender: " + gender);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Person[] persons = new Person[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter details for person " + (i +
1));
System.out.print("PID: ");
int pid = sc.nextInt();
sc.nextLine();
System.out.print("Name: ");
String pname = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
sc.nextLine();
System.out.print("Gender: ");
String gender = sc.nextLine();
persons[i] = new Person(pid, pname, age, gender);
}
for (Person person : persons) {
person.display();
}
sc.close();
}
}

2. Define a class product(pid.pname,price). Write a function to


accept the product details, to display product details and to
calculate total amount. (use array of Objects)
→ import java.util.Scanner;
class Product {
int pid;
String pname;
double price;
Product(int pid, String pname, double price) {
this.pid = pid;
this.pname = pname;
this.price = price;
}
void display() {
System.out.println("PID: " + pid + ", Name: " + pname + ",
Price: " + price);
}
static double calculateTotalAmount(Product[] products) {
double total = 0;
for (Product product : products) {
total += product.price;
}
return total;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of products: ");
int n = sc.nextInt();
sc.nextLine();
Product[] products = new Product[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter details for product " + (i +
1));
System.out.print("PID: ");
int pid = sc.nextInt();
sc.nextLine();
System.out.print("Name: ");
String pname = sc.nextLine();
System.out.print("Price: ");
double price = sc.nextDouble();
products[i] = new Product(pid, pname, price);
}
for (Product product : products) {
product.display();
}
double totalAmount = calculateTotalAmount(products);
System.out.println("Total amount: " + totalAmount);
sc.close();
}
}

3. Define a class Student(rollnojame.per). Create n objects of


the student class and Display using toString() (Use
parameterized constructor)
→ import java.util.Scanner;
class Student {
int rollno;
String name;
double per;
Student(int rollno, String name, double per) {
this.rollno = rollno;
this.name = name;
this.per = per;
}
public String toString() {
return "Roll No: " + rollno + ", Name: " + name + ",
Percentage: " + per;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine();
Student[] students = new Student[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter details for student " + (i +
1));
System.out.print("Roll No: ");
int rollno = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Percentage: ");
double per = sc.nextDouble();
students[i] = new Student(rollno, name, per);
}
for (Student student : students) {
System.out.println(student);
}
sc.close();
}
}

4. Define a class MyNumber having one private integer data


member. Write a default constructor to initialize it to D and
another constructor to initialize it to a value. Write methods
isNegative, isPositive. Use command line argument to pass a
value to the object and perform the above tests
→ public class MyNumber {
private int number;
MyNumber() {
this.number = 0;
}
MyNumber(int number) {
this.number = number;
}
boolean isNegative() {
return number < 0;
}
boolean isPositive() {
return number > 0;
}
public static void main(String[] args) {
if (args.length > 0) {
int num = Integer.parseInt(args[0]);
MyNumber myNum = new MyNumber(num);
System.out.println("Number: " + num);
System.out.println("Is Negative: " +
myNum.isNegative());
System.out.println("Is Positive: " +
myNum.isPositive());
} else {
System.out.println("Please pass a number as command
line argument.");
}
}
}

Set C:

1. Define class Student(rno, name, mark1, mark2). Define


Result class (total, percentage) inside the student class.
Accept the student details & display the mark sheet with rno,
name, mark1, mark2, total, percentage (Use inner class
concept)
→ import java.util.Scanner;
public class Student {
int rno;
String name;
int mark1, mark2;
public Student(int rno, String name, int mark1, int mark2) {
this.rno = rno;
this.name = name;
this.mark1 = mark1;
this.mark2 = mark2;
}
class Result {
int total;
double percentage;
Result() {
total = mark1 + mark2;
percentage = total / 2.0;
}
void displayResult() {
System.out.println("Roll No: " + rno);
System.out.println("Name: " + name);
System.out.println("Mark 1: " + mark1);
System.out.println("Mark 2: " + mark2);
System.out.println("Total: " + total);
System.out.println("Percentage: " + percentage);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter roll number: ");
int rno = sc.nextInt();
sc.nextLine();
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter mark 1: ");
int mark1 = sc.nextInt();
System.out.print("Enter mark 2: ");
int mark2 = sc.nextInt();
Student student = new Student(rno, name, mark1,
mark2);
Student.Result result = student.new Result();
result.displayResult();
sc.close(); } }

2. Write a java program to accept n employee names from


users. Son them in ascending order and Display them (Use
array of object and Static keyword)
→ import java.util.Arrays;
import java.util.Scanner;
class Employee {
String name;
Employee(String name) {
this.name = name;
}
public String getName() {
return name; }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of employees: ");
int n = sc.nextInt();
sc.nextLine();
Employee[] employees = new Employee[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter name of employee " + (i + 1) +
": ");
String name = sc.nextLine();
employees[i] = new Employee(name);
}
Arrays.sort(employees, (e1, e2) ->
e1.getName().compareTo(e2.getName()));
System.out.println("Sorted Employee Names:");
for (Employee employee : employees) {
System.out.println(employee.getName());
}
sc.close();
}
}

3. Write a java program to accept details of 'n' cricket


players(pid,pname,totalRuns,InningsPlayed,NotOuttimes).
Calculate the average of all the players. Display the details of
player having maximum average
→ import java.util.Scanner;
class Player {
int pid;
String pname;
int totalRuns;
int inningsPlayed;
int notOutTimes;
double average;
Player(int pid, String pname, int totalRuns, int inningsPlayed,
int notOutTimes) {
this.pid = pid;
this.pname = pname;
this.totalRuns = totalRuns;
this.inningsPlayed = inningsPlayed;
this.notOutTimes = notOutTimes;
this.average = calculateAverage();
}
double calculateAverage() {
return (double) totalRuns / (inningsPlayed -
notOutTimes);
}
@Override
public String toString() {
return "Player ID: " + pid + ", Name: " + pname + ",
Average: " + average;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of players: ");
int n = sc.nextInt();
sc.nextLine();
Player[] players = new Player[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter details for player " + (i + 1));
System.out.print("Player ID: ");
int pid = sc.nextInt();
sc.nextLine();
System.out.print("Name: ");
String pname = sc.nextLine();
System.out.print("Total Runs: ");
int totalRuns = sc.nextInt();
System.out.print("Innings Played: ");
int inningsPlayed = sc.nextInt();
System.out.print("Not Out Times: ");
int notOutTimes = sc.nextInt();
players[i] = new Player(pid, pname, totalRuns,
inningsPlayed, notOutTimes);
}
Player maxAvgPlayer = players[0];
for (Player player : players) {
if (player.average > maxAvgPlayer.average) {
maxAvgPlayer = player;
}
}
System.out.println("Player with highest average: " +
maxAvgPlayer);
sc.close();
}
}

4. Write a java program to accept details of 'n' books. And


Display the quantity of given book
→ import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Book {
String title;
int quantity;

Book(String title, int quantity) {


this.title = title;
this.quantity = quantity;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of books: ");
int n = sc.nextInt();
sc.nextLine();
Map<String, Book> books = new HashMap<>();
for (int i = 0; i < n; i++) {
System.out.print("Enter title of book " + (i + 1) + ": ");
String title = sc.nextLine();
System.out.print("Enter quantity: ");
int quantity = sc.nextInt();
sc.nextLine();
books.put(title, new Book(title, quantity));
}
System.out.print("Enter title of book to search: ");
String searchTitle = sc.nextLine();
Book book = books.get(searchTitle);
if (book != null) {
System.out.println("Quantity of " + searchTitle + ": " +
book.quantity);
} else {
System.out.println("Book not found.");
}
sc.close();
}
}
Assignment 3:

Practice Set:

1. Create abstract class Shape with abstract method area().


Write a Java program to calculate area of Rectangle and
Triangle (Inherit Shape class in classes Rectangle and
Triangle)
→ abstract class Shape {
abstract double area();
}
class Rectangle extends Shape {
private double length;
private double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
}
class Triangle extends Shape {
private double base;
private double height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double area() {
return 0.5 * base * height;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 4);
System.out.println("Area of Rectangle: " +
rectangle.area());
Triangle triangle = new Triangle(3, 6);
System.out.println("Area of Triangle: " + triangle.area());
}
}

2. Create a class Teacher (Tid, Tname, Designation, Salary,


Subject). Write a Java program to accept the details of 'n'
teachers and display the details of the teacher who is
teaching Java Subject. (Use an array of Objects)
→ import java.util.Scanner;
class Teacher {
private int tid;
private String tname;
private String designation;
private double salary;
private String subject;
Teacher(int tid, String tname, String designation, double
salary, String subject) {
this.tid = tid;
this.tname = tname;
this.designation = designation;
this.salary = salary;
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void display() {
System.out.println("Teacher ID: " + tid);
System.out.println("Name: " + tname);
System.out.println("Designation: " + designation);
System.out.println("Salary: " + salary);
System.out.println("Subject: " + subject);
System.out.println("------------------------");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of teachers: ");
int n = scanner.nextInt();
scanner.nextLine();
Teacher[] teachers = new Teacher[n];
for (int i = 0; i < n; i++) {
System.out.println("\nEnter details for Teacher " + (i
+ 1) + ":");
System.out.print("Teacher ID: ");
int tid = scanner.nextInt();
scanner.nextLine();
System.out.print("Name: ");
String tname = scanner.nextLine();
System.out.print("Designation: ");
String designation = scanner.nextLine();
System.out.print("Salary: ");
double salary = scanner.nextDouble();
scanner.nextLine();
System.out.print("Subject: ");
String subject = scanner.nextLine();
teachers[i] = new Teacher(tid, tname, designation,
salary, subject);
}

System.out.println("\nDetails of teachers teaching Java


subject:");
for (Teacher teacher : teachers) {
if (teacher.getSubject().equalsIgnoreCase("Java")) {
teacher.display();
}
}
scanner.close();
}
}

3. Create a class Doctor(Dno, Dname, Qualification,


Specialization). Write a Java program to accept the details of
'n' doctors and display the details of the doctor in ascending
order by doctor name.
→ import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
class Doctor {
private int dno;
private String dname;
private String qualification;
private String specialization;
Doctor(int dno, String dname, String qualification, String
specialization) {
this.dno = dno;
this.dname = dname;
this.qualification = qualification;
this.specialization = specialization;
}

public String getDname() {


return dname;
}

public void display() {


System.out.println("Doctor Number: " + dno);
System.out.println("Name: " + dname);
System.out.println("Qualification: " + qualification);
System.out.println("Specialization: " + specialization);
System.out.println("------------------------");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of doctors: ");
int n = scanner.nextInt();
scanner.nextLine();
ArrayList<Doctor> doctors = new ArrayList<>();
for (int i = 0; i < n; i++) {
System.out.println("\nEnter details for Doctor " + (i +
1) + ":");
System.out.print("Doctor Number: ");
int dno = scanner.nextInt();
scanner.nextLine(); // Consume newline character
System.out.print("Name: ");
String dname = scanner.nextLine();
System.out.print("Qualification: ");
String qualification = scanner.nextLine();
System.out.print("Specialization: ");
String specialization = scanner.nextLine();
doctors.add(new Doctor(dno, dname, qualification,
specialization));
}
Collections.sort(doctors,
Comparator.comparing(Doctor::getDname));
System.out.println("\nDetails of doctors in ascending
order by name:");
for (Doctor doctor : doctors) {
doctor.display();
}
scanner.close();
}
}

4. Write a Java program to accept 'n' employee names


through command line, Store them in vector. Display the name
of employees starting with character 'S'
→ import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> employees = new Vector<>();
for (String arg : args) {
employees.add(arg);
}
System.out.println("Employee names starting with 'S':");
for (String employee : employees) {
if (employee.startsWith("S")) {
System.out.println(employee);
}
}
}
}
5. Create a package Mathematics with two classes Maximum
and Power. Write a java program to accept two numbers from
the user and perform the following operations on it
a. Find the maximum of two numbers.
b. Calculate the power(X);
→ package mathematics;
public class Maximum {
public static int findMaximum(int a, int b) {
return Math.max(a, b);
}
}
package mathematics;
public class Power {
public static double calculatePower(int base, int exponent) {
return Math.pow(base, exponent);
}
}
import mathematics.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
int max = Maximum.findMaximum(num1, num2);
System.out.println("Maximum of " + num1 + " and " + num2
+ " is: " + max);
System.out.print("Enter base number: ");
int base = scanner.nextInt();
System.out.print("Enter exponent number: ");
int exponent = scanner.nextInt();
double result = Power.calculatePower(base, exponent);
System.out.println(base + " raised to the power " +
exponent + " is: " + result);
scanner.close();
}
}

Set A:

1. Write a java program to calculate the area of Cylinder and


Circle. (Use super keywords)
→ class Cylinder {
double radius;
double height;
Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
double calculateArea() {
return 2 * Math.PI * radius * (radius + height);
}
}
class Circle extends Cylinder {
Circle(double radius) {
super(radius, 0);
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}

2. Define in Interface Shape with abstract method area().


Write a java program to calculate on area of Circle and
Sphere (use final keyword)
→ interface Shape {
double area();
}
class Circle implements Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
class Sphere implements Shape {
double radius;
Sphere(double radius) {
this.radius = radius;
}
@Override
public double area() {
return 4 * Math.PI * radius * radius;
} }
3. Define an Interface “Integer” with a abstract method
(checkt) Write a Java program to check whether a given
number is Positive or Negative
→ interface Integer {
void check(int number);
}
class NumberChecker implements Integer {
@Override
public void check(int number) {
if (number >= 0) {
System.out.println(number + " is Positive");
} else {
System.out.println(number + " is Negative");
}
}
}

4. Define a class Student with attributes rollno and name.


Define default and parameterized constructor. Override the
toString() method. Keep the count of Objects created. Create
objects using parameterized constructor and Display the
object count after cach object is created
→ class Student {
private int rollNo;
private String name;
private static int objectCount = 0;
public Student() {
objectCount++;
this.rollNo = 0;
this.name = "";
}
public Student(int rollNo, String name) {
objectCount++;
this.rollNo = rollNo;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"rollNo=" + rollNo +
", name='" + name + '\'' +
'}';
}
public static int getObjectCount() {
return objectCount;
}
}

5. Write a java program to accept 'n' integers from the user


& store them in an ArrayList collection. Display the elements
of the ArrayList collection in reverse order.
→ import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
int n = scanner.nextInt();
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();
list.add(num);
}
System.out.println("Elements in reverse order:");
Collections.reverse(list);
System.out.println(list);
scanner.close();
}
}

Set B:

1. Create an abstract class Shape with methods cale area() &


cale volume(). Derive two classes Sphere(radius)& Cone(radius,
height) from it. Calculate area and volume of both (Use
Method Overriding)
→ abstract class Shape {
abstract double calculateArea();
abstract double calculateVolume();
}
class Sphere extends Shape {
double radius;
Sphere(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return 4 * Math.PI * radius * radius;
}
@Override
double calculateVolume() {
return (4.0 / 3) * Math.PI * radius * radius * radius;
}
}
class Cone extends Shape {
double radius;
double height;
Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
double calculateArea() {
return Math.PI * radius * (radius + Math.sqrt(radius *
radius + height * height));
}
@Override
double calculateVolume() {
return (1.0 / 3) * Math.PI * radius * radius * height;
}
}

2. Define a class Employee having private members-id, name,


departinent, salary. Define default & parameterized
constructors. Create a subclass called Manager with a private
member bonus. Define methods accept & display in both the
classes. Create n objects of the manager class & display the
details of the manager having the maximum total
salary(salary+bonus).
→ class Employee {
private int id;
private String name;
private String department;
private double salary;
Employee(int id, String name, String department, double
salary) {
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: " + salary);
}
}
class Manager extends Employee {
private double bonus;

Manager(int id, String name, String department, double


salary, double bonus) {
super(id, name, department, salary);
this.bonus = bonus;
}
@Override
void display() {
super.display();
System.out.println("Bonus: " + bonus);
}
double getTotalSalary() {
return super.salary + bonus;
}
}

3. Construct a Linked List containing names, CPP, Java, Python


and PHP. Then extend your program to do the following:
i. Display the contents of the List using an iterator
ii. Display the contents of the List in reverse order using a
ListIterator.
→ import java.util.LinkedList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("CPP");
list.add("Java");
list.add("Python");
list.add("PHP");
System.out.println("Contents using iterator:");
for (String name : list) {
System.out.println(name);
}
System.out.println("Contents in reverse using
ListIterator:");
ListIterator<String> iterator =
list.listIterator(list.size());
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
}

4. Create a hashtable containing employee name & salary.


Display the details of the hashtable. Also search for a
specific Employee and display the salary of that employee.
→ import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, Double> hashtable = new Hashtable<>();
hashtable.put("Alice", 50000.0);
hashtable.put("Bob", 60000.0);
hashtable.put("Charlie", 55000.0);
System.out.println("Hashtable details:");
for (String name : hashtable.keySet()) {
System.out.println("Name: " + name + ", Salary: " +
hashtable.get(name));
}
String searchName = "Bob";
if (hashtable.containsKey(searchName)) {
System.out.println(searchName + "'s salary is " +
hashtable.get(searchName));
} else {
System.out.println(searchName + " not found in the
hashtable.");
}
}
}

5. Write a package game which will have 2 classes indoor &


Outdoor. Use a function display() to generate the list of
players for the specific game. Use default & parameterized
constructor.
→ package game;
public class Indoor {
private String[] players;
public Indoor() {
this.players = new String[]{"Player1", "Player2",
"Player3"};
}
public Indoor(String... players) {
this.players = players;
}
public void display() {
System.out.println("Indoor players:");
for (String player : players) {
System.out.println(player);
}
}
}
package game;
public class Outdoor {
private String[] players;
public Outdoor() {
this.players = new String[]{"Player4", "Player5",
"Player6"};
}
public Outdoor(String... players) {
this.players = players;
}
public void display() {
System.out.println("Outdoor players:");
for (String player : players) {
System.out.println(player);
}
}
}

Set C:
1. Create a hashtable containing city name & STD code. Display
the details of the hashtable. Also search for a specific city
and display the STD code of that city.
→ import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable<String, Integer> hashtable = new
Hashtable<>();
hashtable.put("New York", 212);
hashtable.put("London", 20);
hashtable.put("Tokyo", 81);
System.out.println("Hashtable details:");
for (String city : hashtable.keySet()) {
System.out.println("City: " + city + ", STD Code: " +
hashtable.get(city));
}

String searchCity = "London";


if (hashtable.containsKey(searchCity)) {
System.out.println(searchCity + "'s STD Code is " +
hashtable.get(searchCity));
} else {
System.out.println(searchCity + " not found in the
hashtable.");
}
}
}

2. Construct a Linked List containing name: red, blue, yellow


and orange. Then extend your program to do the following:
Display the contents of the List using an iterator
Display the contents of the List in reverse order using a
ListIterator.
Create another list containing pink & green. Insert the
elements of this list between blue & yellow.
→ import java.util.LinkedList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("red");
list.add("blue");
list.add("yellow");
list.add("orange");
System.out.println("Contents using iterator:");
for (String color : list) {
System.out.println(color);
}
System.out.println("Contents in reverse using
ListIterator:");
ListIterator<String> iterator =
list.listIterator(list.size());
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
LinkedList<String> additionalList = new LinkedList<>();
additionalList.add("pink");
additionalList.add("green");
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (listIterator.next().equals("blue")) {
for (String color : additionalList) {
listIterator.add(color);
}
break;
}
}
System.out.println("Modified list:");
for (String color : list) {
System.out.println(color);
}
}
}
3. Define an abstract class Staff with members name &
address. Define two sab classes FullTimeStaff(Department,
Salary) and PartTimeStaff(numberOfHours, rate Per Hour).
Define appropriate constructors. Create objects which could
be of either FullTimeStaff or PartTimeStaff class by asking
the user's choice. Display details of FulltimeStaff and
PartTimeStaff.
→ abstract class Staff {
String name;
String address;
Staff(String name, String address) {
this.name = name;
this.address = address;
}
}
class FullTimeStaff extends Staff {
String department;
double salary;
FullTimeStaff(String name, String address, String
department, double salary) {
super(name, address);
this.department = department;
this.salary = salary;
}
void display() {
System.out.println("Full-Time Staff:");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Department: " + department);
System.out.println("Salary: " + salary);
}
}
class PartTimeStaff extends Staff {
int numberOfHours;
double ratePerHour;
PartTimeStaff(String name, String address, int
numberOfHours, double ratePerHour) {
super(name, address);
this.numberOfHours = numberOfHours;
this.ratePerHour = ratePerHour;
}
void display() {
System.out.println("Part-Time Staff:");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Number of Hours: " +
numberOfHours);
System.out.println("Rate per Hour: " + ratePerHour);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter type of staff (1. Full-Time, 2.
Part-Time): ");
int type = scanner.nextInt();
scanner.nextLine();
switch (type) {
case 1:
System.out.print("Enter name: ");
String ftName = scanner.nextLine();
System.out.print("Enter address: ");
String ftAddress = scanner.nextLine();
System.out.print("Enter department: ");
String department = scanner.nextLine();
System.out.print("Enter salary: ");
double salary = scanner.nextDouble();
FullTimeStaff fullTimeStaff = new
FullTimeStaff(ftName, ftAddress, department, salary);
fullTimeStaff.display();
break;
case 2:
System.out.print("Enter name: ");
String ptName = scanner.nextLine();
System.out.print("Enter address: ");
String ptAddress = scanner.nextLine();
System.out.print("Enter number of hours: ");
int hours = scanner.nextInt();
System.out.print("Enter rate per hour: ");
double rate = scanner.nextDouble();
PartTimeStaff partTimeStaff = new
PartTimeStaff(ptName, ptAddress, hours, rate);
partTimeStaff.display();
break;
default:
System.out.println("Invalid choice");
}
scanner.close();
}
}

4. Derive a class Square from class Rectangle. Create one


more class Circle. Create an interface with only one method
called area(). Implement this interface in all classes Include
appropriate data members and constructors in all classes.
Write a java program to accept details of Square, Circle &
Rectangle and display the area.
→ interface Shape {
double area();
}
class Rectangle implements Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double area() {
return length * width;
}
}
class Square extends Rectangle {
Square(double side) {
super(side, side);
}
}
class Circle implements Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Square square = new Square(5);
Circle circle = new Circle(3);
System.out.println("Area of Square: " + square.area());
System.out.println("Area of Circle: " + circle.area());
}
}

5. Create a package named Series having three different


classes to print series:
i. Fibonacci series
ii. Cube of numbers
iii. Square of numbers
Write a java program to generate 'n' terms of the above
series.
→ package Series;
public class Fibonacci {
public static void generateSeries(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series of " + n + " terms:");
for (int i = 0; i < n; i++) {
System.out.print(" " + a);
int next = a + b;
a = b;
b = next;
}
System.out.println();
}
}
package Series;
public class Cube {
public static void generateSeries(int n) {
System.out.print("Cube Series of " + n + " terms:");
for (int i = 1; i <= n; i++) {
System.out.print(" " + (i * i * i));
}
System.out.println();
}
}
package Series;
public class Square {
public static void generateSeries(int n) {
System.out.print("Square Series of " + n + " terms:");
for (int i = 1; i <= n; i++) {
System.out.print(" " + (i * i));
}
System.out.println();
}
}
import Series.*;
public class Main {
public static void main(String[] args) {
int n = 5;
Fibonacci.generateSeries(n);
Cube.generateSeries(n);
Square.generateSeries(n);
}
}
Assignment 4:

Practice Set:

1. Write a java program to accept the data from a user and


write it into the file
→ import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteToFile {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter data to write into file: ");
String data = scanner.nextLine();
FileWriter writer = new FileWriter("output.txt");
writer.write(data);
writer.close();
System.out.println("Data written to file
successfully.");
scanner.close();
} catch (IOException e) {
System.out.println("Error writing to file: " +
e.getMessage());
}
}
}

2. Write a java program to display ASCII values of the


characters from a file.
→ import java.io.FileReader;
import java.io.IOException;
public class ASCIIValuesFromFile {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.println("Character: " + (char) character
+ ", ASCII value: " + character);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " +
e.getMessage());
}
}
}
3. Write a java program to count the number of digits, spaces
and characters from a file.
→ import java.io.FileReader;
import java.io.IOException;
public class CountFromFile {
public static void main(String[] args) {
int digitCount = 0, spaceCount = 0, charCount = 0;
try {
FileReader reader = new FileReader("input.txt");
int character;
while ((character = reader.read()) != -1) {
if (Character.isDigit(character)) {
digitCount++;
} else if (Character.isWhitespace(character)) {
spaceCount++;
} else {
charCount++;
}
}
reader.close();
System.out.println("Digits: " + digitCount);
System.out.println("Spaces: " + spaceCount);
System.out.println("Characters: " + charCount);
} catch (IOException e) {
System.out.println("Error reading from file: " +
e.getMessage());
}
}
}

4. Write a java program to accept a number from user if it is


non-zero then check whether it is Armstrong or not,
otherwise throws user defined Exception "Number is Invalid"
→ import java.util.Scanner;
class InvalidNumberException extends Exception {
InvalidNumberException(String message) {
super(message);
}
}
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();
try {
if (number == 0) {
throw new InvalidNumberException("Number is
Invalid");
}
int originalNumber = number;
int sum = 0;
int digits = String.valueOf(number).length();
while (number != 0) {
int remainder = number % 10;
sum += Math.pow(remainder, digits);
number /= 10;
}
if (sum == originalNumber) {
System.out.println(originalNumber + " is an
Armstrong number.");
} else {
System.out.println(originalNumber + " is not an
Armstrong number.");
}
} catch (InvalidNumberException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
scanner.close();
}
}
}
5. Write a java program to check whether a given file is
hidden or not.
→ import java.io.File;
public class CheckFileHidden {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.isHidden()) {
System.out.println(file.getName() + " is hidden.");
} else {
System.out.println(file.getName() + " is not hidden.");
}
}
}

6. Write a java program to display the name and size of the


given files.
→ import java.io.File;
public class DisplayFileNameAndSize {
public static void main(String[] args) {
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
System.out.println("File name: " + file1.getName() + ",
Size: " + file1.length() + " bytes");
System.out.println("File name: " + file2.getName() + ",
Size: " + file2.length() + " bytes"); } }
Set A:

1. Write a java program to count the number of integers from


a given list. (Use command line arguments).
→ public class CountIntegers {
public static void main(String[] args) {
System.out.println("Number of integers: " + args.length);
}
}

2. Write a java program to check whether a given candidate is


eligible for voting or not. Handle user defined as well as
system defined Exception.
→ import java.util.Scanner;
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class EligibilityForVoting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter candidate's age: ");
int age = scanner.nextInt();
try {
if (age < 18) {
throw new InvalidAgeException("Candidate is not
eligible for voting.");
} else {
System.out.println("Candidate is eligible for
voting.");
}
} catch (InvalidAgeException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
scanner.close();
}
}
}

3. Write a java program to calculate the size of a file.


→ import java.io.File;
public class FileSize {
public static void main(String[] args) {
File file = new File("example.txt");
long fileSize = file.length();
System.out.println("File size: " + fileSize + " bytes");
}
}
4. Write a java program to accept a number from a user, if it
is zero then throw user defined Exception "Number is Zero".
If it is non-numeric then generate an error "Number is Invalid
otherwise check whether it is palindrome or not.
→ import java.util.Scanner;
class ZeroNumberException extends Exception {
ZeroNumberException(String message) {
super(message);
}
}
class NonNumericException extends Exception {
NonNumericException(String message) {
super(message);
}
}
public class NumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scanner.nextLine();
try {
int number = Integer.parseInt(input);
if (number == 0) {
throw new ZeroNumberException("Number is
Zero");
} else if (!input.matches("[0-9]+")) {
throw new NonNumericException("Number is
Invalid");
} else {
if (isPalindrome(input)) {
System.out.println("Number is a palindrome.");
} else {
System.out.println("Number is not a
palindrome.");
}
}
} catch (NumberFormatException e) {
System.out.println("Exception: " + e.getMessage());
} catch (ZeroNumberException | NonNumericException
e) {
System.out.println("Exception: " + e.getMessage());
} finally {
scanner.close();
}
}
private static boolean isPalindrome(String str) {
StringBuilder reverse = new StringBuilder(str).reverse();
return str.equals(reverse.toString());
}
}
5. Write a java program to accept a number from a user, If it
is greater than 100 then throw a user defined exception
"Number is out of Range" otherwise do the addition of digits
of that number. (Use static keyword)
→ import java.util.Scanner;
class OutOfRangeException extends Exception {
OutOfRangeException(String message) {
super(message);
}
}
public class NumberRangeCheck {
static int sumOfDigits(int number) {
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
try {
if (number > 100) {
throw new OutOfRangeException("Number is out of
Range");
}
int sum = sumOfDigits(number);
System.out.println("Sum of digits: " + sum);
} catch (OutOfRangeException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
scanner.close();
}
}
}

Set B:

1. Write a java program to copy the data front: one file into
another file, while copying change the case of characters in
target file and replaces all digits by “*" symbol.
→ import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFileChangeCase {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("source.txt");
FileWriter writer = new FileWriter("target.txt");
int character;
while ((character = reader.read()) != -1) {
if (Character.isUpperCase(character)) {
writer.write(Character.toLowerCase(character));
} else if (Character.isLowerCase(character)) {
writer.write(Character.toUpperCase(character));
} else if (Character.isDigit(character)) {
writer.write('*');
} else {
writer.write(character);
}
}
reader.close();
writer.close();
System.out.println("File copied successfully with case
change and digit replacement.");
} catch (IOException e) {
System.out.println("Error copying file: " +
e.getMessage());
}
}
}
2. Write a java program to accept strings from a user. Write
ASCII values of the characters from a string into the file.
→ import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteASCIIValuesToFile {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
FileWriter writer = new FileWriter("output.txt");
for (int i = 0; i < input.length(); i++) {
int ascii = (int) input.charAt(i);
writer.write(ascii + " ");
}
writer.close();
scanner.close();
System.out.println("ASCII values written to file
successfully.");
} catch (IOException e) {
System.out.println("Error writing to file: " +
e.getMessage());
}
} }
3. Write a java program to accept a number from a user, if it
is less than 5 then throw user defined Exception "Number is
small", if it is greater than 10 then throw user defined
exception "Number is Greater", otherwise calculate its
factorial.
→ import java.util.Scanner;
class SmallNumberException extends Exception {
SmallNumberException(String message) {
super(message);
}
}
class GreaterNumberException extends Exception {
GreaterNumberException(String message) {
super(message);
}
}
public class NumberFactorial {
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
try {
if (number < 5) {
throw new SmallNumberException("Number is
small");
} else if (number > 10) {
throw new GreaterNumberException("Number is
greater");
} else {
int fact = factorial(number);
System.out.println("Factorial of " + number + " is: "
+ fact);
}
} catch (SmallNumberException |
GreaterNumberException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
scanner.close();
}
}
}
4. Write a java program to display contents of a file in
reverse order.
→ import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class ReverseFileContent {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt");
Stack<Character> stack = new Stack<>();
int character;
while ((character = reader.read()) != -1) {
stack.push((char) character);
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " +
e.getMessage());
}
}
}
5. Write a java program to display each word from a file in
reverse order.
→ import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
import java.util.StringTokenizer;
public class ReverseWordsInFile {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("input.txt");
BufferedReader bufferedReader = new
BufferedReader(fileReader);
String line;
Stack<String> wordsStack = new Stack<>();
while ((line = bufferedReader.readLine()) != null) {
StringTokenizer tokenizer = new
StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
wordsStack.push(tokenizer.nextToken());
}
}

while (!wordsStack.isEmpty()) {
System.out.print(wordsStack.pop() + " ");
}
fileReader.close();
bufferedReader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " +
e.getMessage());
}
}
}

Set C:

1. Write a java program to accept a list of file names through


the command line. Delete the files having extension txt.
Display name, location and size of remaining files.
→ import java.io.File;
public class DeleteTextFiles {
public static void main(String[] args) {
for (String fileName : args) {
File file = new File(fileName);
if (file.isFile() && fileName.endsWith(".txt")) {
if (file.delete()) {
System.out.println(file.getName() + " deleted
successfully.");
} else {
System.out.println("Failed to delete " +
file.getName());
}
} else {
System.out.println(fileName + " is not a valid text
file.");
}
}
System.out.println("Remaining files:");
File currentDir = new File(".");
File[] files = currentDir.listFiles();
for (File file : files) {
if (file.isFile()) {
System.out.println("Name: " + file.getName() + ",
Location: " + file.getAbsolutePath() + ", Size: " + file.length() +
" bytes");
}
}
}
}

2. Write a java program to display the files having extension


txt from a given directory.
→ import java.io.File;
public class DisplayTextFiles {
public static void main(String[] args) {
File directory = new File("directory_path");
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".txt")) {
System.out.println(file.getName());
}
}
} else {
System.out.println("Directory does not exist or is not
accessible.");
}
}
}

3. Write a java program to count the number of lines, words


and characters from a given file.
→ import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CountFileDetails {
public static void main(String[] args) {
int lineCount = 0, wordCount = 0, charCount = 0;
try {
FileReader fileReader = new FileReader("input.txt");
BufferedReader bufferedReader = new
BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
lineCount++;
charCount += line.length();
StringTokenizer tokenizer = new
StringTokenizer(line);
wordCount += tokenizer.countTokens();
}
System.out.println("Lines: " + lineCount);
System.out.println("Words: " + wordCount);
System.out.println("Characters: " + charCount);
fileReader.close();
bufferedReader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " +
e.getMessage());
}
}
}
4. Write a java program to read the characters from a file, if
a character is alphabet then reverse its case, if not then
display its category on the Screen. (whether it is Digit or
Space)
→ import java.io.FileReader;
import java.io.IOException;
public class ReverseCaseAndCategory {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt");
int character;
while ((character = reader.read()) != -1) {
if (Character.isAlphabetic(character)) {
if (Character.isUpperCase(character)) {
System.out.print(Character.toLowerCase((char) character));
} else {
System.out.print(Character.toUpperCase((char) character));
}
} else if (Character.isDigit(character)) {
System.out.println((char) character + " is a
Digit");
} else if (Character.isWhitespace(character)) {
System.out.println((char) character + " is a
Space");
}
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " +
e.getMessage());
}
}
}

5. Write a java program to validate PAN number and Mobile


Number. If it is invalid then throw a user defined Exception
"Invalid Data", otherwise display it.
→ import java.util.Scanner;
class InvalidDataException extends Exception {
InvalidDataException(String message) {
super(message);
}
}
public class ValidatePanAndMobile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter PAN number: ");
String pan = scanner.nextLine();
System.out.print("Enter Mobile number: ");
String mobile = scanner.nextLine();
try {
if (!isValidPAN(pan)) {
throw new InvalidDataException("Invalid PAN
number");
}
if (!isValidMobile(mobile)) {
throw new InvalidDataException("Invalid Mobile
number");
}
System.out.println("PAN number: " + pan);
System.out.println("Mobile number: " + mobile);
} catch (InvalidDataException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
scanner.close();
}
}
private static boolean isValidPAN(String pan) {
return pan.matches("[A-Z]{5}[0-9]{4}[A-Z]");
}
private static boolean isValidMobile(String mobile) {
return mobile.matches("\\d{10}");
}
}

You might also like