0% found this document useful (0 votes)
2 views52 pages

Java Practical18

The document outlines practical exercises for students at Madhuben & Bhanubhai Patel Institute of Technology, focusing on Java programming concepts such as setting class paths, implementing a command line calculator, and creating classes for array and matrix operations. It includes code examples for various tasks, including reversing arrays, performing matrix multiplication, and demonstrating wrapper classes and string manipulation. The document serves as a guide for students to apply their learning in practical programming scenarios.

Uploaded by

tithibhatt0
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)
2 views52 pages

Java Practical18

The document outlines practical exercises for students at Madhuben & Bhanubhai Patel Institute of Technology, focusing on Java programming concepts such as setting class paths, implementing a command line calculator, and creating classes for array and matrix operations. It includes code examples for various tasks, including reversing arrays, performing matrix multiplication, and demonstrating wrapper classes and string manipulation. The document serves as a guide for students to apply their learning in practical programming scenarios.

Uploaded by

tithibhatt0
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

MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY

(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)


DEPARTMENT OF COMPUTER ENGINEERING

PRACTICAL-1
1.1) : Study of class path and java runtime environment

There are two ways of set a path variable

1) By ordinary method

2) By command prompt By Ordinary Method

Step 1: Open a Environment Variables Dialog box by search box

Step 2: Click on New Button -> Enter PATH as a variable name and copy the path of bin file of JDK

And paste to the variable value -> click on OK

By Command Prompt Syntax: path [[:][;...][;%PATH%]]

1.2) : Write a program to

• Implement command line calculator


import [Link];

public class pract11 {

public static void main(String

args[]){ Scanner sc = new

Scanner([Link]);

[Link]("Enter 1st number: ");

int x = [Link]();

[Link]("Enter 2nd number: ");

int y = [Link]();

double add= x+y;

double sub= x-y;

double mul = x*y;

double div = x/y;

[Link]("Addition of " + x + "and " + y +" is:" + add);

[Link]("Subtraction of " + x + "and " + y +" is:" + sub);

[Link]("Multiplication of " + x + "and " + y +" is:" + mul);

[Link]("Division of " + x + "and " + y +" is:" + div);

}}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

OUTPUT :

• Write To prints Fibonacci series.


import [Link];

public class pract12 {

public static void main(String

args[]){ Scanner sc = new

Scanner([Link]);

[Link]("Enter number of term for the Fibonacci series: ");

int term = [Link]();

int first=0;

int second=1;

[Link]("Fibonacci Series: "+ first+" "+ second+" ");

for(int i=2;i<term;i++){

int next = first+second;

[Link](next + " ");

first = second;

second = next;

OUTPUT :

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

PRACTICAL-2

2.1) : Define a class Array with following member


Field: int data[]; Function: Array( ) //create array data of size 10
Array(int size) // create array of size size
Array(int data[]) // initialize array with parameter array
void Reverse _an _array () //reverse element of an array
int Maximum _of _array () // find maximum element of array
int Average_of _array() //find average of element of array
void Sorting () //sort element of array
void display() //display element of array
int search(int no) //search element and return index else return -1
int size(); //return size of an array Use all the function in main method.
Create different objects with different constructors
public class Array

{ int data[];

int length;

Array(){ leng

th = 10;

data = new int[10];

Array(int

size){ length = size;

data = new int[length];

Array(int

arr[]){ length =

[Link]; data = new

int[length];

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

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

data[i]=arr[i];

public void reverse() {

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

{ int temp = data[i];

data[i] = data[length - 1 - i];

data[length - 1 - i] = temp;

public int

maxofarray(){ int max =

data[0];

for( int i :

data){ if( i >

max){ max = i;

return max;

public int

avgofarray(){ int sum =

0;

for( int i :

data){ sum += i;

return sum / length ;

public void sort(){

for( int i=0 ; i<length ;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

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

j++){

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

if( data[i] >

data[j]){ int temp =

data[i]; data[i] =

data[j]; data[j] =

temp;

[Link]("Sorted Array :");

for ( int i : data){

[Link](i + " ");

[Link]();

public void

display(){ for( int i :

data){ [Link]( i

+ " ");

[Link]();

public int search(int

key){ for( int i = 0; i < length;

i++){ if ( data[i] == key){

return i;

return -1;

public int

size(){ return

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

length;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

public static void main(String args[]){

// make a array of default size set

Array arr1 = new Array();

// make a array of size 5

Array arr2 = new Array(5);

int DATA[]= {10,20,30,40,50};

Array arr3 = new Array(DATA);

[Link]();

[Link]("Reversed Array:");

[Link]();

[Link]("Maximun elemnent:" + [Link]());

[Link]("Average of elemnents in array:" + [Link]());

[Link]();

int num = 30;

int index = [Link](num);

if ( index != -1){

[Link]("Element " + num + " found at index: " + index);

}else{

[Link]("Element " + num + " not found");

[Link]("Size of Array: " + [Link]());

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

OUTPUT :

2.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() //read element of array
float [][] transpose( ) //find transpose of first matrix
float [][] matrixMultiplication(Matrix second ) //multiply two matrices
and return result
void displayMatrix(float [][]a) //display content of argument array
void displayMatrix() //display content
float maximum_of_array() // return maximum element of first array
float average_of_array( ) // return average of first array
create three object of Matrix class with different constructors in main
and test all the functions in main
import [Link];

public class Matrix

{ int row,column;

float mat[][];

Matrix(){

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

row=3;

column=3;

mat = new float[row][column];

Matrix(int r , int

c){ row = r;

column = c;

mat = new float[row][column];

Matrix(int

a[][]){ row =

[Link]; column =

a[0].length;

mat = new float[row][column];

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

for( int j=0 ; j<column ;

j++){ mat[i][j] = a[i][j];

void readMatrix(){

Scanner sc = new Scanner([Link]);

[Link]("Enter matrix elements:");

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

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

{ mat[i][j] = [Link]();

float[][] transpose(){

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

float trans[][] = new float[column][row];

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

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

{ trans[j][i] = mat[i][j];

return trans;

float[][] matrixMultiplication(Matrix second)

{ if ([Link] != [Link]) {

[Link]("Multiplication not possible");

return null;

float result[][] = new float[[Link]][[Link]];

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < [Link]; j++)

{ result[i][j] = 0;

for (int k = 0; k < [Link]; k++)

{ result[i][j] += [Link][i][k] *

[Link][k][j];

return result;

void displayMatrix() {

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

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

{ [Link](mat[i][j] + " ");

[Link]();

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

float max() {

float max = mat[0][0];

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

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

{ if (mat[i][j] > max) {

max = mat[i][j];

return max;

void displayMatrix(float[][] a)

{ for (int i = 0; i < [Link]; i++)

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

{ [Link](a[i][j] + " ");

[Link]();

float avg()

{ float sum = 0;

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

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

{ sum += mat[i][j];

return sum / (row * column);

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

public static void main(String

args[]){ Matrix m1 = new Matrix();

[Link]();

[Link]("Matrix 1:");

[Link]();

Matrix m2 = new Matrix(3,3);

[Link]();

[Link]("Matrix 2:");

[Link]();

int arr[][] = {{1,2,3},{4,5,6}};

Matrix m3 = new Matrix(arr);

[Link]("Transpose of Matrix 3:");

float result[][] = [Link]();

[Link](result);

[Link]("Multiplication of Matrix 1 and Matrix 2:");

float result2[][] = [Link](m2);

if (result2 != null)

{ [Link](result2);

[Link]("Maximum element in Matrix 1: " + [Link]());

[Link]("Average of elements in Matrix 1: " + [Link]());

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

OUTPUT :

2.3: Write a program to demonstrate usage of different methods of Wrapperclass


public class Wrapper_demo{

public static void main(String args[]){

byte b=10;

short s=20;

int i=30;

long l=40;

float f=50.0F;

double d=60.0D;

char c='a';

boolean b2=true;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

Byte byteobj=b;

Short shortobj=s;

Integer intobj=i;

Long longobj=l;

Float floatobj=f;

Double doubleobj=d;

Character charobj=c;

Boolean boolobj=b2;

[Link]("---Printing object values---");

[Link]("Byte object: "+byteobj);

[Link]("Short object: "+shortobj);

[Link]("Integer object: "+intobj);

[Link]("Long object: "+longobj);

[Link]("Float object: "+floatobj);

[Link]("Double object: "+doubleobj);

[Link]("Character object: "+charobj);

[Link]("Boolean object: "+boolobj);

byte bytevalue=byteobj;

short shortvalue=shortobj;

int intvalue=intobj;

long longvalue=longobj;

float floatvalue=floatobj;

double doublevalue=doubleobj;

char charvalue=charobj;

boolean boolvalue=boolobj;

//Printing primitives

[Link]("---Printing primitive values---");

[Link]("byte value: "+bytevalue);

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link]("short value: "+shortvalue);

[Link]("int value: "+intvalue);

[Link]("long value: "+longvalue);

[Link]("float value: "+floatvalue);

[Link]("double value: "+doublevalue);

[Link]("char value: "+charvalue);

[Link]("boolean value: "+boolvalue);

}}

OUTPUT :

2.4): Write a program to demonstrate usage of String and StringBuffer class


public class StringBuffer_demo1{

public static String concatWithString()

String t = "Java";

for (int i=0; i<10000;

i++){ t = t + "Tpoint";

return t;

public static String

concatWithStringBuffer(){ StringBuffer sb =

new StringBuffer("Java"); for (int i=0;

i<10000; i++){
Zala shraddha k 12302040701167
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link]("Tpoint");

return [Link]();

public static void main(String[] args){

long startTime = [Link]();

String temp=concatWithString();

[Link](temp);

[Link]("Time taken by Concating with String: "+([Link]()-startTime)+"ms");

startTime = [Link]();

String temp1= concatWithStringBuffer();

[Link](temp1);

[Link]("Time taken by Concating with StringBuffer: "+([Link]()-


startTime)+"ms");

OUTPUT :

2.5. Define a class Cipher with following data


Field:
String plainText;
int key
Functions:
Cipher(String plaintext,int key)
String Encryption( )
String Decryption( )
Read string and key from command prompt and replace every character of string
with character which is key place down from current character.
import [Link];

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

// Cipher class definition

class Cipher {

String plainText;

int key;

// Constructor to initialize text and key

Cipher(String plainText, int key)

{ [Link] = plainText;

[Link] = key;

// Encryption method

String Encryption() {

StringBuilder encryptedText = new StringBuilder();

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

char encryptedChar = (char) (ch + key); // Shift character by key positions

[Link](encryptedChar);

return [Link]();

// Decryption method

String Decryption() {

StringBuilder decryptedText = new StringBuilder();

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

char decryptedChar = (char) (ch - key); // Shift character back by key positions

[Link](decryptedChar);

return [Link]();

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

public class Code{

public static void main(String[] args)

{ Scanner sc = new Scanner([Link]);

// Input text and key

[Link]("Enter the plaintext: ");

String text = [Link]();

[Link]("Enter the key (number): ");

int key = [Link]();

// Create Cipher object and display results

Cipher cipher = new Cipher(text, key);

String encryptedText = [Link]();

[Link]("Encrypted Text: " + encryptedText);

// Creating another Cipher object for decryption

Cipher decryptCipher = new Cipher(encryptedText, key);

String decryptedText = [Link]();

[Link]("Decrypted Text: " + decryptedText);

OUTPUT :

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

PRACTICAL-3
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

import [Link];
class BankAccount
{ String depositorName;
int accNo;
String accType;
double balance;

static int accountCounter = 1;

void createAcc() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Depositor Name: ");
depositorName = [Link]();
[Link]("Enter Account Type: ");
accType = [Link]();
[Link]("Enter Initial Balance: ");
balance = [Link]();
accNo = accountCounter++; // Assign next serial number
[Link]("Account created successfully. Account Number: " + accNo);
}

void Deposit() {
Scanner sc = new Scanner([Link]);

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link]("Enter Amount to Deposit: ");


double amount = [Link]();
balance += amount;
[Link]("Amount Deposited Successfully. Updated Balance: " + balance);
}

void withdraw() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Amount to Withdraw: ");
double amount = [Link]();
if (amount <= balance)
{ balance -= amount;
[Link]("Withdrawal Successful. Updated Balance: " + balance);
} else {
[Link]("Insufficient Balance.");
}
}

void BalanceInquiry()
{ [Link]("Account Number: " + accNo);
[Link]("Depositor Name: " + depositorName);
[Link]("Account Type: " + accType);
[Link]("Current Balance: " + balance);
}

public static void main(String[] args)


{ BankAccount account = new BankAccount();
[Link]();
[Link]();
[Link]();
[Link]();

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
}
OUTPUT :

3.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.

import [Link];
class Time {
int hour, minute, second;

Time(int hour, int minute, int second)


{ [Link] = hour;
[Link] = minute;
[Link] = second;
}

void Sum(Time t1, Time t2)


{ [Link] = [Link] + [Link];
[Link] = [Link] + [Link] + [Link] / 60;
[Link] = [Link] + [Link] + [Link] / 60;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link] %= 60;
[Link] %= 60;

[Link]("Sum of Times: " + [Link] + "h " + [Link] + "m " + [Link] + "s");
}

public class clock{


public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);

[Link]("Enter first time (hour, minute, second): ");


int h1 = [Link](), m1 = [Link](), s1 = [Link]();
Time t1 = new Time(h1, m1, s1);

[Link]("Enter second time (hour, minute, second): ");


int h2 = [Link](), m2 = [Link](), s2 = [Link]();
Time t2 = new Time(h2, m2, s2);

Time result = new Time(0, 0, 0);


[Link](t1, t2);
}
}

OUTPUT :

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

3.3. Define a class with the Name, Basic salary and dearness allowance as data
[Link] 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

import [Link];
class Employee {
String name;
double basicSalary;
double dearnessAllowance;
double grossSalary;
double tds;
double netSalary;

Employee(String name, double basicSalary)


{ [Link] = name;
[Link] = basicSalary;
calculateSalaries();
}

void calculateSalaries()
{ dearnessAllowance = 0.74 * basicSalary;
grossSalary = basicSalary + dearnessAllowance;

if (grossSalary > 100000) {


tds = 0.10 * (grossSalary - 100000);
} else
{ tds = 0;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

netSalary = grossSalary - tds;


}

void displayDetails()
{ [Link]("Name: " +
name);
[Link]("Basic Salary (Yearly): Rs." + basicSalary);
[Link]("Dearness Allowance: Rs." + dearnessAllowance);
[Link]("Gross Salary: Rs." + grossSalary);
[Link]("TDS Deducted: Rs." + tds);
[Link]("Net Salary: Rs." + netSalary);
}

public class Salary {


public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);

[Link]("Enter Employee Name: ");


String name = [Link]();

[Link]("Enter Basic Salary (Yearly): ");


double basicSalary = [Link]();

Employee emp = new Employee(name, basicSalary);


[Link]();
}
}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

OUTPUT :

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

PRACTICAL-4
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.
import [Link];
abstract class Cricket
{ String name;
int age;
abstract void display();
abstract void setdata();
}
class Match extends Cricket
{ int no_of_odi;
int no_of_test;
void setdata() {
Scanner sc = new Scanner([Link]);
[Link]("Enter the name of the player: ");
name = [Link]();
[Link]("Enter the age:");
age = [Link]();
[Link]("Enter the no of odi:");
no_of_odi = [Link]();
[Link]("Enter the no of test:");
no_of_test = [Link]();

}
void display() {
[Link]("The name of the player: " + name);

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link]("The age:" + age);


[Link]("The no of odi:" + no_of_odi);
[Link]("The no of test:" + no_of_test);
}
}
public class demo {
public static void main(String[] args)
{ Match m[] = new Match[5];
for (int i = 0; i < 5; i++)
{ m[i] = new Match();
m[i].setdata();

for (int i = 0; i < 5; i++)


{ m[i].display();
}
}}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

OUTPUT:

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

4.2. Declare an interface called Property containing a method computePrice to compute


and returnthe price. The interface is to be implemented by following two classes i)
Bungalow and ii) [Link] the classes have following data members - name -
constructionArea. The class Bungalow has an additional data member called landArea.
Define computePricefor 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 [Link] Additional cost ( for Flat) : Rs. 200000/- ( for Bungalow ): Rs. 200/-
per sq. feet forlandArea Land cost ( only for Bungalow ): Rs. 400/- persq. [Link]
method main to show usage of methodcomputePrice.
interface Property
{
double computePrice();
String getName();
}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

class Bungalow implements Property


{ private String name;
private double constructionArea;
private double landArea;

public Bungalow(String name, double constructionArea, double landArea)


{ [Link] = name;
[Link] = constructionArea;
[Link] = landArea;
}

public double computePrice() {


double constructionCost = constructionArea * 500;
double additionalCost = landArea * 200;
double landCost = landArea * 400;
return constructionCost + additionalCost + landCost;
}

public String getName()


{ return name;
}
}

class Flat implements Property


{ public String name;
private double constructionArea;

public Flat(String name, double constructionArea)


{ [Link] = name;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link] = constructionArea;
}

public double computePrice() {


double constructionCost = constructionArea * 500;
double additionalCost = 200000;
return constructionCost + additionalCost;
}

public String getName()


{ return name;
}
}
public class PropertyDemo {
public static void main(String[] args) {
Property bungalow = new Bungalow("Luxury Bungalow", 2000, 1500);
Property flat = new Flat("City Apartment", 1200);

[Link]("Price of " + [Link]() + ": Rs. " + [Link]());


[Link]("Price of " + [Link]() + ": Rs. " + [Link]());
}
}
OUTPUT:

4.3. Define following classes and interfaces.


public interface GeometricShape {
public void describe();

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
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()

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
Define test class to call various methods of
Geometric Shape.
interface GeometricShape
{ void describe();
}
interface TwoDShape extends GeometricShape
{ double area();
}
interface ThreeDShape extends GeometricShape
{ double volume();
}
class Cone implements ThreeDShape
{ private double radius;
private double height;

public Cone(double radius, double height)


{ [Link] = radius;
[Link] = height;
}
public double volume() {
return (1.0 / 3) * [Link] * radius * radius * height;
}

@Override
public void describe() {
[Link]("This is a cone with radius " + radius + " and height " + height);
}
}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

class Rectangle implements TwoDShape


{ private double width, height;

public Rectangle(double width, double height)


{ [Link] = width;
[Link] = height;
}
public double area()
{ return width * height;
}
public double perimeter()
{ return 2 * (width + height);
}
public void describe() {
[Link]("This is a rectangle with width " + width + " and height " + height);
}
}
class Sphere implements ThreeDShape
{ private double radius;

public Sphere(double radius)


{ [Link] = radius;
}
public double volume() {
return (4.0 / 3) * [Link] * [Link](radius, 3);
}
public void describe() {
[Link]("This is a sphere with radius " + radius);

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
}
public class GeometricShapeTest
{ public static void main(String[] args)
{
TwoDShape rectangle = new Rectangle(10, 5);
ThreeDShape cone = new Cone(7, 14);
ThreeDShape sphere = new Sphere(6);

[Link]();
[Link]("Area of rectangle: " + [Link]());
[Link]("Perimeter of rectangle: " + ((Rectangle) rectangle).perimeter());

[Link]();
[Link]("Volume of cone: " + [Link]());

[Link]();
[Link]("Volume of sphere: " + [Link]());
}
}
OUTPUT:

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

PRACTICAL-5
5.1Define 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()
}
}
1) Write appropriate Constructor and create instance of Outer and inner class and call
the methods in main function
class CPU
{ double price;
public CPU(double price)
{ [Link] = price;
}
class Processor {
Zala shraddha k 12302040701167
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

double cores;
double cache;
String manufacturer;
public Processor(double cores, double cache, String manufacturer)
{ [Link] = cores;
[Link] = cache;
[Link] = manufacturer;
}
double getCache()
{ return cache;
}

void displayProcessorDetail()
{ [Link]("Processor Details:");
[Link]("Cores: " + cores);
[Link]("Cache: " + cache + " MB");
[Link]("Manufacturer: " + manufacturer);
}
}
protected class RAM
{ double memory;
String manufacturer;
double clockSpeed;
public RAM(double memory, String manufacturer, double clockSpeed)
{ [Link] = memory;
[Link] = manufacturer;
[Link] = clockSpeed;
}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

double getClockSpeed()
{ return clockSpeed;
}

void displayRAMDetail()
{ [Link]("RAM Details:");
[Link]("Memory: " + memory + " GB");
[Link]("Clock Speed: " + clockSpeed + " MHz");
[Link]("Manufacturer: " + manufacturer);
}
}}
public class Main {
public static void main(String[] args)
{ CPU cpu = new CPU(450.99);
[Link] processor = [Link] Processor(8, 16, "Intel");
[Link]();
[Link] ram = [Link] RAM(16, "Corsair", 3200);
[Link]();
}}
OUTPUT:

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

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

and display the necessary information. Also include a class, which has main to
carry out above-mentioned operations.

Package figures;
public class Shape {
public double calculateArea()
{ return 0;
}

public void displayInfo()


{ [Link]("This is a shape.");
}
}
public class Circle extends Shape
{ private double radius;

public Circle(double radius)


{ [Link] = radius;
}
public double calculateArea()
{ return [Link] * radius * radius;
}
public void displayInfo()
{ [Link]("Circle with radius: " + radius);
[Link]("Area: " + calculateArea());
}
}
1) Create a package new_figures, which has classes rectangle and triangle inherited
from class shape of package figures. Thus import the package [Link] out
necessary operations tocalculate area and display the necessary information.

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

package new_figures;

import [Link];
public class Rectangle extends Shape
{ private double length, width;

public Rectangle(double length, double width)


{ [Link] = length;
[Link] = width;
}
public double calculateArea()
{ return length * width;
}
public void displayInfo() {
[Link]("Rectangle with length: " + length + " and width: " + width);
[Link]("Area: " + calculateArea());
}
}

// Triangle class inheriting Shape


public class Triangle extends Shape
{ private double base, height;

public Triangle(double base, double height)


{ [Link] = base;
[Link] = height;
}
public double calculateArea()
{ return 0.5 * base * height;

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
public void displayInfo() {
[Link]("Triangle with base: " + base + " and height: " + height);
[Link]("Area: " + calculateArea());
}
}

3) Modify the above programs by importing both the packages in a file outside both the
packages, which contains main class.
import [Link];
import new_figures.Rectangle;
import new_figures.Triangle;

public class Main {


public static void main(String[] args) {
// Create and display a Circle
Circle circle = new Circle(5);
[Link]();
Rectangle rectangle = new Rectangle(4, 6);
[Link]();
Triangle triangle = new Triangle(3, 8);
[Link]();
}}
OUTPUT:

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

PRATICAL-6
6.1. Declare a class InvoiceDetail which accepts atype parameter which is of type Number
with following data members
class InvoiceDetail <N extends Number>
{ private String invoiceName;
private N amount;
private N Discount
// write getters, setters, and constructors
}
Call the methods in Main class.
class InvoiceDetail<N extends Number>
{ private String invoiceName;
private N amount;
private N discount;
public InvoiceDetail(String invoiceName, N amount, N discount)
{ [Link] = invoiceName;
[Link] = amount;
[Link] = discount;
}
public String getInvoiceName()
{ return invoiceName;
}
public N getAmount()
{ return amount;
}

public N getDiscount()
{ return discount;
}
public void setInvoiceName(String invoiceName) {

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link] = invoiceName;
}

public void setAmount(N amount)


{ [Link] = amount;
}

public void setDiscount(N discount)


{ [Link] = discount;
}
public void displayInvoice()
{ [Link]("Invoice Name: " + invoiceName);
[Link]("Amount: " + amount);
[Link]("Discount: " + discount);
}
}
public class Main {
public static void main(String[] args) {
InvoiceDetail<Integer> invoice1 = new InvoiceDetail<>("Laptop Purchase", 50000, 5000);
[Link]();
InvoiceDetail<Double> invoice2 = new InvoiceDetail<>("Mobile Purchase", 15000.50,
1500.75);
[Link]();
}}
OUTPUT:

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

6.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)
import [Link].*;
class Book implements Comparable<Book>
{ private int bookId;
private String title;
private String author;
private String publisher;
public Book(int bookId, String title, String author, String publisher)
{ [Link] = bookId;
[Link] = title;
[Link] = author;
[Link] = publisher;
}
public int getBookId()
{ return bookId;
}
public String getTitle()
{ return title;
}
public String getAuthor()
{ return author;
}
public String getPublisher()
{ return publisher;
}
public int compareTo(Book other) {
return [Link]([Link], [Link]);
}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

public String toString() {


return "Book ID: " + bookId + ", Title: " + title + ", Author: " + author + ", Publisher: " +
publisher;
}
}

class TitleComparator implements Comparator<Book> {

public int compare(Book b1, Book b2)


{ return
[Link]().compareTo([Link]());
}
}

class AuthorComparator implements Comparator<Book> {

public int compare(Book b1, Book b2) {


return [Link]().compareTo([Link]());
}
}
public class Main {
public static void main(String[] args)
{ List<Book> books = new ArrayList<>();
[Link](new Book(103, "The Alchemist", "Paulo Coelho", "HarperCollins"));
[Link](new Book(101, "Harry Potter", "J.K. Rowling", "Bloomsbury"));
[Link](new Book(102, "Inferno", "Dan Brown", "Doubleday"));

[Link]("Sorting by Book ID (Comparable):");


[Link](books);
for (Book book : books)
{ [Link](book);
Zala shraddha k 12302040701167
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

[Link]("\nSorting by Title (Comparator):");


[Link](books, new TitleComparator());
for (Book book : books)
{ [Link](book);
}

[Link]("\nSorting by Author (Comparator):");


[Link](books, new AuthorComparator());
for (Book book : books)
{ [Link](book);
}
}
}
OUTPUT:

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

PRATICAL-7
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 Arithmetic Exception and if balance is less than 500rs after
withdrawing then it throw custom exception, Not Enough Money Exception.
import [Link].*;
class NotEnoughMoneyException extends Exception
{ public NotEnoughMoneyException(String message)
{ super(message);
}
}

class Bank {
private double balance;

public Bank(double initialBalance)


{ [Link] = initialBalance;
}

public void deposit(double amount)


{ [Link]("Old Balance: " + balance);
balance += amount;
[Link]("New Balance: " + balance);
}

public void withdraw(double amount) throws NotEnoughMoneyException


{ [Link]("Old Balance: " + balance);
if (amount > balance) {
throw new ArithmeticException("Insufficient balance!");

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
balance -= amount;
if (balance < 500) {
throw new NotEnoughMoneyException("Balance after withdrawal is below Rs.500!");
}
[Link]("New Balance: " + balance);
}

public double getBalance()


{ return balance;
}
}

public class BankDemo {


public static void main(String[] args) {
Bank myAccount = new Bank(1000); // Initial balance Rs.1000

try {
[Link](500); // Depositing Rs.500
[Link](700); // Withdrawing Rs.700 (Balance remains Rs.800)
[Link](800); // This will trigger NotEnoughMoneyException
} catch (ArithmeticException e)
{ [Link]("Exception: " +
[Link]());
} catch (NotEnoughMoneyException e)
{ [Link]("Custom Exception: " + [Link]());
}
}
}

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

OUTPUT:

7.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.
import [Link].*;
import [Link];

class InvalidInputException extends Exception


{ public InvalidInputException(String message)
{ super(message);
}
}

public class AverageCalculator


{ public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);

try {
[Link]("Enter the number of elements (n): ");
int n = [Link]();

if (n == 0) {

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

throw new InvalidInputException("n cannot be zero!");


}

int[] A = new int[n];


int sum = 0;

[Link]("Enter " + n + " positive integers:");


for (int i = 0; i < n; i++) {
if (![Link]()) {
throw new InvalidInputException("Non-integer value detected!");
}
A[i] = [Link]();

if (A[i] < 0) {
throw new InvalidInputException("Negative numbers are not allowed!");
}

sum += A[i];
}

double average = (double) sum / n;


[Link]("The average is: " + average);

} catch (InvalidInputException e)
{ [Link]("Custom Exception: " + [Link]());
} catch (Exception e)
{ [Link]("Exception: Invalid
input!");
} finally
{ [Link]();

Zala shraddha k 12302040701167


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING

}
}
}
OUTPUT:

Zala shraddha k 12302040701167

You might also like