0% found this document useful (0 votes)
30 views33 pages

Abhi 123

The document contains multiple Java programming assignments that cover various concepts such as matrix operations, point representation, shape interfaces, exception handling, file reading, temperature conversion, user authentication, inheritance, and substring matching. Each assignment includes a problem statement, source code, and expected output. The assignments aim to enhance programming skills and understanding of Java fundamentals.

Uploaded by

Akash Mourya
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)
30 views33 pages

Abhi 123

The document contains multiple Java programming assignments that cover various concepts such as matrix operations, point representation, shape interfaces, exception handling, file reading, temperature conversion, user authentication, inheritance, and substring matching. Each assignment includes a problem statement, source code, and expected output. The assignments aim to enhance programming skills and understanding of Java fundamentals.

Uploaded by

Akash Mourya
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/ 33

Page |1

Assignment-1
Problem statement: Write a Java Program to create a class ‘Matrix’ containing constructor that
initializes the number of rows and columns of a new matrix object. Write a member function Sum()
that prints the sum of the elements of the matrix column wise.

Source Code:
import java.util.*;
class Matrix {
int rows;
int cols;
int data[][];
Matrix()
{
rows=4;
cols=4;
data = new int[rows][cols];
}
Matrix(int a, int b)
{
rows=a;
cols=b;
data = new int[rows][cols];
}
void inputMatrix()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Element [" +i+" ]["+j+"]: ");
data[i][j] = sc.nextInt();
}
}
System.out.println("\nMatrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(data[i][j]+"\t");
}
System.out.println();
}
}
void sum()
{
for (int j = 0; j < cols; j++)
{ int sum = 0;
for (int i = 0; i < rows; i++)
{ sum =sum + data[i][j];
}
System.out.println("Sum of each element is: "+sum);
}
}
}
class MatMain
{
public static void main(String args[])
{
Matrix r1 = new Matrix();
Page |2

r1.inputMatrix();
System.out.println();
r1.sum();
}
}
Output:

Set-1:

Teacher’s Signature
Page |3

Assignment-2
Problem statement: Write a Java program to create a class Point to represent a point in X-Y plane and
add the method to perform the following tasks:
a) Set the coordinate of a point using a constructor .
b) Print the coordinate of a point.
c) Print the quadrant number in which the point
lies. Source Code:
import java.util.*;
class Point
{
int x;
int y;
Point()
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter the value of x: ");
x=sc.nextInt();
System.out.print("Enter the value of y: ");
y=sc.nextInt();
}
void printCoordinate()
{
System.out.println("\nPoint coordinate: ("+x+ "," +y+ ")");
System.out.println();
}
void printQuadrant()
{
if(x>0 && y >0){
System.out.println("The point lies in Quadrant I");
}
else if(x<0 && y>0){
System.out.println("The point lies in Quadrant II");
}
else if(x<0 && y<0){
System.out.println("The point lies in Quadrant III");
}
else if(x>0 && y<0){
System.out.println("The point lies in Quadrant IV");
}
else if(x==0 && y>0){
System.out.println("The point lies on the positive Y - axis.");
}
else if(x==0 && y<0){
System.out.println("The point lies on the negative Y - axis");
}
else if(x>0 && y==0){
System.out.println("The point lies on the positive X - axis");
}
else if(x<0 && y==0){
System.out.println("The point lies on the negative X - axis");
}
else{
System.out.print("The point lies on the origin");
}
Page |4

}
}
class PointMain
{
public static void main(String args[])
{
Point p1 = new Point();
p1.printCoordinate();
p1.printQuadrant();
}
}

Output:

Set-1:

Set-2:

Teacher’s Signature
Page |5

Assignment-3
Problem statement: Design an interface called shape with methods draw() and getArea(). Further
design two classes Circle and Rectangle that implements shape to compute area of respective shapes.
Write a JAVA program for the same.

Source Code:
import java.util.*;
interface Shape{
public final double PI = 3.14;
public void Draw();
public void getArea();
}
class Circle implements Shape{
double radious;
Circle(double x){
radious=x;
}
public void Draw(){
System.out.println("Circle Drawn");
}
public void getArea(){
System.out.print("Circle area:" +PI*radious*radious);
}
}
class Rect implements Shape{
double len;
double breadth;
Rect(double x,double y){
len=x;
breadth=y;
}
public void Draw(){
System.out.println("Rectangle is Drawn");
}
public void getArea(){
System.out.print("Rectangle area:" +len*breadth);
}
}
class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radious:");
double radious = sc.nextDouble();
Circle c = new Circle(radious);
c.Draw();
c.getArea();

System.out.print("\n\nEnter the length:");


double len = sc.nextDouble();
System.out.print("Enter the breadth:");
double breadth = sc.nextDouble();
Rect r = new
Rect(len,breadth); r.Draw();
r.getArea();
Page |6

}
}

Output:

Set-1:

Set-2:

Teacher’s Signature
Page |7

Assignment-4
Problem statement: Write a JAVA program to create your own experience as Negative Exception
whenever negative values are put in an array.
Source Code:
import java.util.*;
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
class Array
{ int[] data;
int count = 0;
int limit;
Array(int limit) {
this.limit = limit;
this.data = new int[limit];
}
void add(int value) throws MyException {
if (value < 0) {
throw new MyException("Negative number is not allowed: " + value);
}
if (count < limit) {
data[count++] = value;
} else {
System.out.println("Array limit reached.");
}
}
}
class Main {
public static void main(String args[])
{ int invalid = 0;
int limit;
int[] data;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
limit = sc.nextInt();
data = new int[limit];
System.out.println("Enter the elements: ");
for (int i = 0; i < limit; i++) {
System.out.printf("Element [%d]: ", i);
data[i] = sc.nextInt();
}
Array newAr = new Array(limit);
for (int i = 0; i < limit; i++) {
try {
newAr.add(data[i]);
} catch (MyException e)
{ invalid++;
System.out.println(e.getMessage());
}
}
System.out.println("Invalid input count: " + invalid);
}
}
Page |8

Output

Set-1:

Set-2:

Teacher’s Signature
Page |9

Assignment-5
Problem statement: Develop a Java program for reading & displaying the content of a text file.
Implement exception handling to address potential issues, such as file not found
(FileNotFoundException) and IO errors.

Source Code:
import java.io.*;
import java.util.*;
class FileRead {
void readFile(String filepath) {
File f = new File(filepath);
try{
Scanner r = new
Scanner(f); while
(r.hasNextLine()) {
System.out.println("The content of the file: ");
System.out.println(r.nextLine());
}
}
catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
}
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name or path: ");
String filepath = sc.nextLine();
FileRead f1obj = new FileRead();
f1obj.readFile(filepath);
}
}
Output:
Set-1:

Set-2:

Teacher’s Signature
P a g e | 10

Assignment-6
Problem statement: Develop a JAVA program to convert temperatures between Celsius & Fahrenheit.
Implement exception handling to address potential issues, such as invalid temperature input
(NumberFormatException) and invalid conversion choices (illegalArgumentException).

Source Code:
import java.util.*;
class NumberFormatException extends Exception {
public NumberFormatException(String message){
super(message);
}
}
class IllegalArgumentException extends Exception {
public IllegalArgumentException(String message) {
super(message);
}
}
class TempMain{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
try{
System.out.print("Enter the temperature value: ");
double temp = sc.nextDouble();
System.out.print("Enter the conversion type (F for Celsius to Fahrenheit, C
for Fahrenheit to Celsius): ");
String choice = sc.next().toUpperCase();
switch(choice) {
case "F":
if(temp < -459.67){
throw new NumberFormatException("\nTemparature can't be below `
absolute zero temparature");
}
double convertedTemp = celsiusToFahrenheit(temp);
System.out.printf("\n"+temp+" Celsius is "+convertedTemp+" Fahrenheit");
break;
case "C":
if(temp < -273.15){
throw new NumberFormatException("\nTemparature can't be below
absolute zero temparature");
}
convertedTemp = fahrenheitToCelsius(temp); System.out.printf("\
n"+temp+" Fahrenheit is "+convertedTemp+" Celcius"); break;
default:
throw new IllegalArgumentException("Its an invalid conversion");
}
}
catch(IllegalArgumentException e){
System.out.print("\nError"+ e.getMessage());
}
catch(NumberFormatException e){
System.out.print("\nError"+ e.getMessage());
}
}
P a g e | 11

public static double celsiusToFahrenheit(double temp){


return (temp * 9/5) + 32;
}
public static double fahrenheitToCelsius(double temp){
return (temp - 32) * 5/9;
}
}
Output:
Set-1:

Set-2:

Set-3:

Set-4:

Teacher’s Signature
P a g e | 12

Assignment-7
Problem statement: Develop a Java program for user authentication. Users input a username &
password, and the program validates the credentials. Implement exception handling to address
potential issues, such as incorrect username or password (Authentication Exception) and null
input (NullPointerException).

Source Code:
import java.util.*;
class AuthenticationException extends Exception{
AuthenticationException(String message){
super(message);
}
}
class NullPointerException extends Exception{
NullPointerException (String message){
super(message);
}
}
class Authentication
{
static String valid_username = "abhi296";
static String valid_password =
"pass123"; String username;
String password;
Authentication(){
this.username = "";
this.password = "";
}
Authentication(String username,String password){
setvalue(username,password);
}
public void setvalue(String username,String password){
this.username = username;
this.password = password;
}
public void validationCheck(){
try{
if(this.username.equals("") || this.password.equals("")) {
throw new NullPointerException("Input can not be null!!!");
}
else if(!this.username.equals(valid_username) ||
!this.password.equals(valid_password)) {
throw new AuthenticationException("Username or Password is incorrect!!!");
}
else{
System.out.print("Authentication is succesful!!");
}
}
catch(NullPointerException e){
System.out.print("Error: "+e.getMessage());
}
catch(AuthenticationException e){
System.out.print("Authentication is failed. "+e.getMessage());
}
}
P a g e | 13

}
class Authentication_Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the username : ");
String username = sc.nextLine();
System.out.print("Enter the password : ");
String password = sc.nextLine();

Authentication a = new Authentication();


a.setvalue(username,password);
a.validationCheck();
}
}
Output:
Set-1

Set-2:

Set-3:

Teacher’s Signature
P a g e | 14

Assignment-8
Problem statement: Create a super class ‘Person’ and one subclass ‘Student’. Write a Java program
to do the following: (a) For ‘Person’ instance variables: Name: String , address: String. Initiate
variable through constructor, incorporate one method setPerson() that updates Person variables,
another method tostring () that shows Person details as “Person :- name: ? , address: ?”.
(b) For ‘Student’ sub class instance variables: Program: String ,year: String, fees: Double. Initiate both
‘Student’ & ‘Person’ variables through constructor, incorporate one method setStudent() that
updates both ‘Student’ and ‘Person’ data, another method tostring () that shows ‘Person-Student’
details as “Person:- name: ? , address: ?, program: ?, year: ?, fees: ?”.

Source Code:
import java.util.*;
class Person{
String name;
String address;
Person(String name,String address){
this.name=name;
this.address=address;
}
void setPerson(String name,String address){
this.name=name;
this.address=address;
}
public String toString(){
return "Person :- Name: " +name+ ", Address : " +address;
}
}
class Student extends Person {
String program;
int year;
double fees;
Student(String name,String address,String program,int year,double fees){
super(name,address);
this.program =
program; this.year =
year; this.fees = fees;
}
void setStudent(String name,String address,String program,int year,double fees) {
setPerson(name,address);
this.program = program;
this.year = year;
this.fees = fees;
}
public String toString(){
return super.toString()+ ", Program : " +program+ ", Year: " +year+ ", Fees: " +fees;
}
}
class Stu_Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the name : ");
String personName=sc.nextLine();
System.out.print("Enter the address : ");
String personAddress=sc.nextLine();
Person p =new Person(personName,personAddress);
p.setPerson(personName,personAddress);
System.out.print(p.toString());
P a g e | 15

System.out.print("\nEnter the program : ");


String program=sc.nextLine();
System.out.print("Enter the year : ");
int year=sc.nextInt();
System.out.print("Enter the Fees : ");
double fees=sc.nextDouble();

Student s =new Student(personName,personAddress,program,year,fees);


System.out.println("\nInitial Student Details:");
System.out.print(s.toString());

System.out.print("\nEnter the name : ");


sc.nextLine();
String newname=sc.nextLine();
System.out.print("Enter the address : ");
String newaddress=sc.nextLine();
System.out.print("Enter the program : ");
String newprogram=sc.nextLine();
System.out.print("Enter the year : ");
int newyear=sc.nextInt();
System.out.print("Enter the Fees : ");
double newfees=sc.nextDouble();
s.setStudent(newname,newaddress,newprogram,newyear,newfees);
System.out.println("\nUpdated Student Details:");
System.out.print(s.toString());
}
}
Output:
Set-1:

Teacher’s Signature
P a g e | 16

Assignment-9
Problem statement: Write a Java program to find whether a region in the current string matches with
a separate region in another string. Sample output: Str1 [0-7] = = str2[28-35]? True
Str2 [9-15] = = str2[9-15]? False.
Source Code:
import java.util.*;
class SubStrmatcher
{
String str1;
String str2;
int str1Start1;
int str1End1;
int str2Start1;
int str2End1;
int str1Start2;
int str1End2;
int str2Start2;
int str2End2;
SubStrmatcher(int str1Start2,int str1End2, int str2Start2, int str2End2,int str1Start1,int str1End1, int
str2Start1, int str2End1,String str1, String str2) {
this.str1 =
str1; this.str2
= str2;
this.str1Start1 = str1Start1;
this.str1End1 = str1End1;
this.str2Start1 = str2Start1;
this.str2End1 = str2End1;
this.str1Start2 = str1Start2;
this.str1End2 = str1End2;
this.str2Start2 = str2Start2;
this.str2End2 = str2End2;
}
// Method to check if the substrings
match void checking_Match() {
if (str1Start1 >= 0 && str1End1 <= str1.length() && str2Start1 >= 0 && str2End1 <= str2.length()) {
boolean match1 = str1.substring(str1Start1, str1End1).equals(str2.substring(str2Start1, str2End1));
System.out.println("Str1[" + str1Start1 + "-" + (str1End1) + "] = Str2[" + str2Start1 + "-" + (str2End1) + "] ? " +
match1);
}else {
System.out.println("Invalid indices are selected for first checking.");}
if (str1Start2 >= 0 && str1End2 <= str1.length() && str2Start2 >= 0 && str2End2 <= str2.length()) {
boolean match2 = str1.substring(str1Start2, str1End2).equals(str2.substring(str2Start2, str2End2));
System.out.println("Str1[" + str1Start2 + "-" + (str1End2) + "] = Str2[" + str2Start2 + "-" + (str2End2) + "] ? " +
match2);
} else {
System.out.println("Invalid indices are selected for second checking.");
}
}
}
class MainStrMatch {
public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = sc.nextLine();
System.out.print("Enter the second string: ");
String str2 = sc.nextLine();
System.out.println("Take input for first checking : ");
System.out.print("Enter the first index of str1: ");
int str1Start1 = sc.nextInt();
System.out.print("Enter the second index of str1: ");
int str1End1 = sc.nextInt();
System.out.print("Enter the first index of str2: ");
P a g e | 17

int str2Start1 = sc.nextInt();


System.out.print("Enter the second index of str2: ");
int str2End1 = sc.nextInt();
System.out.println("Take input for second checking : ");
System.out.print("Enter the first index of str1: ");
int str1Start2 = sc.nextInt();
System.out.print("Enter the second index of str1: ");
int str1End2 = sc.nextInt();
System.out.print("Enter the first index of str2: ");
int str2Start2 = sc.nextInt();
System.out.print("Enter the second index of str2: ");
int str2End2 = sc.nextInt();

// Create SubStrmatcher object and check the match


SubStrmatcher s = new SubStrmatcher (str1Start2, str1End2, str2Start2, str2End2, str1Start1 str1End1,
str2Start1, str2End1, str1, str2);
s.checking_Match();
}
}
Output:
Set-1:

Teacher’s Signature
P a g e | 18

Assignment-10
Problem statement: Write a Java program to delete all consonants from an input str ng and print the
resultant string.
Source Code:
import java.util.*;
class RemoveConsonant{
String str;
RemoveConsonant(String str)
{ this.str=str;
}
public void remove(String str){
String result = str.replaceAll("[^aeiouAEIOU\\s]","");
System.out.print("The String without consonants:
"+result);
}
}
class Remove_Main{
public static void main(String args[])
{ Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String str = sc.nextLine();
RemoveConsonant r = new RemoveConsonant(str);
r.remove(str);
}
}
Output:

Set-1:

Set-2:

Teacher’s Signature
P a g e | 19

Assignment-11
Problem statement: There is a class called Mypoint, which models a 2D point with X & Y co-ordinates.
It contains: Two instance variables x(int) , y(int).
a) A default constructor that construct a point at the default location (0,0).
b) An overloaded constructor that construct a point with the given X & Y coordinates.
c) A method getData() to take values of X & Y from user.
d) A method called linesegment(Mypoint m, Mypoint n) that finds out the gradient of the
line segment and returns it from the function.
Write the Mypoint class in java and also write a class Gradient-check to test all the public methods
defined in the class Mypoint.

Source Code:
import java.util.*;
class MyPoint{
int x;
int y;
MyPoint(){
this.x=0;
this.y=0;
}
MyPoint(int x,int y)
{ this.x=x;
this.y=y;
}
public void getData(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of X co-ordinate:");
this.x=sc.nextInt();
System.out.print("Enter the value of Y co-ordinate:");
this.y=sc.nextInt();
}
public double lineSegment(MyPoint m,MyPoint n){
if(n.x - m.x == 0){
System.out.print("Gradinent is undefined.");
}
return (double) (n.y - m.y)/(n.x - m.x);
}
void display(){
System.out.println("Point coordinate: ("+x+","+y+")");
}
}
class GradientCheck{
public static void main(String args[]){
MyPoint p1 = new
MyPoint(); MyPoint p2 =
new MyPoint();
System.out.println("Enter the coordinate of Point 1 :
"); p1.getData();
System.out.println("Enter the coordinate of Point 2 :
"); p2.getData();
p1.display();
p2.display();
double gradient = p1.lineSegment(p1,p2);
System.out.println("Gradient of line segment between Point1 and Point2 is : "
+gradient);
}
P a g e | 20

}
Output:

Set-1

:Set-2:

Teacher’s Signature
P a g e | 21

Assignment-12
Problem Statement: Write a Java program to create a class student with following operations : a)
Create parameterized constructor to initialize the objects. b) Create a function isEqual() to check
whether the two objects are equal or not which returns the Boolean value and gets two objects. c)
Print the result in main method if objects are equal or not (take variables as your assumption).

Source Code:
import java.util.*;
class Student {
String name;
int roll;
int age;
Student(String name, int roll, int age)
{ this.name = name;
this.roll = roll;
this.age = age;
}
void setVal() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the student name: ");
this.name = sc.nextLine(); // Set instance
variable System.out.print("Enter the roll no.: ");
this.roll = sc.nextInt(); // Set instance variable
System.out.print("Enter the age: ");
this.age = sc.nextInt(); // Set instance variable
}
boolean isEqual(Student other) {
if (other == null) {
return false;
}
return this.name.equals(other.name) && this.roll == other.roll && this.age == other.age;
}
}
class MainStudentCheck {
public static void main(String args[])
{ Student s1 = new Student("", 0,
0); Student s2 = new Student("",
0, 0); Student s3 = new
Student("", 0, 0); s1.setVal();
s2.setVal();
s3.setVal();
boolean isEq1 = s1.isEqual(s2);
System.out.println("Student 1 == Student 2 : " + isEq1);

boolean isEq2 = s2.isEqual(s3);


System.out.println("Student 2 == Student 3 : " + isEq2);

boolean isEq3 = s1.isEqual(s3);


System.out.println("Student 1 == Student 3 : " + isEq3);
}
}
P a g e | 22

Output:

Set-1:

Teacher’s Signature
P a g e | 23

Assignment-13
Problem statement: Write a Java program to find out the areas of Square and Rectangle by deriving
them from Shape class.
Source Code:
import java.util.*;
class Shape
{
double length;
Shape(double x) {
length=x;
}
void calArea() {
System.out.println("Area of Square: " +length*+length);
System.out.println();
}
}
class Square extends Shape {
Square(double x){
super(x);
}
}
class Rect extends Shape {
double breadth;
Rect(double x,double y) {
super(x);
breadth = y;
}
void calArea()
{ System.out.println("Area of Rectangle: " +length*+breadth);

}
}
class ShapeMain
{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length: " );
double length = sc.nextDouble();
Square s = new Square(length);
s.calArea();

System.out.println("Enter the length: " );


length = sc.nextDouble();
System.out.println("Enter the breadth: " );
double breadth = sc.nextDouble();
Rect r = new Rect(length,breadth);
r.calArea(); }
}
Output:
Set-1:

Teache ’s Signature
P a g e | 24

Assignment-14
Problem statement: Write a Java program to accept two numbers. Check whether the two numbers
are prime or not. Throw an Exception in the following cases:
(a) If the 1st number is negative.
(b) If the 2nd number is equal to Zero

Source Code:
import java.util.*;
class My_NegativeNumberException extends Exception {
public My_NegativeNumberException(String message) {
super(message);
}
}
class My_ZeroInputException extends Exception {
public My_ZeroInputException(String message)
{ super(message);
}
}
class PrimeCheck {
public static boolean isPrime(int num) {
if (num <= 1) {
return false; // 0 and 1 are not prime
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // Not a prime number
}
}
return true; // It is a prime number
}
}
class MainNegZero {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); try {
System.out.print("Enter the first number: ");
int num1 = sc.nextInt();
System.out.print("Enter the second number:
"); int num2 = sc.nextInt();
if (num1 < 0) {
throw new My_NegativeNumberException("First number is negative, which is not allowed.");
}
if (num2 == 0) {
throw new My_ZeroInputException("Second number cannot be zero.");
}
if (PrimeCheck.isPrime(num1))
{ System.out.println(num1 + " is a prime
number.");
} else {
System.out.println(num1 + " is not a prime number.");
}
if (PrimeCheck.isPrime(num2))
{ System.out.println(num2 + " is a prime
number.");
} else {
System.out.println(num2 + " is not a prime number.");
}
} catch (My_NegativeNumberException e) {
System.out.println("Error: " + e.getMessage());
} catch (My_ZeroInputException e) {
System.out.println("Error: " + e.getMessage());
P a g e | 25

}
}
}
Output:
Set-1:

Set-2:

Set-3:

Teacher’s Signature
P a g e | 26

Assignment-15
Problem statement: Write a Java program that performs division of two numbers while incorporating
exception handling. Users are prompted to input the numerator and denomitator. The program should
handle potential exception such as division by zero and invalid input.

Source Code:
import java.util.*;
class MyArithmeticException extends Exception{
MyArithmeticException(String message){
super(message);
}
}
class Division{
double divide(double numerator,double denominator) throws
MyArithmeticException{ if(denominator == 0){
throw new MyArithmeticException("Exception: Division by zero.");
}
double result =
(numerator/denominator); if(result < 0){
throw new MyArithmeticException("Exception: The result is negative.");
}
return result;
}
}
class DivMain{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Division div = new Division();
try{
System.out.print("Enter the numerator: ");
double numerator = sc.nextDouble();
System.out.print("Enter the denominator : ");
double denominator = sc.nextDouble();
double result = div.divide(numerator,denominator);
System.out.println("The Result: ");
System.out.print(numerator+" / "+denominator+" = " +result);
} catch(MyArithmeticException e){
System.out.println("Error: "+e.getMessage());
}
catch(Exception e){
System.out.println("Error: "+e.getMessage());
}
}
}
Output:
Set-1:
P a g e | 27

Set-2:

Set-3:

Set-4:

Teacher’s Signature
P a g e | 28

Assignment-16
Problem statement: Write a java program to transpose a matrix.Given an N x M matrix,the transpose
of the matrix is obtained by swapping the rows & columns.
Source Code:
import java.util.*;
classTransMatrix{
int[][] matrix,transposeMatrix;
int N,M;
Scanner sc;
TransMatrix(intN,intM){
sc=newScanner(System.in);
this.N = N;
this.M=M;
matrix = new int[N][M];
transposeMatrix=newint[M][N];
}

voidinputMatrix(){
System.out.println("Entertheelementsofthematrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j]=sc.nextInt();
}

void changeTranspose(){
for(inti=0;i<N;i++){ for (int j
= 0; j < M; j++) {
transposeMatrix[j][i]=matrix[i][j];
}

void printMatrix(){
System.out.println("OriginalMatrix:");
for (int i = 0; i < N; i++)
{for(intj=0;j<M;j++){
System.out.print(matrix[i][j]+"");
}

System.out.println();
}

System.out.println("TransposedMatrix:");
for (int i = 0; i < M; i++) {
for(intj=0;j<N;j++){
System.out.print(transposeMatrix[i][j]+"");
}

System.out.println();
}

}
P a g e | 29

classMatrixMain{
public static void main(String args[]) {
Scannersc=newScanner(System.in);
System.out.print("Enterthenumberofrows(N):");
Int N=sc.nextInt();
System.out.print("Enterthenumberofcolumns(M):");
int M = sc.nextInt();
TransMatrixmatrix1=newTransMatrix(N,M);
matrix1.inputMatrix(); matrix1.changeTranspose();
matrix1.printMatrix();

Output:
Set-1:

Teacher’s Signature
P a g e | 30

Assignment-17

Problem statement: Write a java program to find the length of the longest substring without repeating
characters, in a given string.
Source Code:
import java.util.HashSet;

class LongestSubstring {

public static int findLongestSubstring(String s) {

int maxLength = 0;

int start = 0;

HashSet<Character> set = new HashSet<>();

for (int end = 0; end < s.length(); end++) {

while (set.contains(s.charAt(end))) {

set.remove(s.charAt(start));

start++;

set.add(s.charAt(end));

maxLength = Math.max(maxLength, end - start + 1);

return maxLength;

public static void main(String[] args) {

String input = "abcdefg";

System.out.println("The length of the longest substring without repeating characters is: "

+ findLongestSubstring(input));

Output:
Set-1:

Teacher’s Signature
P a g e | 31

Assignment-18

Problem Statement: Write a program to create two threads one prints ‘Hello’ and other prints ‘Hi’.

Source Code:
class A extends Thread
{
@Override
public void
run()
{
System.out.println("Hi");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Hello");
}
}
class Threadmain
{
public static void main(String[] args)
{
A threadA=new A();
B threadB=new B();

threadA.start(); threadB.start();
}
}
Output:
Set-1:

Teacher’s Signature
P a g e | 32

Assignment-19

Problem Statement: Using methods chatAt() and lengths() of string class, write a program to print
the frequency of each character in a string.
Source Code:
class CharacterFrequency {

public static void main(String[] args)


{ String input = "computer
science";
printCharacterFrequency(input);
}

public static void printCharacterFrequency(String str) {


// Loop through the string
for (int i = 0; i < str.length(); i++)
{ char currentChar =
str.charAt(i); int count = 0;

// Count occurrences of the current character


for (int j = 0; j < str.length(); j++) {
if (str.charAt(j) == currentChar) {
count++;
}
}

// Print the character and its frequency, only once per character
if (str.indexOf(currentChar) == i) {
System.out.println("Character: " + currentChar + " | Frequency: " + count);
}
}
}
}

Output:
Set-1:

Teacher’s Signature
P a g e | 33

Assignment-20

Problem Statement: Write a Java method to count all words in a string and reverse every word &
display them.
Source Code:
class WordReversal {
public static void main(String[] args)
{ String input = "Bidhan Chandra
College"; reverseAndCountWords(input);
}

public static void reverseAndCountWords(String str) {


// Split the string into words using space as the delimiter
String[] words = str.split(" ");

// Count the number of words


int wordCount = words.length;
System.out.println("Total number of words: " + wordCount);

// Reverse and display each word


System.out.print("Reversed words: ");
for (String word : words) {
String reversedWord = new
StringBuilder(word).reverse().toString();
System.out.print(reversedWord + " ");
}
}
}
Output:
Set-1:

Teacher’s Signature

You might also like