0% found this document useful (0 votes)
4 views51 pages

Nisarg Java File

Uploaded by

22ai37
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views51 pages

Nisarg Java File

Uploaded by

22ai37
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 51

A D PATEL INSTITUTE OF TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY


Subject : Programming with Java (202044504)

Practical :- 1
1. Study of class path and java runtime environment.

Ans :-
class P1
{
public static void main (String a[])
{
System.out.println("Hello World");
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. (1) Write a program to Implement command line calculator.


Ans :-
import java.util.Scanner;
class P2
{
public static void main (String[] args)
{
int a , b ;
a=Integer.parseInt(args[0]);
System.out.println("Enter 1st Number = "+a);
b=Integer.parseInt(args[1]);

System.out.println("Enter 2nd Number = "+b);


char ch=args[2].charAt(0);
switch(ch)
{
case'+':
int c=a+b;
System.out.println("c is : "+c);
break;
case'-':
c=a-b;
System.out.println("c is : "+c);
break;
case'*':
c=a*b;
System.out.println("c is : "+c);
break;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
case'/':
c=a/b;
System.out.println("c is : "+c);
break;
default :
System.out.println(" Inavalid Choice");
break;
}
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. (2) Write a Program to prints Fibonacci series.


Ans :- import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of n:");
n = s.nextInt();
System.out.print("Fibonacci Series:");
for(int i = 1; i <= n; i++)
{
a = b;
b = c;
c = a + b;
System.out.print(a+" ");
}
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Practical :- 2

1. Define a class Array with following member Field : (int data[]; ,


Function: , Array( ) , Array(int size) , Array(int data[]) , void Reverse
_an _array() , int Maximum _of _array() , int Average_of _array() ,
void Sorting () , void display() , int search(int no) , int size(); )
Use all the function in main method. Create different objects with
different constructors.

Ans :-
import java.util.*;
class Array
{
int data[];
Array()
{
data = new int[0];
}
Array(int size)
{
data = new int[size];
}
Array(int data[])
{
this.data = data;
}
void reverseArray()
{
int n = data.length;
int temp;
for (int i = 0; i < n / 2; i++)
{
temp = data[i];
data[i] = data[n - i - 1];
data[n - i - 1] = temp;
}
}
int maximumOfArray()
{
int max = data[0];
for (int i = 1; i < data.length; i++)
{
if (data[i] > max)
{

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

max = data[i];
}
}
return max;
}
int averageOfArray()
{
int sum = 0;
for (int i = 0; i < data.length; i++)
{
sum += data[i];
}
return sum / data.length;
}
void sorting()
{
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data.length - i - 1; j++)
{
if (data[j] > data[j + 1])
{
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
}
void display()
{
for (int i = 0; i < data.length; i++)
{
System.out.print(data[i] + " ");
}
System.out.println();
}
int search(int no)
{
for (int i = 0; i < data.length; i++)
{
if (data[i] == no)
{
return i;
}
}
return -1;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

}
int size()
{
return data.length;
}
}
}

class Arr1
{
public static void main(String[] args)
{
int data1[] = {1, 2, 3, 4, 5};
Array array1 = new Array();
Array array2 = new Array(10);
Array array = new Array(data1);

System.out.println("Array 1 size: " + array1.size());


System.out.println("Array 2 size: " + array2.size());
System.out.println("Array size: " + array.size());
System.out.println();

System.out.println("Array before reverse: ");


array.display();
array.reverseArray();
System.out.println("Array after reverse: ");
array.display();
System.out.println();

System.out.println("Maximum of Array: " +


array.maximumOfArray());
System.out.println("\n Average of Array: " + array.averageOfArray());
System.out.println();

System.out.println("Array before sorting: ");


array.display();
array.sorting();
System.out.println("\n Array after sorting: ");
array.display();
System.out.println();

int searchKey = 3;
int index = array.search(searchKey);
if (index == -1)
{
System.out.println(searchKey + " not found in Array.");
}
else
{

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

System.out.println(searchKey + " found at index " + index + " in


Array.");
}
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. Define a class Matrix with following Field : int row , column ; float
mat[][] Function : Matrix(int a[][]) , Matrix() , Matrix(int rwo, int
col) , void readMatrix() , float [][] transpose( ) , float [][]
matrixMultiplication(Matrix second ) , void displayMatrix(float [][]a)
, void displayMatrix() , float maximum_of_array() , float
average_of_array( ) create three object of Matrix class with different
constructors in main and test all the functions in main.
Ans :-
import java.util.Scanner;
class Matrix
{
int row;
int column;
float mat[][];
Matrix(int a[][])
{
this.row = a.length;
this.column = a[0].length;
this.mat =new float[this.row][this.column];
for(int i=0;i<this.row;i++){
for(int j=0;j<this.column;j++)
{
this.mat[i][j]=a[i][j];
}
}
}
Matrix()
{
this.row = 3;
this.column = 3;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
this.mat = new float[this.row][this.column];

Matrix(int row, int col)


{
this.row = row;
this.column = col;
this.mat = new float[row][col];
}
void readMatrix()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements of matrix:");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
mat[i][j] = sc.nextFloat();
}
}
}
float[][] transpose()
{
float[][] transposed = new float[column][row];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
transposed[j][i] = mat[i][j];

}
}

return transposed;
}
float[][] matrixMultiplication(Matrix second)
{
if (this.column != second.row)
{
System.out.println("Error: The number of columns in the first matrix must match
the number of rows in the second matrix");
return null;
}
float[][] result = new float[this.row][second.column];
for (int i = 0; i < this.row; i++)
{
for (int j = 0; j < second.column; j++)
{
for (int k = 0; k < this.column; k++)
{
result[i][j] += this.mat[i][k] * second.mat[k][j];
}
}
}
return result;
}
void displayMatrix(float[][] a)

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
{

System.out.println("The matrix is: ");


for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[0].length; j++)
{

System.out.print(a[i][j] + " ");


}
System.out.println();
}
}
void displayMatrix()
{
System.out.println("The matrix is: ");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
float maximum_of_array()
{
float max = mat[0][0];
for (int i = 0; i < row; i++)

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
{

for (int j = 0; j < column; j++)


{
if (mat[i][j] > max)
{
max = mat[i][j];
}
}
}
return max;
}
float average_of_array()
{
int sum = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
sum += mat[i][j];
}
}
return sum / (row * column);
}
}
class Matrix2
{
public static void main(String[] args)
{

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
Matrix matrix1 = new Matrix();

System.out.println("Matrix 1:");
matrix1.readMatrix();
matrix1.displayMatrix();

Matrix matrix2 = new Matrix(3, 3);


System.out.println("Matrix 2:");
matrix2.readMatrix();
matrix2.displayMatrix();

int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};


Matrix matrix3 = new Matrix(array);
System.out.println("Matrix 3:");
matrix3.displayMatrix();

float[][] transposedMatrix = matrix3.transpose();


System.out.println("Transposed Matrix 3:");
matrix3.displayMatrix(transposedMatrix);

float[][] multipliedMatrix = matrix1.matrixMultiplication(matrix2);


System.out.println("Result of Matrix Multiplication:");
matrix1.displayMatrix(multipliedMatrix);

float maximum = matrix3.maximum_of_array();

System.out.println("Maximum value in Matrix 3: " + maximum);

float average = matrix1.average_of_array();

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
System.out.println("Average value in Matrix 1: " + average);

}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

3. Write a program to demonstrate usage of different methods of


Wrapper class.
Ans :- public class Wrapper1
{
public static void main(String args[])
{
int a=20;
Integer i=Integer.valueOf(a);
Integer j=a;

System.out.println(a+" "+i+" "+j);


}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

4. Write a program to demonstrate usage of String and StringBuffer


class.
Ans :- a) String Class
class string
{
public static void main(String args[])
{
String str=new String ("MBIT");
str.concat("Welcomes u");
System.out.println( str );
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

b) String Buffer Class


class sbuffer
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("MBIT");
str.append(" Welcomes u");
System.out.println( str );
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Practical :- 3

1. Create a class BankAccount that has Depositor name , Acc_no,


Acc_type, Balance as Data Members and void createAcc() . void
Deposit(), void withdraw() and void BalanceInquiry as Member
Function. When a new Account is created assign next serial no as
account number. Account number starts from 1.

Ans :- import java.util.Scanner;


class BankAccount11
{
String name;
static int Acc_no=1;
String Acc_type;
double balance;
double amount;
void createAcc()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the account details of Account:" + Acc_no);
name=sc.next();
Acc_type=sc.next();
balance=sc.nextDouble();
Acc_no++;
}
void Deposit()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the amount you need to deposit in Account:"
+
Acc_no);
amount=sc.nextDouble();
balance=balance + amount;
System.out.println("the current Balance of the Account is:" + balance);
}
void withdraw()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the amount you want to withdraw:");
amount= sc.nextDouble();
if (balance >= amount)
{
balance = balance - amount;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

System.out.println("Balance after withdrawal: " + balance);


}
else
{

System.out.println("Your balance is less than " + amount +


"\tTransaction failed...!!" );
}
}
void balanceInquiry()
{
System.out.println("the balance int the Account:" + Acc_no);
System.out.println("is:" + balance);
}
}

class BankAccount12
{
public static void main(String args[])
{
BankAccount A1= new BankAccount();
A1.createAcc();
A1.Deposit();
A1.withdraw();
A1.balanceInquiry();
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. Create a class time that has hour, minute and second as data
members. Create a parameterized constructor to initialize Time
Objects. Create a member Function Time Sum (Time, Time) to sum
two time objects.

Ans :- import java.util.*;


class time

{
int hour , minute , second;
time()
{
hour = 0;
minute = 0;
second = 0;
}
time(int h , int m , int s)
{
hour = h;
minute = m;
second = s;
}
time sum(time t2 , time t3)
{
t3.hour = hour + t2.hour;
t3.minute = minute + t2.minute;
t3.second = second + t2.second;
if(t3.second>=60)
{
t3.minute = t3.minute + t3.minute;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

t3.second = t3.second % 60;


}
if(t3.minute>=60)
{
t3.hour = t3.hour + t2.minute/60;
t3.minute = t3.minute % 60;
}

return t3;
}
void display()
{
System.out.println(hour + " : " + minute + " : " + second);
}
}
class time1
{
public static void main(String args[])
{
time t1 = new time (4 , 24 , 29);
time t2 = new time (2 , 49 , 29);
time t3 = new time ();
t3 = t1.sum(t2,t1);
System.out.print("t3 = ");
t3.display();
}
}

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

3. Define a class with the Name, Basic salary and dearness allowance as
data members. Calculate and print the Name, Basic salary(yearly),
dearness allowance and tax deduced at source(TDS) and net salary,
where TDS is charged on gross salary which is basic salary +
dearness allowance and TDS rate is as per following table:
Gross Salary TDS
Rs. 100000 and below NIL
Above Rs. 100000 10% on excess over 100000
DA is 74% of Basic Salary for all. Use appropriate member function.
Ans :- class employee
{
String name;
int basicSalary;
double DA;
employee(String name,int basicSalary)
{
this.name = name;
this.basicSalary = basicSalary;
this.DA = 0.74 * basicSalary;
}
public double grossSalary()
{
return basicSalary + DA;
}
public double tds()
{ double tds = 0;
if (grossSalary()<=100000 )
tds = 0;
else if (grossSalary()>100000)
tds = grossSalary() * 0.1;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
return tds;
}
double netSalary()
{
return grossSalary() - tds();
}
void getInformation()
{
System.out.println("Name of the employee: "+name);
System.out.println("Basic Salary of the employee: "+basicSalary);
System.out.println("Dearness Allowance of the salary: "+DA);
System.out.println("TDS of the salary: "+tds());
System.out.println("Net Salary of the employee: "+netSalary());
}
}
public class pr03_3
{
public static void main(String[] args)
{
employee a = new employee("Feny",50000);
a.getInformation();
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Practical :- 4

1. class Cricket having data members name, age and member


methods display() and setdata(). class Match inherits Cricket
and has data members no_of_odi, no_of_test. Create an array of 5
objects of class Match. Provide all the required data through
command line and display the information.

Ans :- import java.util.Scanner;


class cricket

String name;

int age;

void display()

System.out.println("The name of the player is "+name+" and age is "+age);

cricket(String name,int age)

this.name = name;

this.age = age;

class match extends cricket

int noOfOdi, noOfTest;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
public void setNoOfOdi(int noOfOdi)

this.noOfOdi = noOfOdi;

public void setNoOfTest(int noOfTest)

this.noOfTest = noOfTest;

match(String name,int age,int noOfOdi,int noOfTest)

super(name,age);

this.noOfOdi = noOfOdi;

this.noOfTest = noOfTest;

public void printInfo()

display();

System.out.println("The number of ODI and TEST matches played are


"+noOfOdi+" and "+noOfTest);

public class pr04_1

public static void main(String[] args)

match m = new match("Mahendra Singh Dhoni",22,58,65);

m.printInfo();

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. Declare an interface called Property containing a method


computePrice to compute and return the price. The interface is
to be implemented by following two classes i) Bungalow and ii)
Flat.
Both the classes have following data members
- name
-constructionArea.
The class Bungalow has an additional data member called
landArea. Define computePrice for both classes for computing
total price. Use following rules for computing total price by
summing up sub-costs:
Construction cost(for both classes): Rs.500/ - per sq.feet
Additional cost ( for Flat) : Rs. 200000/-
( for Bungalow ): Rs. 200/- per sq. feet for landArea
Land cost ( only for Bungalow ): Rs. 400/- per sq. feet
Define method main to show usage of method computePrice.

Ans :- interface Property


{

int ConstructionCost=500;

int AddCostFlat=200000;

int AddCostBun=200;

int LandCost=400;

float computePrice();

class Bungalow implements Property

String name;

float constructionArea;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
float landArea;

Bungalow(String name, float constructionArea, float landArea)

this.name=name;

this.constructionArea=constructionArea;

this.landArea=landArea;

public float computePrice()

return constructionArea*(ConstructionCost+AddCostBun)+landArea*LandCost;

class Flat implements Property

String name;

float constructionArea;

Flat(String name, float constructionArea)

this.name=name;

this.constructionArea = constructionArea;

public float computePrice()

return constructionArea*ConstructionCost + AddCostFlat;

public class pr04_2

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

public static void main(String[] args)

Bungalow b=new Bungalow("Rudraksh",10000,1);

Flat f=new Flat("Shyam",2000);

System.out.print("Price for Bungalow: ");

System.out.println(b.computePrice());

System.out.print("Price for Flat: ");

System.out.println(f.computePrice());

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

3. Define following classes and interfaces. public interface


GeometricShape {
public void describe();
}
public interface TwoDShape extends GeometricShape {
public double area();
}
public interface ThreeDShape extends GeometricShape {
public double volume();
}
public class Cone implements ThreeDShape {
private double radius;
private double height;
public Cone (double radius, double height)
public double volume()
public void describe()
}
public class Rectangle implements TwoDShape {
private double width, height;
public Rectangle (double width, double height)
public double area()
public double perimeter()
public void describe()
}
public class Sphere implements ThreeDShape {
private double radius;
public Sphere (double radius)
public double volume()
public void describe()
}

Define test class to call various methods of Geometric Shape.

Ans :- import java.util.*;


import java.io.*;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
interface GeometricShape

public void describe();

interface TwoDShape extends GeometricShape

public double area();

interface ThreeDShape extends GeometricShape

public double volume();

class Cone implements ThreeDShape

private double radius;

private double height;

public Cone (double radius, double height)

this.height=height;

this.radius=radius;

public double volume()

return (double)((.33)*(Math.PI)*(Math.pow(radius, 2))*height);

public void describe()

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
{

System.out.println("A cone is a 3D shape consisting of a circular base and once


continuous curved surface tapering to a point (the apex) above the
centre of the circular base.");

class Rectangle implements TwoDShape

private double width, height;

public Rectangle(double width, double height)

this.width = width;

this.height = height;

public double area()

return height*width;

public double perimeter()

return 2*(height+width);

public void describe()

System.out.println("A rectangle is a 2D shape that has 4 sides, 4 corners, and 4 right


angles");

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
}

class Sphere implements ThreeDShape

private double radius;

public Sphere (double radius){this.radius=radius;}

public double volume(){return (4/3)*Math.PI*Math.pow(radius, 3);}

public void describe()

System.out.println("A sphere is a perfectly-round 3D shape in the shape of a ball.");

public class pr04_3

public static void main(String[] args)

Rectangle r=new Rectangle(10, 20);

Sphere s=new Sphere(3);

Cone c=new Cone(4, 5);

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

System.out.println("Area : "+r.area());

r.describe();

System.out.println("Perimeter : "+r.perimeter());

System.out.println();

System.out.println("Sphere :");

System.out.println("Volume : "+s.volume());

s.describe();

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
System.out.println();

System.out.println("Cone :");

System.out.println(""+c.volume());

c.describe();

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Practical :- 5

Inner Class :

Define two nested classes: Processor and RAM inside the outer class: CPU
with following data members

class CPU {
double price;
class Processor{ // nested class
double cores;
double catch()
String manufacturer;
double getCache()
void displayProcesorDetail()
}
protected class RAM{ // nested protected class
// members of protected nested class
double memory;
String manufacturer;
Double clockSpeed;
double getClockSpeed()
void displayRAMDetail()
}
}

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

1. Write appropriate Constructor and create instance of Outer and


inner class and call the methods in main function.

Ans :- class CPU


{

public CPU(){}

double price = 45000.0;

static class Processor

public Processor() {}

double cores = 16.0;

String manufacturer = "AMD";

double getCache()

return 16;

void displayProcesorDetail()

System.out.println("Processor Name: AMD Ryzen 9 6000 Series");

protected static class RAM

double memory = 160000000.00;

String manufacturer = "Crucial";

Double clockSpeed = 320000000000.00;

double getClockSpeed()

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
{

return clockSpeed;

void displayRAMDetail()

System.out.println("Ram Name: Crucial");

System.out.println("Ram Speed: 3200Mhz");

System.out.println("Ram Capacity: 16 GB");

public class pr05_1

public static void main(String[] args)

{ CPU.Processor cpu = new CPU.Processor();

CPU c = new CPU();

CPU.RAM r = new CPU.RAM();

cpu.displayProcesorDetail();

r.displayRAMDetail();

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Packages :

1. Implement a program that defines package figures, which has a class


circle inherited from a class shape in it. Include the methods in the
class to calculate area and display the necessary information. Also
include a class, which has main to carry out above-mentioned
operations.

Ans :- package figures;


class Shape {

protected String name;

public Shape(String name)

this.name = name;

public double area()

return 0.0;

public void display()

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

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

class Circle extends Shape

protected double radius;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
public Circle(String name, double radius)

super(name);

this.radius = radius;

public double area()

return Math.PI * radius * radius;

public class pr05_p1

public static void main(String[] args)

Circle circle = new Circle("Circle 1", 5.0);

circle.display();

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. Create a package new_figures, which has classes rectangle and


triangle inherited from class shape of package figures. Thus import
the package figure.Carry out necessary operations tocalculate area
and display the necessary information.

Ans :- package new_figures;


import figures.Shape;

class Rectangle extends Shape


{
protected double length;
protected double width;
public Rectangle(String name, double length, double width)
{
super(name);
this.length = length;
this.width = width;
}
public double area()
{
return length * width;
}
}
class Triangle extends Shape
{
protected double base;
protected double height;
public Triangle(String name, double base, double height)
{
super(name);
this.base = base;
this.height = height;
}

public double area()


{
return 0.5 * base * height;
}
}
public class pr05_p2
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle("Rectangle 1", 5.0, 10.0);
rectangle.display();

Triangle triangle = new Triangle("Triangle 1", 4.0, 6.0);

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
triangle.display();
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Practical :- 6
1. Declare a class InvoiceDetail which accepts a type parameter which is
of type Number with following data members
class InvoiceDetail {
private String invoiceName;
private N amount;
private N Discount // write getters, setters, and constructors
}
Call the methods in Main class

Ans :- class InvoiceDetail<N extends Number>


{
private String invoiceName;
private N amount;
private N discount;

public InvoiceDetail(String invoiceName, N amount, N discount) {


this.invoiceName = invoiceName;
this.amount = amount;
this.discount = discount;
}
public String getInvoiceName()
{
return invoiceName;
}
public void setInvoiceName(String invoiceName)
{
this.invoiceName = invoiceName;
}
public N getAmount()
{
return amount;
}
public void setAmount(N amount)
{
this.amount = amount;
}
public N getDiscount()
{
return discount;
}
public void setDiscount(N discount)
{
this.discount = discount;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
}
public class pr06_1
{
public static void main(String[] args)
{
InvoiceDetail<Double> invoice = new InvoiceDetail<>("Invoice 001", 100.0, 10.0);

System.out.println("Invoice name: " + invoice.getInvoiceName());


System.out.println("Amount: " + invoice.getAmount());
System.out.println("Discount: " + invoice.getDiscount());

invoice.setAmount(90.0);
invoice.setDiscount(9.0);

System.out.println("Updated amount: " + invoice.getAmount());


System.out.println("Updated discount: " + invoice.getDiscount());
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. Write a program to sort the object of Book class using comparable


and comparator interface. (Book class consist of book id, title, author
and publisher as data members)

Ans :- import java.util.ArrayList;


import java.util.Collections;
import java.util.Comparator;

public class Book implements Comparable<Book>


{
private int id;
private String title;
private String author;
private String publisher;
public Book(int id, String title, String author, String publisher)
{
this.id = id;
this.title = title;
this.author = author;
this.publisher = publisher;
}
public int compareTo(Book b)
{
return this.id - b.id;
}
public int getId()
{
return id;
}
public String getTitle()
{
return title;
}
public String getAuthor()
{
return author;
}
public String getPublisher()
{
return publisher;
}
public static void main(String[] args)
{
ArrayList<Book> books = new ArrayList<Book>();
books.add(new Book(2, "Harry Potter and the Philosopher's Stone", "J.K. Rowling",
"Bloomsbury"));

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
books.add(new Book(1, "To Kill a Mockingbird", "Harper Lee", "J. B. Lippincott &
Co."));
books.add(new Book(3, "The Catcher in the Rye", "J.D. Salinger", "Little, Brown
and Company"));

Collections.sort(books);

System.out.println("Sorted by book id:");


for (Book b : books)
{
System.out.println(b.getId() + " " + b.getTitle() + " " + b.getAuthor() + " " +
b.getPublisher());
}
Comparator<Book> titleComparator = new Comparator<Book>()
{
public int compare(Book b1, Book b2)
{
return b1.getTitle().compareTo(b2.getTitle());
}
};
Collections.sort(books, titleComparator);

System.out.println("\nSorted by book title:");


for (Book b : books)
{
System.out.println(b.getId() + " " + b.getTitle() + " " + b.getAuthor() + " " +
b.getPublisher());
}
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

Practical :- 7
1. Write a program for creating a Bank class, which is used to manage
the bank account of customers. Class has two methods, Deposit () and
withdraw (). Deposit method display old balance and new balance
after depositing the specified amount. Withdrew method display old
balance and new balance after withdrawing. If balance is not enough
to withdraw the money, it throws ArithmeticException and if balance
is less than 500rs after withdrawing then it throw custom exception,
NotEnoughMoneyException.

Ans :- class NotEnoughMoneyException extends Exception


{
public NotEnoughMoneyException(String message)
{
super(message);
}
}
class Bank
{
private double balance;
public Bank(double balance)
{
this.balance = balance;
}

public void deposit(double amount)


{
double oldBalance = balance;
balance += amount;
System.out.println("Old Balance: " + oldBalance);
System.out.println("New Balance: " + balance);
}

public void withdraw(double amount) throws ArithmeticException,


NotEnoughMoneyException
{
double oldBalance = balance;
if (balance < amount)
{
throw new ArithmeticException("Not enough balance to withdraw");
}
else
{
balance -= amount;

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
}
if (balance < 500)
{
balance = oldBalance;
throw new NotEnoughMoneyException("Balance cannot be less than 500rs after
withdrawal");
}
System.out.println("Old Balance: " + oldBalance);
System.out.println("New Balance: " + balance);
}
}
public class pr07_1
{
public static void main(String[] args)
{
Bank bank = new Bank(1000);
try
{
bank.deposit(500);
bank.withdraw(200);
bank.withdraw(1000);
bank.withdraw(500);
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch (NotEnoughMoneyException e)
{
System.out.println(e.getMessage());
}
}
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)

2. Write a complete program for calculation average of n +ve integer


numbers of Array A. a. Read the array form keyboard b. Raise and
handle Exception if i. Element value is -ve or non-integer. ii. If n is
zero.

Ans :- import java.util.Scanner;


public class pr07_2
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;

try {
System.out.print("Enter the number of elements: ");
n = scanner.nextInt();
if (n == 0)
{
throw new Exception("Number of elements cannot be zero");
}
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}

int[] A = new int[n];

try {
for (int i = 0; i < n; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
int element = scanner.nextInt();
if (element <= 0) {
throw new Exception("Element value must be positive");
}
A[i] = element;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}

int sum = 0;
for (int i = 0; i < n; i++) {
sum += A[i];
}
double average = (double) sum / n;
System.out.println("The average is: " + average);
}

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096
A D PATEL INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject : Programming with Java (202044504)
}

Output :-

NAME: NISARGKUMAR JAGDISHKUMAR PATEL


ENROLLMENT NUMBER: 12202080601096

You might also like