Constructor Programs
- Categories Java, Constructors, OOPS
1 . A class Collection contains an array of 100 integers. Using the following class description create an array with common elements from two integer arrays. Some of the members of the class are given below:
Class name Disarium Data members / instance variables: int num : stores the number int size : stores the size of the number Member functions : Disarium(int nn) : parameterized constructor to initialize the data members n =nn size = 0 void countDigit() : counts the total number of digits and assigns it to size int sumofDigits(int n, int p) : returns the sum of the digits of the number(n) to the power of their respectively points(p) using recursive technique void check( ) : checks whether the number is a disarium number and displays the result with an appropriate message.
Specify the class Collection giving the details of the constructors, void inparr( ) and void arrange(), Collection common (Collection). You need not write the main function.
Ans. In the following solution, we have written additional private function setLength0 for setting length of collection object so that length of Collection object containing common elements may be set.
import java.io.* ;
public class Collection {
int arr[];
int size ;
public Collection( ) { // default constructer
arr = new int[1001] ;
size = 100 ;
}
public Collection(int size) { // parameterised constructer to assign the length of the array
arr = new int[size] ;
size = size ;
}
public void inarr() { // accept the array elements
DataInputStream in = new DataInputStream(System.in); int val = 0 ;
for(int i = 0 ; i < size ; ++i) { // accept the array elements
System.out.println("Enter element "+ (1+1) ) ;
try {
val = Integer.parseInt(in.readLine()) ; //if input is not an integer value show exception
}
catch(Exception e) {
System.out.println("Error in reading/ Invalid integer.") ;
}
arr[i]= val;
}
}
private void setLength(int le){
size=le ;
}
public Collection common( Collection c2){
Collection c3 = new Collection() ;
int val; int k = 0;
for (int i= 0 ; i < size ; ++i){
val = arr[i];
for( int j = 0; j < c2.arr.length; ++j) {
if ( val == c2.arr[j]) {
c3.arr[k] = val ;
k++ ;
}
}
}
c3. setLength(k) ; return c3 ;
}
public void display( ) {
for(int i = 0 ; i < size ; i++){
System.out.print(arr[i] +"");
}
System.out.println( ) ;
}
public void arrange( ){ // sorting elements in ascending order
for(int i = size - 1 ; i >= 0 ; i--) { // start at the end of the array
int HIndex = i ; // (1) default value of the highest element index.
for(int j = i ; j >= 0 ; j--){ // (2) loop from the end of unsorted
// zone to the beginning of the array.
if(arr[j] > arr[HIndex]) // compare current element to highest
HIndex = j ; // if it's higher, it becomes the new highest
}
// swap the two values
int temp = arr[i] ;
arr[i] = arr[HIndex] ;
arr[HIndex] = temp ;
}
}
}
2 . A class SeriesSum is designed to calculate the sum of the following series :
Some of the members of the class are given below :
Class name SeriesSum Data members / instance variables: X : to store an integer number N : to store number of terms Sum : double variable to store the sum of the series Member functions : SeriesSum(int xx, int nn) :constructor to assign x = xx and n = nn double CalFact (int m) : to return the factorial of musing recursive technique. double CalPower (int x, int y) : to return x raised to the power of y using recursive technique. void CalSum( ) : to calculate the sum of the series by invoking the recursive functions respectively void display( ) : to display the sum of the series
(a) Specify the class SeriesSum, giving details of the constructor(int, int), double findfact (int), double findpower(int, int), void calculate() and void display (). Define the main() function to create an object and call functions accordingly to enable the task.
(b) State the two differences between iteration and recursion.
Ans.
a.
public class SeriesSum { int x, n; double sum; public SeriesSum(int xx, int nn){ // constructor x = xx; n = nn; sum = 0; } double CalFact(int x){ // calculate factorial of i if (x <=1 ) return 13; else return (x* CalFact (x-1)) ; } double CalPower(int a, int b) { // calculate power of x if (b == 0 ) return 1; else return (a * CalPower(a, b-1)); } void CalSum() { double term = 0; for ( int i = 2; i <=n; i += 2) { term = CalPower(x, i) / CalFact(i-1); sum += term; } } void display() { System.out.println("Sum of the series : "+ sum); } public static void main() { SeriesSum ser1 = new SeriesSum(2, 6) ; ser1. CalSum(); ser1.display(); }
}
(b) Iteration. (i) executes faster and (ii) takes less memory.
Recursion. (i) execution time is more because of multiple function calls and (ii) take more memory.
3 . A super class Product has been defined to store the details of a product sold by a wholesaler to a retailer. Define a sub class Sales to compute the total amount paid by the retailer with or without fine along with service tax.
Some of the members of both the classes are given below:Class name Product Data members / instance variables: name : stores the name of the product code : integer to store the product code amount : stores the total sale amount of the product (in decimals) Member functions : product (String n, int c, double p) : parameterized constructor to assign values to data embers name=n,
code=c and amount = p displays the details of the data members.void show() : displays the details of the data members Class name Sales Data members / instance variables: day : stores number of days taken to pay the sale amount tax : to store the service tax (in decimals) totamt : to store the total amount (in decimals) Member functions : Sales(…) : parameterized constructor to assign values to data void compute( ) : calculates the service tax (@ 12.4% of the actual sale amount calculates the fine @ 2.5% of the actual sale amount only if the amount paid by the retailer to the wholesaler exceeds 30 days calculates the total amount paid by the retailer as (actual sale amount + service tax + fine) void show() : displays the data members of super class and the total amount
assume that the super class Product has been defined. Using the concept of inheritance. Specify the class Sales giving the details of the constructor(..), void compute ) and void show().
The super class, main function and algorithm need NOT be written.
Ans.
public class Sales extends Product { int day; double tax, totamt; Sales( String n, int a, double b, int d) { super(n,a,b); day=d; } void compute() { double f=0.0; tax= (12.4 /100) * amount; if(day>27) f=(2.5/100)* amount; totamt = amount + tax + f; } void show() { Super.show(); System.out.printn("No of days-" + day); System.out.println("Sales Tax-" +tax); System.out.println("Total Amount-" + totamt ); } }
4 . A super class Stock has been defined to store the details of the stock of a retail store. Define subclass Purchase to store the details of the items purchased with the new rate and updates the stock. Some of members of the classes are given bellow:Class name Stock Data members / instance variables: item : to store the name of the item qty : to store the quantity of an item in stock rate : to store the unit price of an item amt : to store the net value of the item in stock Member functions : Stock(..) : parameterized constructor to assign values to the data members void display() : displays the stock details Class name Purchase Data members / instance variables: pqty : to store the purchased quantity prate : to store the unit price of the purchased item Member functions : Purchase (..) : Parameterized constructor to assign values to the data members to both classes. void update( ) : To update stock by adding the previous quantity by the purchased quantity and
replace the rate of the item if there is a difference in the purchase rate. Also update the current stock value as : (quantity * unit price)void display() : to display the stock details before and after updation
Specify the class Stock going details of the constructor(..) and void display( ). Using concept of inheritance, specify the class Purchase, going details of the constructor(..), void update( ) and void display( ).
The main function and algorithm need not be written.
Ans.
public class Stock { String item ; double qty, rate, amt ; public Stock(String a, double b, double c) { item =a; qty= b; rate =c; amt = qty*rate ; } void display() { System.out.println("Item Name :"+ item) ; System.out.println("Quantity : "+qty) ; System.out.println("Rate (per unit) : "+ rate) ; System.out.println("Net Value : "+ amt) ; } } class Purchase extends Stock { int pqty ; double prate ; public Purchase( String a, double b, double c, int al, double b1) { super(a,b,c); pqty = a1; prate = b1; } void update() { qty += pqty; if (prate != rate) rate = prate ; amt = qty * rate; } void display() { super.display(); update(); super.display() ; } }
5 . A emirp number is a number which is prime backwards and forwards. Example : 13 and 31 are both prime numbers. Thus, 13 is an emirp number. Design a class Emirp to check if a given number is Emirp number or not. Some of the members of the class are given below :Class name Emirp Data members / instance variables: num : stores the -number rev : stores the reverse of the number div : stores the divisor Member functions : Emirp ( int n) : to assign num=n, rev=0 and div=2 Int isprime(int x ) : check if the number is prime using the recursive technique and return 1 if prime otherwise return 0. Void isEmirp() : reverse the given number and check if both the original number and the reverse number are prime, by invoking the function isprime(int) and display the result with an appropriate message
Specify the class Emirp giving details of the constructor(int), and void is Emirp(). Define the main() function to create an object and call the methods to check for Emirp number.
Ans.
import java.util.Scanner ;
public class Emirp{
int num, rev, div ;
public Emirp(int n) { //constructor
num= n ;
rev = 0 ;
div= 2 ;
}
int isprime(int x) { //check if the number is prime using the recursive technique
if ( x > Math.sqrt(num) )
return 1 ;
else if (num == 2 || num==3)
return 1;
else if (num== 1 || num %x == 0)
return 0 ;
else
return isprime(x+1) ;
}
void isEmirp() { //reverse the given number and check if both the original
//number and the reverse number are prime
int n = num, d;
while ( n>0) {
d = n%10 ;
n = n /10 ;
rev = rev * 10+ d ;
}
int chk1, chk2 ;
int origNo = num ; //save n for future recall
chk1 = isprime(div) ; //check if n is prime
//reinitialize divisor and number to be tested
div = 2 ;
num = rev ; // set n to rev for testing purpose
chk2= isprime(div) ; // check if rev is prime ( n set to rev now)
num =origNo; // restore original n
System.out.println("Original number : " + num) ;
System. out.println("Reversed number :" + rev) ;
if (chk1 == 1 && chk2 ==1)
System.out.println(num + " is an Emirp number.") ;
else
System.out.println(num + " is NOT an Emirp number.");
}
public static void main(String[ ]args) {
Scanner kb = new Scanner(System.in) ;
System.out.println("Enter a number") ;
int a = kb.nextInt() ;
Emirp num = new Emirp(a) ;
num.isEmirp() ;
}
}
6 . Write a program that finds the greatest common divisor of two positive integers using the following guidelines:
gcd(p, q) =
- p if q =
- q if p = e
- 2 * gcd(p/2, q/2) if p and q are even
- gcd(p/2, q) if p is even and q is odd
gcd(p, q/2) if p is odd and q is even - gcd((p – q)/2, q) if p and q are odd and p >= q
- gcd(p, (q – p)/2) if p and q are odd and p < q
The class structure is as follows :Name BinaryGCD Data members : n1,n2, gcd (all int) Method int binGcd(int p, int q): : computes the ged as per above logic int getGcd( ) : returns the value of data member gcd constructor : takes two int parameters and initialises the two numbers and then it computes the gcd of these two numbers and stores in variable gcd.
The main( ) method should obtain two numbers from user and then invoke methods appropriately.
import java.util.Scanner ;
class BinaryGCD {
int n1, n2, gcd;
BinaryGCD (int a, int b) {
n1 = a;
n2 = b;
gcd = binGcd(n1, n2) ;
}
public static int binGcd(int p, int q) {
if (q == 0)
return p ;
if (p == 0)
return q ;
if ((p & 1) ==0 && (q & 1) == 0) // p is even, q
return binGcd (p >> 1, q >> 1) << 1 ;
else if ((p & 1) == 0) // p is even, q is odd
return binGcd(p >> 1, q) ;
else if ((q & 1) == 0) // p is odd, q is even
return binGcd(p, q >> 1) ;
else if (p >= q) // p and q odd, p >= q
return binGcd((p - q) >> 1, q) ;
else // p and q odd, p < q
return binGcd(p, (q - p) >> 1) ;
}
int getGcd() {
return gcd ;
}
public static void main(String[] args) {
Scanner in = new Scanner( System.in ) ;
System.out. print("Enter 2 numbers : ");
int p = in.nextInt() ;
int q = in.nextInt();
BinaryGCD bcd= new BinaryGCD(p,q);
System.out.println("gcd(" + p + "," +q + ") = " + bcd.getGcd());
}
}
7 . A super class Worker has been defined to store the details of a worker. Define a subclass Wages to compute the monthly wages for the worker. The details specifications of both the classes are given below :Class name Worker Data members / instance variables: Name : to store the name of the worker Basic : to store the basic pay in decimals Member functions : Worker() : Parameterised constructor to assign values to the instance variables void display() : displays the workers details Class name Series Data members / instance variables: hrs : stores the hours worked rate : stores rate per hour wage : stores the overall wage of the worker Member functions : Wages(..) : Parameterised constructor to assign values to the instance variables of both the classes double overtime( ) : Calculates and returns the overtime amount as (hours*rate) void display() : Calculates the wage using the formula wage= overtime amount t Basic pay and displays it along with the other details
Specify the class Worker going details of the constructor( ) and void display( ). Using the concept of inheritance, specify the class Wages giving details of constructor( ), double overtime( ) and void display(). The main( ) function need not be written.
Ans.
class worker
{
String Name ;
double Basic;
Worker (String nm, double bas)
{
Name = nm;
Basic = bas ;
}
void display()
{
System.out. printIn("NAME :" + Name) ;
System.out. println("BASIC :" + Basic) ;
}
}
public class Wages extends worker
{
int hrs ;
double rate ;
double wage ;
Wages (String nm, double bas, int h, double rt)
{
super(nm, bas) ;
hrs = h;
rate =rt;
}
double overtime ()
{
return hrs * rate;
}
void display()
{
super. display() ;
wage = overtime()+ basic;
System.out.println("Hours worked :"+hrs);
System.out.printin("Rate :"+ rate) ;
System.out.printin("Wage : "+ wage);
}
}
8 . Write a program that takes a positive integer N (in decimal) from the user and prints out its binary representation . Repeatedly divide 2 into N and read the remainders backwards. First, write a while loop to carry out this computation and print the bits in the wrong order. Then, use recursion to print the bits in the correct order.
Implement 1 the functionality through following classclass name : Binary Converter Data members / Instance Variables Num : int type bNum : long type Methods convert( ) : takes an int parameter and converts it to equivalent binary number. Returns the binary number as long show( ) : displays the values of both number and binNumber Constructor method : receives an int parameter and stores it into number. It then also initialises binNumber
The program should also contain main( ) method that takes number from user and invokes the appropriate methods.
Ans.
import java. util.Scanner ;
class BinaryConverter {
int num ;
long bNum ;
BinaryConverter(int n) { // Constructor
num = n ;
bNum = convert(n) ;
}
long convert(int n) { // converts parameter to equivalent binary number
if (n == 0) return 0 ;
return convert(n / 2) * 10 + (n % 2) ;
}
void show() { // show output
System.out.println("num " + num) ;
System.out.println("Binary Equivalent : "+bNum) ;
}
public static void main(String[] args){
Scanner console = new Scanner(System.in) ;
System.out.print("Enter num to be converted into binary equivalent : ") ;
int N= console.nextInt() ;
BinaryConverter binum =new BinaryConverter(N) ;
binum.show() ;
}
}
9 . A super class Number is defined to calculate the factorial of a number. Define a sub class Series to find the sum of the series S = 1! + 2! + 3! + 4!+…+n!
The details of the members of both the classes are given below:Class name Number Data members / instance variables: n : to store an integer number Member functions : Number(int num) : parameterized constructor to initialize the data member n=num int factorial (int a) : returns the factorial of a number
(factorial of n = 1×2×3×………×n)void display() : displays the data members Class name Series Data members / instance variables: sum : to store sum of the series Member functions : Series(…) : parameterized constructor to initialize the data members of both the classes void calsum( ) : calculates the sum of the given series void display() : displays the data members of both the classes
Assume that the super class Number has been defined. Using the concept of inheritance, specify the class Series giving the details of the constructor(…),void calsum( ) and void display( ).
The super class, main function and algorithm need NOT be written.
Ans.
class Series extends Number
{
long sum;
Series(int num)
{
super(num);
sum=0;
}
void calsum()
{
for (int i=1;i<=n;i++)
sum=sum+factorial(i);
f=f*i ;
sum=sum + f ;
}
void display()
{
super.display();
System.out.println("sum of the series="+sum);
}
}