0% found this document useful (0 votes)
32 views

Computer Project Class 12th

Uploaded by

shajaralirizvi11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Computer Project Class 12th

Uploaded by

shajaralirizvi11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 91

0

UNITY COLLEGE

Acknowledgement
I would like to express my sincere gratitude to the following individuals who have significantly
contributed to my academic journey and success.

Firstly, I am profoundly grateful to our esteemed Principal, Mr. Deepak Mathews, whose
leadership, guidance, and unwavering support have been a source of inspiration throughout my
academic years. His commitment to excellence and encouragement has greatly motivated me to
achieve my goals.

I also extend my heartfelt thanks to my teacher, Mr. Monis Naqvi. His dedication, insightful
teaching, and encouragement have played a crucial role in my understanding of the subject
matter and my overall academic development. His passion for teaching and personal support
have been invaluable.

Thank you both for your exceptional support and guidance.

Feel free to adjust it if needed to better fit your personal style or specific contributions of your
principal and teacher.
1

INDEX

S.NO DATE TOPIC PAGE NO SIGNATURE


1 4/8/24 Inheritance java programs 1-20
2 4/8/24 String java programs 21-37
3 4/8/24 Array java programs 38-55
4 4/8/24 Object passing java programs 56-74
5 4/8/24 Other java programs 75-90
2

INHERITANCE JAVA PROGRAMS

(1) A class Employee contains employee details and another class Salary calculates the
employee’s net salary. The details of the two classes are given below: [10,2008] Class name : Employee
Data members : empNo : stores the employee number empName : stores the employee name empDesig
: stores the employee’s designation Member functions/methods Employee( ) : default constructor
Employee( . . . ) : parameterized constructor to assign values to employee number, name and
designation void display( ) : display the employee details Class name : Salary Data members : basic : float
variable to store the basic pay Member functions : Salary( . . . ) : parameterized constructor to assign
values to data members void calculate( ) : calculate the employee’s net salary according to the following
rules: DA = 10% of basic HRA = 15% of basic Salary = basic + DA + HRA PF = 8% of Salary Net salary =
Salary – PF Display the employee details and the Net salary Specify the class Employee giving details of
the constructors and member function void display( ).Using the concept of Inheritance specify the class
Salary giving details of constructor and the member function void calculate( ). The main function needs
to be written.

Import java.util.Scanner;
class Employee
{
int empno;String empname,empdesig;
Employee()
{
3

empno=0;
empname=null;
empdesig=null;
}
Employee(int a,String b,String c)
{
empno=a;
empname=b;
empdesig=c;
}
void display()
{
System.out.println("Employee name:"+empname);
System.out.println("Employee number:"+empno);
System.out.println("Employee designation:"+empdesig);
}
}

class Salary extends Employee


{
float basic;
Salary(float b,int n,String name,String d)
{
super(n,name,d);
basic=b;
}
void calculate()
{
double da=0.1*basic,hra=0.15*basic,gross=basic+da+hra,pf=0.08*gross,netpay=gross-pf;
System.out.println("\nEmployee Details");
System.out.println("----------------");
super.display();
System.out.println("\nPayment Details");
System.out.println("----------------");
System.out.println("Basic="+basic+"\nDA="+da+"\nHRA="+hra+"\nGross Pay="+gross+"\nNet
Pay="+netpay);
}
public static void main(String arg[])
{
Scanner ob=new Scanner(System.in);
4

System.out.print("Enter employee name:");


String name=ob.nextLine ();
System.out.print("Enter employee number:");
int n=ob.nextInt();
System.out.print("Enter employee designation:");
String d=ob.next();
System.out.print("Enter basic pay:");
float b=ob.nextFloat ();
Salary call=new Salary(b,n,name,d);
call.calculate();
}
}

Variable Description table

Variable Data
Scope Description
Name Type
empno int Instance Stores the employee number.
empname String Instance Stores the employee name.
empdesig String Instance Stores the employee designation.
basic float Instance Stores the basic pay of the employee.
Method Stores the Dearness Allowance which is 10% of the basic
da double
(calculate) pay.
Method Stores the House Rent Allowance which is 15% of the
hra double
(calculate) basic pay.
Method Stores the Gross Pay which is the sum of basic pay, DA,
gross double
(calculate) and HRA.
Method
pf double Stores the Provident Fund which is 8% of the gross pay.
(calculate)
Method Stores the Net Pay which is the Gross Pay minus the
netpay double
(calculate) Provident Fund.
name String Main method Temporary variable to take user input for employee name.
Temporary variable to take user input for employee
n int Main method
number.
d String Main method Temporary variable to take user input for employee
5

Variable Data
Scope Description
Name Type
designation.
b float Main method Temporary variable to take user input for basic pay.
Object of the Scanner class used for taking input from the
ob Scanner Main method
user.
Object of the Salary class used to call the calculate method
call Salary Main method
and display the employee and payment details.

This table provides an overview of each variable used in the program, including its data type,
scope, and purpose.

(2) A super class Worker has been defined to store the details of a worker. Define a sub class Wages to
compute the monthly wages for the worker. The details of both the classes are given below: Class name
Data members : : Worker Name : to store the name of the worker [ 10,2011] Basic Member functions :
to store the basic pay in decimal Worker(….) : parameterized constructor to assign values to the instance
variables void display() : display worker details class name Data members : Wages hrs : stores the hours
worked rate : stores rate per hour wage Member functions : stores the overall wage of the worker
Wages(….) : parameterized constructor to assign values to the instance variables of both classes double
overtime( ) : calculates and returns the overtime amount as (hours * rate ) void display() : calculates the
wage using the formula wage=overtime amount +basic pay and displays it along with other details
Specify the class Worker giving details of the constructor() and void display(). Using the concept of
inheritance, specify the class Wages giving details of the constructor(), double overtime() and void
display(). The main function needs to be wriiten

public class Worker

String Name;

double Basic;
6

public Worker(String n,double b)

Name=n;

Basic=b;

public void display()

System.out.println("Name of worker :"+Name);

System.out.println("Basic Pay of worker :"+Basic);

public class Wages extends Worker

int hrs;

double rate,wage;

public Wages(String a,double b,int c,double d)

super(a,b);

hrs=c;

rate=d;

wage=0.0;

}
7

public double overtime()

return(rate*hrs);

public void display()

double x=overtime();

wage=x+super.Basic;

super.display();

System.out.println("Wage="+wage);

Variable Description table

Variable Type Description


Name String Stores the name of the worker
Basic double Stores the basic pay of the worker
Constructor Description
Worker(String n, double b) Initializes the Name and Basic variables with provided values
Method Return Type Description
display() void Displays the name and basic pay of the worker

Wages Class

Variable Type Description


hrs int Stores the number of hours worked overtime
rate double Stores the rate of pay for overtime work
wage double Stores the total wage, calculated based on basic pay and overtime
Constructor Description
Wages(String a, double b, int Calls the superclass constructor to initialize Name and Basic, and
c, double d) initializes hrs, rate, and wage variables
8

Method Return Type Description


overtime() double Calculates and returns the overtime pay based on hours and rate
display() void Displays the worker details and the total wage

(3) A super class Record has been defined to store the names and ranks of 50 students. Define a sub
class Rank to find the highest rank along with the name. The details of both classes are given below:
[ 10,2012] Class name Record Data Mambers: name[] : to store the names of students rnk[] Member
functions: : to store the ranks of students Record() : default constructor void readvalues() : to store
name and ranks void display() Class name Rank Data Mambers: : displays the names and the
corresponding ranks index Member functions: : integer to store the index of the topmost rank Rank() :
constructor to invoke the base class constructor and to initialize index to 0. void highest() : finds the
index location of the topmost rank and stores it in index without sorting the array displays the name and
ranks along with the name having the topmost rank. Specify the class Record giving details of the
constructor(), void readvalues(), void display(). Using the concept of inheritance, specify the class Rank
giving details of constructor(), void highest() and void display(). The main function needs to be wriiten.

import java.io.*;

class Record {
public String name[];
public int rank[];
9

Record() {
name = new String[50];
rank = new int[50];
}

void readvalues() throws IOException {


BufferedReader B = new BufferedReader(new
InputStreamReader(System.in));
for (int i = 0; i < 50; i++) {
System.out.println("Enter name and corresponding
rank");
name[i] = B.readLine();
rank[i] = Integer.parseInt(B.readLine());
}
}

void display() {
System.out.println("The names and corresponding ranks
are: ");
for (int i = 0; i < 50; i++) {
System.out.println(name[i] + " " + rank[i]);
}
}
}

class Rank extends Record {


public int index; //

Rank() {
super();
index = 0;
}

void highest() {
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 50; j++) {
if (rank[i] < rank[j]) {
index = i;
}
}
}
}
10

void display() {
super.display();
System.out.println("The Topmost rank achiever is " +
name[index] + " " + rank[index]);
}
}

Variable Description table

Variable Name Data Type Scope Description


name String[] Record class Array to store the names of the students.
rank int[] Record class Array to store the ranks of the students.
index int Rank class Stores the index of the student with the highest rank.

Methods Description Table

Method Return
Scope Description
Name Type
Record
Record Constructor Initializes the name and rank arrays.
class
readvalues void
Record Reads the names and ranks from the user using
class BufferedReader.

display void
Record Displays the names and corresponding ranks of all the
class students.
11

Method Return
Scope Description
Name Type
Calls the parent class constructor and initializes the
Rank Constructor Rank class
index to 0.
highest void Rank class Finds the index of the student with the highest rank.
Displays the names and ranks of all the students and the
display void Rank class
topmost rank achiever.

(4) A super class Detail has been defined to store the details of a customer. Define a sub class Bill to
compute the monthly telephone charge of the customer as per the chart given below: [ 10,2013]
NUMBER OF CALLS RATE 1- 100 Only rental charge 101-200 60 paisa per call + rental charge 201-300 80
paisa per call + rental charge Above 300 1 rupee per call + rental charge The details of both the classes
are given below: Class Name Data members : Detail name : to store the name of the customer. address :
to store the address of the customer. telno : to store the phone number of the customer. rent Member
functions: : to store the monthly rental charge Detail(..) : parameterized constructor to assign values to
data members. void show() Class Name : Bill Data members : to display the detail of the customer. n : to
store the number of calls. amt Member functions: : to store the amount to be paid by the customer.
Bill(..) : parameterized constructor to assign values to data Members of both classes and to initialize amt
= 0.0. void cal() : calculates the monthly telephone charge as per the charge given above. void show() :
to display the detail of the customer and amount to be paid. Specify the class Detail giving details of the
constructor( ) and void show(). Uisng the concept of inheritance, specify the class Bill giving details of
the constructor( ), void cal() and void show(). THE MAIN FUNCTION AND

public class Detail

String name,address;
12

long telno;

double rent;

Detail(String n,String a,long t,double r)

name=n;

address=a;

telno=t;

rent=r;

void show()

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

System.out.println("Address:"+address);

System.out.println("Telephone Number:"+telno);

System.out.println("MonthlyRent:"+rent);

public class Bill extends Detail

int n;

double amt;

Bill(String a,String b,long c,double d,int e)

{
13

super(a,b,c,d);

n=e;

amt=0.0;

void cal()

if(n>=1 && n<=100)

amt=rent;

else if(n>=101 && n<=200)

amt=n*0.6+rent;

else if(n>=201 && n<=300)

amt=n*0.8+rent;

else if(n>300)

amt=n+rent;

void show()

{
14

super.show();

System.out.println("Number of calls="+n);

System.out.println("Amount to pay="+amt);

Variable Description table

Variable Data Type Description

name String Stores the name of the customer.

address String Stores the address of the customer.

telno long Stores the telephone number of the customer.

rent double Stores the monthly rent for the telephone service.

Bill Class (inherits from Detail)

Variable Data Type Description

n int Stores the number of calls made by the customer.

amt double Stores the calculated amount to be paid by the customer.


15

Method Description

Detail Class
Method Description

Detail(String n, String a, long t, double Constructor to initialize the Detail class


r) variables.

void show() Displays the details of the customer.

Bill Class
Method Description

Bill(String a, String b, long c, Constructor to initialize the Bill class variables and call the
double d, int e) Detail class constructor.

Calculates the amount to be paid based on the number of


void cal()
calls.

Displays the details of the customer along with the number


void show()
of calls and the amount to be paid.
16

(5) A super class Perimeter has been defined to calculate the perimeter of a parallelogram. Define a sub
class Area to compute the area of the parallelogram by using the required data members of the super
class. The details are given below: [ 10,2014] Class name Data Members : Perimeter a : to store the
length in decimal b Member functions: : to store the breadth in decimal Perimeter(…) : parameterized
constructor to assign values to data Members double Calculate() : calculate and return the perimeter of
a parallelogram as 2 *(length +breadth) void show() : to display the data members along with the
perimeter of the parallelogram. Class name Data Members : Area h : to store the height in decimal b
Member functions: : to store the area of the parallelogram Area(…) : parameterized constructor to
assign values to data Members of both classes. void doarea() : computes the area( breadth * height).7
void show() : to display the data members of both the classes along with the area and perimeter of the
parallelogram. Specify the class Perimeter giving details of the constructor(…), double Calculate() and
void show(). Using the concept of inheritance, specify the class Area giving details of the constructor(…),
void doarea() and void show(). The main function and algorithm need not be written.

public class Perimeter

double a,b;

Perimeter(double aa,double bb)

{
17

a=aa;b=bb;

double Calculate()

return (2*(a+b));

void show()

System.out.println("Length="+a);

System.out.println("Breadth= "+b);

System.out.println("Perimeter="+Calculate());

public class Area extends Perimeter

double h;

double area;

Area(double aa,double bb,double cc)

super(aa,bb);

h=cc;

void doarea()
18

area=b*h;

void show()

super.show();

System.out.println("Height= "+h);

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

Variable Description Table

Variable Name Data Type Description

a double Represents the length of the rectangle.

b double Represents the breadth of the rectangle.

Class Area

Variable Name Data Type Description

h double Represents the height used for area calculation.

area double Stores the calculated area of the rectangle.

Constructor Parameters for Perimeter

Parameter Name Data Type Description

aa double Initializes the length a of the rectangle.

bb double Initializes the breadth b of the rectangle.


19

Constructor Parameters for Area

Parameter Name Data Type Description

aa double Initializes the length a of the rectangle.

bb double Initializes the breadth b of the rectangle.

cc double Initializes the height h used for area calculation.

Methods in Perimeter

Method Name Return Type Description

Calculate double Calculates and returns the perimeter of the rectangle.

show void Displays the length, breadth, and perimeter of the rectangle.

Methods in Area

Method Name Return Type Description

doarea void Calculates the area of the rectangle using breadth b and height h.

show void Displays the length, breadth, perimeter, height, and area of the rectangle.
20

String programs

(1) Write a program to enter any sentence and check if it is a snowball string or not.
The words in the sentence may be separated by one or more spaces and
terminated by ‘.’ or ‘?’ only. The program will generate appropriate error message
for any other terminating character.

Example 1
INPUT: He may give bonus.
OUTOUT: IT IS A SNOWBALL STRING
Example 2
INPUT: Is the cold water frozen?
OUTPUT: IT IS A SNOWBALL STRING

import java.util.Scanner;
class Snowball{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = in.nextLine();
char last = s.charAt(s.length() - 1);
if(last != '.' && last != '?'){
System.out.println("INCORRECT TERMINATING CHARACTER.
INVALID INPUT");
return;
}
int len = 0;
String word = "";
boolean status = true;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
21

if(Character.isLetterOrDigit(ch))
word += ch;
else{
if(len == 0)
len = word.length();
else if(len + 1 != word.length()){
status = false;
break;
}
else
len = word.length();
word = "";
}
}
if(status)
System.out.println("IT IS A SNOWBALL STRING");
else
System.out.println("IT IS NOT A SNOWBALL STRING");
}
}
22

Variable description table

Variable
Data Type Description
Name
in Scanner An instance of the Scanner class used to take input from the user.
s String A string variable to store the input sentence entered by the user.
last char A character variable to store the last character of the input sentence s.
len int
An integer variable to store the length of the previous word.
Initialized to 0.
word String
A string variable to store the current word being processed from the
sentence.
status boolean
A boolean variable to keep track of whether the sentence is a
snowball string.
ch char
A character variable to store the current character being processed
from s.
23

(2) Write a program to accept a sentence which may


be terminated by either ‘.’, ‘?’ or ‘!’ only. Any other
character may be ignored. The words may be
separated by more than one blank space and are in
uppercase.
Perform the following tasks:
(a) Accept the sentence and reduce all the extra
blank space between two words to a single blank
space.
(b) Accept a word from the user which is a part of
the sentence along with its position number and
delete the word and display the sentence.
import java.util.Scanner;

public class DeleteWordFromPosition

public static void main(String args[])

int i=0,count=1,len=0,pos=0;

char ch=' ',last=' ';

String sen="",newsen="",wd="",wd1="";
24

Scanner sc=new Scanner(System.in);

System.out.print("ENTER A SENTENCE: ");

sen =sc.nextLine();

len = sen.length();

last = sen.charAt(len - 1);

if(last != '.' && last != '?' && last != '!')

System.out.println("INVALID INPUT.");

return;

sen = sen.toUpperCase();

System.out.print("WORD TO BE DELETED: ");

wd = sc.next();

wd = wd.toUpperCase();

System.out.print("WORD POSITION IN THE SENTENCE: ");

pos = sc.nextInt();

for(i=0;i< len;i++)

ch=sen.charAt(i);

if(ch==' '||ch=='.'||ch=='?'||ch=='!')

if(wd1.equals(wd)==true && (count)==pos)

/*do nothing*/
25

else

newsen=newsen+wd1+ch;

wd1="";

count++;

else

wd1=wd1+ch;

System.out.println("NEW SENTENCE:"+newsen);

}
26

Variable description table

Variable Type Initial Value Description


i int 0Loop counter variable used to iterate through the characters in the sentence.
count int 1
Counter variable to track the position of the current word in the sentence. Initialized
to 1 because word positions start from 1.
len int 0 Variable to store the length of the input sentence.
pos int 0 Variable to store the position of the word to be deleted as entered by the user.
ch char ' ' Variable to store the current character being processed from the sentence.
' Variable to store the last character of the input sentence to check if it ends with a
last char
' punctuation mark.
sen String "" Variable to store the input sentence entered by the user.
newsen String "" Variable to store the new sentence after deleting the specified word.
wd String "" Variable to store the word to be deleted as entered by the user.
wd1 String "" Variable to build the current word being processed from the sentence.
sc Scanner - Scanner object to read input from the user.
27

(3) A class Mix has been defined to mix two words, character by character, in the
following manner:
The first character of the first word is followed by the first character of the second
word and so on. If the words are of different length, the remaining characters of
the longer word are put at the end.
Example: If the First word is “JUMP” and the second word is “STROLL”, then the
required word will be “JSUTMRPOLL”
Some of the members of the class are given below:
Classname Mix
Data member/instance
variable:
wrd to store a word
len to store the length of the word
Member functions/methods:
Mix( ) default constructor to initialize the data members with legal initial values
void feedword( ) to accept the word in UPPER case
void mix_word( Mix P, Mix Q ) mixes the words of objects P and Q as stated above and stores the resultant
current object
void display( ) displays the word

import java.util.*;
class Mix
{
String wrd;
int len;
static Scanner x=new Scanner(System.in);
Mix()
{
wrd="";
len=0;
}
28

void feedword()
{
System.out.println( "Enter a word in UPPER CASE");
wrd=x.next();
len=wrd.length();
}
void mix_word(Mix P,Mix Q)
{
int s=(P.len <Q.len)? P.len:Q.len;
for(int i=0;i<s;i++)
wrd += P.wrd.charAt(i)+""+Q.wrd.charAt(i);
if (P.len > Q.len)
wrd +=P.wrd.substring(Q.len);
else
wrd +=Q.wrd.substring(P.len);
}
void display()
{
System.out.println("WORD = " + wrd);
}
static void main()
{
Mix obj=new Mix();
Mix obj1=new Mix();
Mix obj2= new Mix();
obj.feedword();
obj1.feedword();
obj2.mix_word (obj,obj1);
obj2.display();
}
}
29

Variable Description table

Variable Data
Scope Description
Name Type
Stores the word input by the user in upper case and the
wrd String Instance
resultant mixed word.
len int Instance Stores the length of the input word.
x Scanner Class (static) A static Scanner object used for taking user input.
obj Mix
Local (main An instance of Mix used to call methods and hold the
method) first word.
obj1 Mix
Local (main An instance of Mix used to call methods and hold the
method) second word.
obj2 Mix
Local (main An instance of Mix used to call methods and hold the
method) mixed word result.
30

(4) A class SwapSort has been defined to perform string related operations on a
word input.
Some of the members of the class are as follows:
Class name SwapSort
Data members/instance
variables:
wrd to store a word
len integer to store length of the word
swapwrd to store the swapped word
sortwrd to store the sorted word
Member
functions/methods:
SwapSort( ) default constructor to initialize data members with legal initial values
void readword( ) to accept a word in UPPER CASE
void swapchar( ) to interchange/swap the first and last characters of the word in ‘wrd’ and stores t
‘swapwrd’
void sortword( ) sorts the characters of the original word in alphabetical order and stores it in ‘so
void display( ) displays the original word, swapped word and the sorted word

import java.util.*;

public class SwapSort

String wrd,swapwrd,sortwrd;

int len;

static Scanner x=new Scanner(System.in);

SwapSort()

{
31

swapwrd="";

sortwrd="";

void readword()

System.out.println("Enter word in Upper case");

wrd=x.next();

len=wrd.length();

void swapchar()

swapwrd=wrd.charAt(len-1) + wrd.substring(1,len-1) + wrd.charAt(0);

void sortword()

char c;

for(int i=65;i<=90;i++)

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

c=wrd.charAt(j);

if(c==i)

sortwrd += c;

}
32

void display()

System.out.println("Original word = " + wrd);

System.out.println("Swapped word = " + swapwrd);

System.out.println("Sorted word = " + sortwrd);

static void main()

SwapSort x=new SwapSort();

x.readword();

x.swapchar();

x.sortword();

x.display();

}
33

Variable Description Table

Variable Name Type Description


wrd String Stores the word entered by the user.
swapwrd String Stores the word after swapping the first and last characters.
sortwrd String Stores the word with its characters sorted in alphabetical order.
len int Stores the length of the word.
x Scanner Scanner object used to read input from the user.
c char Temporary variable used to store individual characters while sorting
34

(5) A class ConsChange has been defined with the following details: [10]
Class name: ConsChange
Data members/instance variables:
word: stores the word len: stores the length of the word
Member functions/methods:
ConsChange(): default constructor
void readword(): accepts the word in lowercase
void shiftcons(): shifts all the consonants of the word at the beginning followed by the
vowels (e.g. spoon becomes spnoo)
void changeword(): changes the case of all occurring consonants of the shifted word
to uppercase, for e.g. (spnoo becomes SPNoo)
void show(): displays the original word, shifted word and the changed word
Specify the class ConsChange giving the details of the constructor ), void readword (
), void shiftcons (), void changeword() and void show(). Define the main() function to
create an object and call the functions accordingly to enable the task.

import java.io.*;

class ConsChange {
String word;
int len; public ConsChange() {
word = new String ();
len = word, length ();
}
public void readword () throws IOException {
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (isr);
System.out.println ("Enter the word"):
word = br.readLine();
word = word, trim().toLowerCase();
if (word.indexOf (") > 0)
word = word.substring (0, word.indexOf ("));
len = word, length();
}
35

public void shiftcons()


{
String cons = new String();
String vowel = new String();
for (int i= 0; i < len; i++)
{
char ch = word.charAt (i);
switch (ch)
{
case 'a';
case 'e';
case 'i';
case 'o';
case 'u';
vowel+ = ch;
break;
default:
cons + = ch ;
}
}
word = cons + vowel;
System.out.println (''Shifted Word+word):
changeword();
System.outprintln("Changed Word: "+ word);
}
public void changeword()
{
int pos = -1;
for (int i = 0; i < len; i++)
char ch = word.charAt (i);
switch (ch)
{
case 'a';
case 'e';
case 'o';
case 'u';
break;
default:
pos = i;
}
word = word.substring (0, pos + 1). toUpperCase ()+word.substring
(pos + 1);
}
}
36

Variable
Type Description
Name
word String Stores the input word from the user after processing.
len int Stores the length of the processed word.
cons String Temporary variable to store consonants extracted from word.
vowel String Temporary variable to store vowels extracted from word.

ch char
Temporary variable used to store individual characters while processing
word.
pos int Stores the position of the last consonant found in word.
37

Array Programs

(1) Design a class BinSearch to search for a particular value in an array.


Some of the members of the class are given below:
Classname BinSearch
Data members/instance
variables:
arr[ ] to store integer elements
n integer to store the size of the array
Member functions/methods:
BinSearch(int nn )
void fillarray( )
void sort( )
void sort( ) searches for the value ‘v’ using binary search and recursive technique and re
location if found otherwise returns -1

import java.util.*;

class BinSearch

int arr[];

int n;

static Scanner x=new Scanner(System.in);

BinSearch(int nn)

n=nn;

}
38

void fillarray()

arr=new int[n];

System.out.println("Enter "+n + " elements");

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

arr[i]=x.nextInt();

void sort()

int t;

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

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

if (arr[j]>arr[j+1])

t=arr[j];

arr[j]=arr[j+1];

arr[j+1]=t;

int bin_search(int l,int u, int v )

int m=(l+u)/2;
39

if(arr[m]==v)

return m;

else if(l>u)

return -1;

else if (arr[m]>v)

return bin_search(l,m-1,v);

else

return bin_search(m+1,u,v);

static void main()

BinSearch obj = new BinSearch(5);

obj.fillarray();

obj.sort();

System.out.println(" location: " + obj.bin_search(0,4,20) );

}
40

Variable Description table

Variable
Data Type Scope Description
Name
Instance
arr int[] Array to hold the elements entered by the user.
variable
Instance
n int The number of elements in the array.
variable
x Scanner Static variable Scanner object to read user input.
Temporary variable used for swapping elements
t int Local variable
during sorting.
Loop variable used for iterating through the array
i int Local variable
during sorting and filling.
Loop variable used for iterating through the array
j int Local variable
during sorting.
Method
l int Lower bound index for the binary search.
parameter
Method
u int Upper bound index for the binary search.
parameter
Method
v int The value to be searched for in the array.
parameter
m int Local variable Middle index calculated during the binary search.
obj BinSearch Local variable Object of the BinSearch class used to call its methods.
41

(2) Design a class MatRev to reverse each element of a matrix.


Example:

Some of the members of the class are given below:

Class name MatRev


Data members/instance
variables:
arr[ ][ ] to store integer elements
m to store the number of rows
n to store the number of columns
Member functions/methods:
MatRev(int mm, int nn) parameterised constructor to initialise the data members m = mm and n = nn
void fillarray( ) to enter elements in the array
int reverse(int x) returns the reverse of the number x
void revMat( MatRev P) reverses each element of the array of the parameterized object and stores it in the
current object
void show( ) displays the array elements in matrix form

import java.io.*;

import java.util.*;

class MatRev{

private int arr[][];

private int m;

private int n;

public MatRev(int mm, int nn) {


42

m=mm;

n = nn;

arr=newint[m][n];

public void fillArray( )throws IOException{

Scanner sc = new Scanner(System.in);

System.out.println("Enter matrix elements::");

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

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

arr[i][j] = sc.nextInt();

public int reverse(int x) {

int rev = 0;

for(int i = x; i != 0; i /= 10)

rev = rev * 10 + i % 10;

return rev;

public void revMat(MatRev p) {

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

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

this.arr[i] [j] = reverse(p.arr[i] [j]);

}
43

public void show() {

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

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

System, out. print(arr[i][j] + "\t");

System.out.println();

public static void main(String args[])throws IOException{

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of rows::");

int x = sc.nextInt();

System.out.print("Enter number of columns::");

int y = sc.nextInt();

MatRev obj 1 = new MatRev(x, y);

MatRev obj2 = new MatRev(x, y);

obj1.fillArray();

obj2.revMat(obj 1);

System.out.println("Original Matrix is::");

obj1.show();

System.out.println("Matrix with reversed elements");

obj2.show();
44

Variable Description Table

Variable
Data Type Scope Description
Name

arr int[][] Instance variable 2D array to store the matrix elements

m int Instance variable Number of rows in the matrix

n int Instance variable Number of columns in the matrix

Method local
rev int Used to store the reversed number in the reverse method
variable

Method local
sc Scanner Scanner object to read input from the user
variable

Method local
x int Number of rows input by the user
variable

Method local
y int Number of columns input by the user
variable

Method local First instance of the MatRev class used to store the original
obj1 MatRev
variable matrix

Method local Second instance of the MatRev class used to store the
obj2 MatRev
variable reversed matrix
45

(3) Two matrices are said to be equal if they have the same dimension and their
corresponding elements are equal.
For example, the two matrices A and B given below are equal:

Design a class EqMat to check if two matrices are equal or not. Assume that the two
matrices have the same dimension.
Some of the members of the class are given below:

Class name EqMat


Data members/instance variables:
a[ ][ ] to store integer elements
m to store the number of rows
n to store the number of columns
Member functions/methods:
EqMat(int mm, int nn) parameterised constructor to initialise the data members m = mm and n = nn
void readarray( ) to enter elements in the array
int check(EqMat P, EqMat Q) checks if the parameterized objects P and Q are equal and returns 1 if true, othe
void print( ) displays the array elements

import java.util.*;

class EqMat

int a[][];

int m;

int n;
46

static Scanner sc=new Scanner(System.in);

EqMat(int mm,int nn)

m=mm;

n=nn;

a=new int[m][n];

void readarray()

System.out.println("enter" + (m*n) + "elements" );

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

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

a[i][j]=sc.nextInt();

int check(EqMat P,EqMat Q)

for (int i=0;i<P.m;i++)

for (int j=0;j<P.n;j++)

if (P.a[i][j]!=Q.a[i][j])

return 0;

return 1;

}
47

void print()

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

System.out.println();

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

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

public static void main()

EqMat ob1=new EqMat(3,3);

EqMat ob2=new EqMat(3,3);

System.out.println("enter nos for the Ist Matrix");

ob1.readarray();

System.out.println("enter nos for the 2nd Matrix");

ob2.readarray();

if (ob1.check(ob1,ob2)==1)

System.out.println("Equal Matrix");

ob1.print();

ob2.print();

else
48

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

Variable Description Table

Variable Name Type Description


a int[][] A 2D array to store the elements of the matrix.
m int Number of rows in the matrix.
n int Number of columns in the matrix.
sc static Scanner A static Scanner object for reading input from the console.
mm int Parameter for initializing the number of rows.
nn int Parameter for initializing the number of columns.
i int Loop variable used for iterating through rows.
j int Loop variable used for iterating through columns.
P EqMat Parameter representing the first matrix in the check method.
Q EqMat
Parameter representing the second matrix in the check
method.
ob1 EqMat Object representing the first matrix.
ob2 EqMat Object representing the second matrix.
49

(4) A class Trans is defined to find the transpose of a square matrix. A transpose of a matrix
is obtained by interchanging

the elements of the rows and columns.

Example: If size of the matrix = 3, then

ORIGINAL TRANSPOSE

11 5 7 11 8 1

8 13 9 5 13 6

1 6 20 7 9 20

Some of the members of the class are given below:

Class name : Trans

Data members/instance variable:

arr[][] : to store integers in the matrix

m : integer to store the size of the matrix

Methods/Member functions:

Trans(int mm) : parameterised constructor to initialise the data member

m = mm

void fillarray() : to enter integer elements in the matrix

void transpose() : to create the transpose of the given matrix

void display() : displays the original matrix and the transport matrix by

invoking the method transpose()

Specify the class Trans giving details of the constructor(), void fillarray(), void transpose() and
void display().
50

Define a main() function to create an object and call the functions accordingly to enable the task.

. import java.util.Scanner;

class Trans

int arr[][];

int m;

public Trans(int mm)

m=mm;

arr=new int[m][m];

public void fillarray()

Scanner sc=new Scanner(System.in);

System.out.println(“Enter the array elements”);

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

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

arr[i][j]=sc.nextInt();

}
51

public void transpose()

System.out.println(“TRANSPOSE”);

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

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

System.out.print(arr[j][i]+”\t”);

System.out.println();

Variable Description table

Variable Name Data Type Description

arr int[][] A 2D array to store the matrix elements.

m int The size of the matrix (number of rows and columns, as it


is a square matrix).

sc Scanner A Scanner object to read input from the user.

mm int Parameter passed to the constructor to initialize the size of


the matrix.

i int Loop counter for iterating through rows of the matrix.

j int Loop counter for iterating through columns of the matrix.


52

(5) A class Admission contains the admission numbers of 100 students. Some of the data
members/member functions are given below: [10]

Class name: Admission

Data member/instance variable:

Adno[]: integer array to store admission numbers

Member functions/methods:

Admission(): constructor to initialize the array elements

void fill Array(): to accept the elements of the array in ascending order

int binSearch(int 1, int u, int v): to search for a particular admission number (v) using binary
search and recursive technique and returns 1 if found otherwise returns -1

Specify the class Admission giving details of the constructor, void fill Array() and int
binSearch(int, int, int). Define the main() function to create an object and call the functions
accordingly to enable the task.

Import java.util.Scanner;

class Admission {

int adno[];

public Admission()

adno=newint[100];

public void fillArray()


53

Scanner sc=new Scanner(System.in);

System.out.print(“Enter admission numbers in ascending order:”);

for(int i=0;i<adno.length;i++)

adno[i]=sc.nextInt();

public int binSearch(int 1, int u, int v)

int m=(1+u)/2;

if(1>u)

return-1;

else if(v = =adno[m])

return 1;

elseif(v>adno[m])

return binSearch(m+1, u, v);

else

return binSearch(1, m-1, v);

public static void main(String args[])

Scanner sc = new Scanner(System.in);

Admission obj = new Admission();


54

obj.fillArray();

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

int key = sc.nextInt();

int result = obj .binSearch(0, 4, key);

if(result == 1)

System.out.println(key+"available.");

else

System.out.println(key +" unavailable.");

Variable Description Table

Variable Name Data Type Description

adno int[] An array to store admission numbers.

sc Scanner A Scanner object to read input from the user.

i int Loop counter for iterating through the array adno when
filling it with admission numbers.

l int The lower bound index for the binary search.

u int The upper bound index for the binary search.

v int The value to search for in the array adno.

m int The middle index of the current search range in the binary
search.

key int The key value entered by the user to search for in the array
adno.
55

result int The result of the binary search, indicating if the key was
found

Object Passing Programs

(1) A class Mixer has been defined to merge two sorted integer arrays in ascending order.
Some of the members of the class are given below: [10]

Class name: Mixer

Data members/instance variables:

int arr[ ]: to store the elements of an array

int n: to store the size of the array

Member functions:

Mixer(int nn): constructor to assign n=nn

void accept(): to accept the elements of the array in ascending order without any duplicates

Mixer mix (Mixer A): to merge the current object array elements with the parameterized array
elements and return the resultant object

void display(): to display the elements of the array

Specify the class Mixer, giving details of the constructor(int), void accept(), Mixer mix(Mixer)
and void display(). Define the main( ) function to create an object and call the function
accordingly to enable the task.

import java.util.*;

class Mixer

intarr[];
56

int n;

static Scanner sc=new Scanner(System.in);

Mixer(int nn)

n=nn;

arr=new int[n];

void accept()

System.out.println("Enter"+ n+ " elements in ascending order");

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

arr[i]=sc.nextInt();

Mixer mix(Mixer A)

Mixer B=new Mixer(n+A.n);

int x=0, y=0, z=0;

while(xA.arr[y])

B.arr[z]=A.arr[y];

y++;

else

{
57

B.arr[y]=arr[x];

x++;

z++;

while(x<n)

B.arr[z++]=arr[x++];

while(y<A.n)

B.arr[z++]=A.arr[y++];

return B;

void display()

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

System.out.println(arr[i]);

static void main()

R=P.mix(Q);

R. display();

}
58

Variable Description table

Variable Name Data Type Description

arr int[] An array to store elements in ascending order.

n int The number of elements in the array.

sc Scanner A static Scanner object to read input from the user.

nn int Parameter passed to the constructor to initialize the size of


the array.

A Mixer A Mixer object passed as an argument to the mix


method.

B Mixer A new Mixer object created in the mix method to


store the merged elements.

x int Loop counter for iterating through the arr array of the
current Mixer object.

y int Loop counter for iterating through the arr array of the
Mixer object A.

z int Loop counter for iterating through the arr array of the
Mixer object B.

R Mixer A Mixer object to store the result of merging two


Mixer objects.

P Mixer A Mixer object to be merged.

Q Mixer Another Mixer object to be merged.


59

(2) A class Shift contains a two-dimensional integer array of order (m×n) where the
maximum values of both m and n are 5. Design the class Shift to shuffle the matrix (i.e.
the first row becomes the last, the second row becomes the first and so on). The details of
the members of the class are given below: [10]

Class name: Shift

Data member/instance variable:

mat[][]: stores the array element

m: integer to store the number of rows

n: integer to store the number of columns

Member functions/methods:

Shift(int mm, int nn): parameterized constructor to initialize the data members m=mm and n=nn

void input(): enters the elements of the array

void cyclic(Shift p): enables the matrix of the object (P) to shift each row upwards in a cyclic
manner and store the resultant matrix in the current object

void display(): displays the matrix elements

Specify the class Shift giving details of the constructor(), void input(), void cyclic(Shift) and
void display(). Define the main() function to create an object and call the methods accordingly to
enable the task of shifting the array elements.

Import java.io.*;

class Shift

{
60

intmat[][];

int m;

int n;

public Shift(int mm, int nn){

m = mm;

n = nn;

m = 5;

n = 5;

mat = new int[m][n];

public void input()throws IOException {

InputStreamReader input = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(input);

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

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

System.out.print("Elements of the matrix: "+i+", "+j+":");

mat[i] [j] = Integer.parseInt(br.readLine());

public void cyclic(Shift p){

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

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

if(i == 0)

this.mat[m-1][j] = p.mat[i][j];
61

else

this.mat[i-1][j] = p.mat[i][j];

public void display() {

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

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

System, out .print(mat[i] [j]+" \t");

System.out.println();

public static void main(String args[])throws IOException{

InputStreamReader input = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(input);

System.out.print("M = ");

int mm=Integer. parseInt(br.readLine());

System.out.print("N = ");

int nn = Integer.parseInt(br.readLine());

Shift obj 1 = new Shift(mm, nn);

Shift obj2 = new Shift(mm, nn);

obj 1.input();

System.out.println("Original Matrix entered by you :");

obj1.display();

obj2.cyclic(obj1);
62

System.out.println("New Shifted Matrix is :");

obj2.display();

Variable Description Table

Variable/Method Type Scope Description

mat int[][] Instance A 2D array representing the matrix.


Initialized with size m by n.

m int Instance The number of rows in the matrix.

n int Instance The number of columns in the matrix.

Shift(int mm, int nn) Constructor Instance Constructor initializing the matrix
dimensions to 5x5 regardless of input parameters mm and nn.

input() void Instance Method to take input from the user to fill the
matrix mat.

cyclic(Shift p) void Instance Method to cyclically shift the matrix by one


row down.

display() void Instance Method to print the matrix mat.

main(String[] args) void Static The main method to execute the program, create
Shift objects, and perform matrix input, display, and shift operations.

input InputStreamReader Local to input(), main() Reader object


to take user input from the console.

br BufferedReader Local to input(), main() Buffered


reader object to read user input from input.

mm int Local to main() Number of rows input by the user.

nn int Local to main() Number of columns input by the


user.
63

obj1 ShiftLocal to main() First Shift object representing the


original matrix.

obj2 ShiftLocal to main() Second Shift object representing the


cyclically shifted matrix.

(3) A class Adder has been defined to add any two accepted time.

Example: Time A – 6 hours 35 minutes

Time B – 7 hours 45 minutes

Their sum is – 14 hours 20 minutes ( where 60 minutes = 1 hour)

The details of the members of the class are given below:

Class name Adder

Data member/instance variable:

a[ ] integer array to hold two elements (hours and minutes)

Member

functions/methods:

Adder( ) constructor to assign 0 to the array elements

void readtime( ) to enter the elements of the array

void addtime( Adder X, Adder Y) adds the time of the two parameterized objects X and Y and
stores the sum in the current calling object

void disptime( ) displays the array elements with an appropriate message (i.e.
hours = and minutes = )

import java.util.*;

public class Adder

{
64

int a[]=new int[2];

static Scanner x=new Scanner(System.in);

Adder()

{ a[0]=0;a[1]=0;

void readtime()

System.out.println("Enter hours and minutes");

a[0]=x.nextInt();

a[1]=x.nextInt();

void disptime()

System.out.println("Hours=" + a[0]);

System.out.println("Minutes=" + a[1]);

void addtime(Adder X,Adder Y)

a[1]=X.a[1] + Y.a[1];

a[0]=a[1]/60;

a[1]=a[1]%60;

a[0] += X.a[0] + Y.a[0];

static void main()


65

Adder a=new Adder();

Adder b=new Adder();

Adder c=new Adder();

a.readtime();

b.readtime();

c.addtime(a,b);

c.disptime();

Variable Description Table

Variable Type Scope Description

a int[] Instance (non-static) An array of integers to store


hours and minutes.

x Scanner Static A static Scanner object to read input


from the user.

a[0] int Instance (non-static) The first element of the array


a, representing hours.

a[1] int Instance (non-static) The second element of the


array a, representing minutes.

X Adder Method parameter An Adder object passed as a


parameter to the addtime method.

Y Adder Method parameter An Adder object passed as a


parameter to the addtime method.
66

(4) The coordinates of a point P on a two-dimensional plane can be represented by P(x, y)


with x as the x-coordinate and y as the y-coordinate. The coordinates of the midpoint of
two points P1(x1, y1) and P2(x2, y2) can be calculated as P(x, y) where: [10]

x=x1+x22,y=y1+y22

Design a class Point with the following details:

Class name: Point

Data Members/instance variables:

x: stores the x-coordinate

y: stores the y-coordinate

Member functions:

Point (): constructor to initialize x = 0, y = 0

void readpoint (): accepts the coordinates x and y of a point

Point midpoint (Point A, Point B): calculates and returns the midpoint of the two points A and B

void displaypoint (): displays the coordinates of a point

Specify the class Point giving details of the constructor (), member functions void readpoint ( ),
Point midpoint (Point, Point) and void displaypoint () along with the main () function to create
an object and call the functions accordingly to calculate the midpoint between any two given
points.

import java.io.*;

class Point
67

int x;

inty;

public Point ()

x = 0;

y = 0;

public void read point () throws IOException

Buffered Reader br = new BufferedReader(new InputStreamReader(Systemin);

System.out.println("Enter the value of x'');

x = Integer.parselnt (br. readLine());

System.out.printing'Enter the value of y ");

y = Integer.parselnt(br. readLine ( ));

public Point midpoint(Point A, Point B)

x = (A.x+B.x)/2;

y = (A.y + B.y)/2;

public void displaypoint()

System.out.println(x);
68

System. out.println(y);

public void main()

Point obj 1 = new Point();

obj1.readpoint();

Point obj 2 = new Point();

obj2.readpoint();

Point obj 3 = new Point();

Point obj4 = obj3.midpoint(obj 1, obj2);

obj4.displayPoint();

Variable Description table

Variable Type Scope Description

x int Instance (non-static) Stores the x-coordinate of the point.

y int Instance (non-static) Stores the y-coordinate of the point.

br BufferedReader Method (local)Reads input from the user.

obj1 Point Method (local)Instance of Point used in the main


method.

obj2 Point Method (local)Instance of Point used in the main


method.

obj3 Point Method (local)Instance of Point used to calculate


the midpoint.
69

obj4 Point Method (local)Stores the result of the midpoint


calculation.

(5) A class Combine contains an array of integers which combines two arrays into a single
array including the duplicate elements, if any, and sorts the combined array. Some of the
members of the class are given below: [10]

Class name: Combine

Data Members/instance variables:

com[]: integer array

size: size of the array

Member functions/methods:

Combine(nt nn): parameterized constructor to assign size = nn

void inputarray(): accepts the array elements.

void sort(): sorts the elements of the combined array in ascending order using the selection sort
technique.

void mix(Combine A, Combine B): combines the parameterized object arrays and stores the
result in the current object array along with duplicate elements, if any.

void display(): displays the array elements

Specify the class Combine giving details of the constructor (int), void inputarray(), void sort(),
void mix (Combine, Combine) and void display (). Also, define the main() function to create an
object and call the methods accordingly to enable the task.

rt java. io.*;

class Combine

{
70

int com [], size;

public Combine (int nn)

size = nn;

com = new int [size];

void inputarray () throws IOException

Buffered Reader br = new

Buffered Reader [new Input Stream Reader (System.in)];

int i;

for (i = 0; i < size; i++)

System.out.println ("Enter a no.");

com [i] = Integer.parseInt[br.readLine ()];

void sort ()

int i, j, t;

for (i = 0; z < size; i++)

for (j = i + 1; j < size; j++) { if (com[i] > com [j])

{
71

t = com [i];

com [i] = com [j];

com [j] = t;

void mix (Combine A, Combine B)

int i, j;

for (i = 0, j = 0; i < A.size; i ++, j++)

com[j] = A.com[i];

for (i = 0; i < B.size; i++, j++)

com [j] = B.com [i];

void display ()

int i;

for (i = 0; i < size; i ++)

{
72

System.out.println(com[i]);

public static void main (String args [ ]) throws IOException

Combine c1 = new Combine(5);

Combine c2 = new Combine(3);

Combine c3 = new Combine(8);

c1.inputarray();

c2.inputarray();

c3.mix (c1, c2);

c3.sort();

c3.display();

}
73

Variable Description Table

Variable Description Type Scope

com Array to store integer elements int[] Instance variable of


the Combine class

size Number of elements in the com array int Instance


variable of the Combine class

br BufferedReader object for reading input from the console


BufferedReader Local variable in the inputarray method

i Loop counter for iterating over array elements int Local


variable in inputarray, sort, and mix methods

j Loop counter for nested loops and merging arrays int


Local variable in sort and mix methods

t Temporary variable for swapping elements during sorting


int Local variable in sort method

args Command-line arguments array String[] Parameter of


the main method
74

Other Programs

(1) A class Palin has been defined to check whether a positive number is a Palindrome
number or not.

The number ‘N’ is palindrome if the original number and its reverse are same. Some of the
members of the class are given below:

Class name Palin

Data members/instance

variables:

num integer to store the number

revnum integer to store the reverse of the number

Methods/Member functions:

Palin( ) constructor to initialize data members with legal initial values

void accept( ) to accept the number

int reverse(int y) reverses the parameterized argument ‘y’ and stores it in ‘revnum’
using recursive technique

void check( ) checks whether the number is a Palindrome by invoking the


function reverse( ) and display the result with an appropriate message
75

import java.util.*;

public class Palin

int num,revnum;

static Scanner x=new Scanner(System.in);

Palin()

num=0;revnum=0;

void accept()

System.out.println( "Enter a number");

num=x.nextInt();

int reverse(int y)

if(y>0)

revnum =revnum * 10 + y%10;

return reverse(y/10);

else

return revnum;

}
76

void check()

int p=num;

if( num==reverse(p))

System.out.println("palindrome");

else

System.out.println("not a palindrome");

static void main()

Palin obj=new Palin();

obj.accept();

obj.check();

Variable Description Table

Variable Description Type Scope

num Stores the number entered by the user int Instance


variable of the Palin class

revnum Stores the reversed number during recursion int


Instance variable of the Palin class

x Scanner object for reading input from the console


Scanner Static variable of the Palin class

y Parameter in the reverse method for recursionint Local


variable in the reverse method
77

p Temporary variable to hold the original number for


comparison int Local variable in the check method

(2) Design a class ArmNum to check if a given number is an Armstrong number or not. [A
number is said to be Armstrong if sum of its digits raised to the power of length of the
number is equal to the number]

Example:

371 = 33 + 73 + 13

1634 = 14 + 64 + 34 + 44

54748 = 55 + 45 + 75 + 45 + 85

Thus, 371, 1634 and 54748 are all examples of Armstrong numbers.

Some of the members of the class are given below:

Class name ArmNum

Data members/instance variables:

n to store the number

l to store the length of the number

Methods/Member functions:

ArmNum (int nn) parameterized constructor to initialize the data

member n=nn

int sum_pow(int i) returns the sum of each digit raised to the power of the length of the
number using
78

recursive technique

eg. 34 will return 32 + 42 (as the length of the

number is 2)

void isArmstrong( ) checks whether the given number is an

Armstrong number by invoking the function

sum_pow( ) and displays the result with an appropriate message

import java.io.*;

import javautil.*;

class ArmNum

private int n;

private int 1;

public ArmNum(int num)

n = num;

i = 0;

for(int i = n; i! = 0; i/= 10)

i++;

public int sumPow(int i)

if(i < 10)

return (int)Math.pow(i, 1);

return (int)Math.pow(i % 10, 1) + sumPow(i/10);


79

public void isArmstrong()

if(n == sumPow(n))

System.out.println(n+" is an Armstrong number.");

else

System.out.println(n+ " is not an Armstrong number.");

public static void main(String args[])throws IOException{

Scanner sc = new Scanner(System.in);

System.out.print("N =");

int num = sc.nextInt();

ArmNum obj = new ArmNum(num);

obj.isArmstrong();

Variable Description Table

Variable Description Type Scope

n Stores the number to be checked if it is an Armstrong number


int Instance variable of the ArmNum class

i Used as a temporary variable to store digits and count the number


of digits int Instance variable of the ArmNum class (note: this is
incorrectly defined)

sc Scanner object for reading input from the console Scanner


Local variable in the main method
80

num Stores the number read from user input int Local variable
in the main method

(3) Design a class Perfect to check if a given number is a perfect number or not. [ A number
is said to be perfect if sum of the factors of the number excluding itself is equal to the
original number]

Example : 6 = 1 + 2 + 3 (where 1, 2 and 3 are factors of 6, excluding itself)

Some of the members of the class are given below:

Class name Perfect

Data members/instance variables:

num to store the number

Methods/Member functions:

Perfect (int nn) parameterized constructor to initialize the data member num=nn

int sum_of_factors(int i) returns the sum of the factors of the number(num), excluding
itself, using recursive technique

void check() checks whether the given number is perfect by invoking the
function sum_of_factors() and displays the result with an appropriate message

import java.util.*;

class Perfect

int num;
81

Perfect(int nn)

num=nn;

int sum_of_factors(int i)

if (i == num)

return 0;

else if (num%i==0)

return i + sum_of_factors(i+1);

else

return sum_of_factors(i+1);

void check()

int s=sum_of_factors(1);

if (s==num)

System.out.println(num+"is a perfect number");

else

System.out.println(num+"is not a perfect number");

public static void main()

Scanner sc=new Scanner(System.in);


82

System.out.println("Enter a number");

int no=sc.nextInt();

Perfect ob=new Perfect(no); // OR Perfect ob=new Perfect(6);

ob.check(); // ob.check();

Variable Description Table

Variable Description Type Scope

num Stores the number to be checked if it is a perfect number


int Instance variable of the Perfect class

i Parameter used in the sum_of_factors method for recursion


int Local variable in the sum_of_factors method

s Stores the sum of the factors of num computed by the


sum_of_factors method int Local variable in the check method

sc Scanner object for reading input from the console


ScannerLocal variable in the main method

no Stores the number read from user input int Local


variable in the main method

ob Instance of the Perfect class Perfect Local variable in the


main method
83

(4) Design a class Convert to find the date and the month from a given day number for a
particular year.

Example: If day number is 64 and the year is 2020, then the corresponding date would be:

March 4, 2020 i.e. (31 + 29 + 4 = 64)

Some of the members of the class are given below:

Classname Convert

Data members/instance variables:

n integer to store the day number

d integer to store the day of the month

(date)

m integer to store the month

y integer to store the year

Methods/Member functions:

Convert ( ) constructor to initialize the data members with legal initial


values

void accept( ) to accept the day number and the year

void day_to_date( ) converts the day number to its corresponding date for a
particular year and stores the date in ‘d’ and the month in ‘m’

void display( ) displays the month name, date and year


84

import java.util.*;

class Convert

int n,d,m,y;

Convert( )

n=0;

y=0;

void accept()

Scanner x=new Scanner(System.in) ;

System.out.println(("Enter day number and year") ;

n=x.nextInt() ;

y=x.nextInt() ;

void day_to_date()

int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
85

if(y%4==0)

a[2]=29;

int s=0, c=0;

while(s<n)

s=s+a[c++];

s=s-a[--c];

d=n-s;

m=c;

void display()

String x[]={"","JANUARY","FEBRUARY","MARCH","APRIL","MAY",
"JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"};

System.out.print("\n Day Number: " + n);

System.out.print("\n Date: " );

System.out.print(x[m]+" " +d + "," + y);

static void main()

Convert obj =new Convert();

obj.accept( ) ;

obj.day_to_date();

obj.display();

}
86

Variable Description Table

Variable Description Type Scope

n Stores the day number to be converted to a date int


Instance variable of the Convert class

d Stores the day of the month after conversion int


Instance variable of the Convert class

m Stores the month after conversion int Instance


variable of the Convert class

y Stores the year after conversion int Instance


variable of the Convert class

a Array that holds the number of days in each month int[]


Local variable in the day_to_date method

s Accumulates the total number of days to find the month and


day int Local variable in the day_to_date method

c Index for iterating through the days of each month array


int Local variable in the day_to_date method

x Array of month names String[] Local variable in the


display method
87

(5) A class Mix has been defined to mix two words, character by character, in the following
manner:

The first character of the first word is followed by the first character of the second word and so
on. If the words are of different length, the remaining characters of the longer word are put at the
end.

Example: If the First word is “JUMP” and the second word is “STROLL”, then the required
word will be “JSUTMRPOLL”

Some of the members of the class are given below:

Classname Mix

Data member/instance variable:

wrd to store a word

len to store the length of the word

Member functions/methods:

Mix( ) default constructor to initialize the data members with legal


initial values

void feedword( ) to accept the word in UPPER case

void mix_word( Mix P, Mix Q ) mixes the words of objects P and Q as stated above and
stores the resultant word in the current object

void display( ) displays the word


88

import java.util.*;

class Mix

String wrd;

int len;

static Scanner x=new Scanner(System.in);

Mix()

wrd="";

len=0;

void feedword()

System.out.println( "Enter a word in UPPER CASE");

wrd=x.next();

len=wrd.length();

void mix_word(Mix P,Mix Q)

int s=(P.len <Q.len)? P.len:Q.len;

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

wrd += P.wrd.charAt(i)+""+Q.wrd.charAt(i);

if (P.len > Q.len)

wrd +=P.wrd.substring(Q.len);
89

else

wrd +=Q.wrd.substring(P.len);

void display()

System.out.println("WORD = " + wrd);

static void main()

Mix obj=new Mix();

Mix obj1=new Mix();

Mix obj2= new Mix();

obj.feedword();

obj1.feedword();

obj2.mix_word (obj,obj1);

obj2.display();

Variable Description Table

Variable Description Type Scope

wrd Stores the word that is constructed or mixed String Instance


variable of the Mix class

len Stores the length of the word wrd int Instance variable of
the Mix class
90

x Scanner object for reading input from the console Scanner


Static variable of the Mix class

s Stores the length of the shorter word between two Mix objects
int Local variable in the mix_word method

i Loop counter for iterating through characters of the words int


Local variable in the mix_word method

You might also like