Get ICSE Constructors Solutions for class 10. It will help you to make good preparation before attending the ICSE Board exam. We have provided you with Constructors Solutions class 10 to score good marks in your exam.
In ICSE CLass 10, Constructors Solutions is compulsory to score good marks in computer applications. Students Who are planning to score higher marks in class 10 should practice ICSE Constructors Solutions class 10.
ICSE Constructors Solutions for Class 10 Computer Applications
A. Tick (✓) the correct option.
1. Which of the following is not applicable for a constructor function?
a. It has the same name as the class.
b. It has no return-type
c. It is usually used for initialisation.
d. It can be invoked using an object like any other member function.
Answer
D
2. If the name of a class is ‘Number’, what can be the possible name for its constructor?
a. Number
b. number
c. No
d. no
Answer
A
3. Which among the following is a type of constructor?
a. Parameterised constructor
b. Non-parameterised constructor
c. Both a and b
d. None of these
Answer
C
4. If constructors are overloaded, what differentiates it?
a. Parameter list
b. Return type
c. Both a and b
d. None of these
5. What access specifier for a constructor allows you to create an object only within the class?
a. public
b. private
c. protected
d. default
Answer
B
6. Name the type of constructor that gets invoked when an object is created, which is initialised with the content of another object.
a. Copy constructor
b. Default constructor
c. Overloaded constructor
d. None of these
Answer
A
7. Categorise the type of object that can be created without any name or identifier.
a. Temporary object
b. Anonymous object
c. Both a and b
d. None of these
Answer
C
8. Predict the output of the following program:
class T
{
int t = 20;
T()
{
t = 40;
}
public static void main(String args[])
{
T t1 = new T();
System.out.println(t1.t);
}
}
a. 20 b. 40
c. Compiler Error d. None of these
Answer
B
9. The following code contains one compilation error, find it?
public class Test {
Test() { } // line 1
static void Test() { this(); } // line 2
public static void main(String[] args) { // line 3
Test(); // line 4
}
}
a. At line 1, constructor Tester must be marked public like its class
b. At line 2, constructor call
c. At line 3, compilation error, ambiguity problem, compiler can’t determine whether a constructor
d. At line 4
Answer
B
10. Which of the following is not true for static block?
a. It is used to initialise static variables.
b. It gets executed when a class gets loaded in the memory.
c. It can print the content of instance variables.
d. It begins with the static keyword.
Answer
C
SECTION A
1. What is a constructor? Why is it needed in a program?
Ans. A constructor in Java is a block of code similar to a method that is called when an instance of an object is created. A constructor is needed to initialise data members with legal initial values.
2. State the characteristics of a constructor.
Ans. The characteristics of a constructor are:
a. It has the same name as the class-name.
b. It does not have any return type.
c. It follows the usual rules of accessibility as other members of a class and therefore access modifiers can be applied to it.
d. It gets called automatically, whenever an object is created.
3. How are constructors invoked?
Ans. Constructor function gets called (invoked) automatically whenever an object is created.
4. Why do we need a constructor as a class member?
Ans. A constructor is a special member method which will be called by the JVM implicitly for placing user/programmer defined values instead of placing default values. Constructors are meant for initializing the object.
5. State the difference between function and constructor.
Ans. Following are the difference between constructor and method.
a. Constructor is used to initialize an object whereas method is used to exhibits functionality of an object.
b. Constructors are invoked implicitly whereas methods are invoked explicitly.
c. Constructor does not return any value where the method may/may not return a value.
d. In case constructor is not present, a default constructor is provided by java compiler. In the case of a method, no default method is provided.
e. Constructor should be of the same name as that of class. Method name should not be of the same name as that of class.
6. How are private constructors called?
Ans. Private constructors allows an object to be created only within the methods of the class where it is private.
7. What are the different types of constructors available in Java?
Ans. Parameterised constructor and Non-parameterised constructor.
8. What is a default constructor?
Ans. When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn’t accept any arguments. The default constructor’s job is to call the super class constructor and initialize all instance variables.
9. Point out the difference between implicit and explicit default constructors.
Ans. Implicit default constructor is the default constructor created by java if the user do not create a constructor. Explicit default constructor is a non-parameterised constructor defined by the user to initialise data members with legal initial values.
10. What are temporary objects? How are they created, explain with the help of an example?
Ans. Temporary or anonymous objects or instances are the ones that live in the memory as long as it is being used or referenced in an expression and after that it dies. Temporary objects are created by explicit call to a constructor, preceded with the new command. For example,
public class temp
{
int a,b;
temp(int x, int y)
{
a=x;
b=y;
}
void show()
{
System.out.println(a+“,”+b);
}
static void test( )
{
new temp(1,2).show( );
}
}
Here the statement new temp(1,2) of the statement new temp(1,2).show(); creates an anonymous temporary object and lives in the memory as long as show() of the statement new temp(1,2).show(); is being executed. Upon completion of the execution of the show() function, the temporary object gets wiped out of the memory.
11. What is constructor overloading? Illustrate it with the help of an example.
Ans. Just like method overloading, constructors also can be overloaded. Same constructor declared with different parameters in the same class is known as constructor overloading. Compiler differentiates which constructor is to be called depending upon the number of parameters and their sequence of data types.
Java
public class Perimeter
{
public Perimeter() // I
{
System.out.println(“From default”);
}
public Perimeter(int x) // II
{
System.out.println(“Circle perimeter: “ + 2*Math.PI*x);
}
public Perimeter(int x, int y) // III
{
System.out.println(“Rectangle perimeter: “ +2*(x+y));
}
public static void main(String args[])
{
Perimeter p1 = new Perimeter(); // I
Perimeter p2 = new Perimeter(10); // II
Perimeter p3 = new Perimeter(10, 20); // III
}
}
12. What is a destructor? Is destructor function necessary in Java? If no, explain why?
Ans. A destructor is a special method called automatically during the destruction of an object. In java a destructor is not necessary because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.
13. What is the implicit return type of a constructor function?
Ans. The implicit return type is the class itself.
14. Enter any two variables through constructor with parameters and write a program to swap and print the values.
Ans.
class Swap
{
int a,b;
Swap(int x,int y)
{
a=x;
b=y;
}
void interchange()
{
int t=a;
a=b;
b=t;
}
}
15. What is the default initial value of a boolean variable data type?
Ans. the default initial value is ‘false’.
B. Consider the following code and answer the questions that follow:
class Myclass
{
int a,b;
void Myclass(int x, int y)
{
a=x;
b=y;
}
int Myclass(int x)
{
a=b=x;
}
void show( )
{
System.out.println(a+ “ “+y);
}
public static void main(String args[])
{
Myclass ob1=new Myclass();
Myclass ob2=new Myclass(12.3,14.6,15);
Myclass ob3=new Myclass(7);
ob1.ob2.ob3.show();
}
}
Ans. The program has errors and here is the solution:
class Myclass
{
int a,b;
void Myclass(int x, int y)
{
a=x;
b=y;
}
int Myclass(int x)
{
a=b=x;
}
void show( )
{
System.out.println(a+ “ ”+b);
}
public static void main(String args[])
{
Myclass ob2=new Myclass(12,15);
Myclass ob3=new Myclass(7);
ob2.show();
ob3.show();
}
}
C. Consider the following code and answer the questions that follow:
class academic
{
int x,y;
void access()
{
int a,b;
academic student=new academic();
System.out.println(Object Created”);
}
}
a. What is the object name of the class?
b. Name the instance variables used in the class.
c. Write the name of local variables used in the program.
d. Give the type of function being used and its name.
Ans.
a. student
b. x and y
c. a and b
d. procedural function Name: access
D. State the output of the following program segment:
class Today
{
static int a;
char b;
void input()
{
a=20;
b=’Z’;
}
void convert()
{
char c=(char)(a+b);
System.out.println(c);
}
public static void main()
{
Today t=new Today();
t.input();
t.convert();
}
}
Based on the above given piece of code, answer that questions the follow:
i. Name the instance, class and local variables.
ii. What is the name of the constructor of the above class?
iii. Explain the line: Today t=new Today();
Ans.
Output:
n
i. Instance variable: b
Class variable: a
Local variable: c
ii. Today()
iii. An object named t is being created of ‘Today’ type.
E. In the program given below, state the name and value of the
i. method argument or argument variable
ii. class variable
iii. local variable
iv. instance variable
class Myclass
{
static int x=7;
int y=2;
public static void main(String args[])
{
Myclass obj=new Myclass();
System.out.println(x);
obj.sampleMethod(5);
int a=6;
System.out.pritnln(a);
}
void sampleMethod(int n)
{
System.out.println(n);
System.out.println(y);
}
}
Ans.
i. main() method: String args[]
sampleMethod() method: int n
ii. x
iii. a
iv. y
SECTION B
Write programs for the following:
1. Define a class called Box, having members as:
Data Members: length, breadth and height of int type.
Member Functions:
i. Constructor to initialise the data members.
ii. To compute and display the volume.
Ans.
class Box
{
int length,breadth,height;
Box(int l,int b,int h)
{
length=l;
breadth=b;
height=h;
}
void compute()
{
int vol;
vol=length*breadth*height;
System.out.println(“Volume:”+vol);
}
}
2. Define a class called Friend, having members as:
Data Members: Name, Address, Favourite hobby
Member Functions
i. Constructor to initialise the data members.
ii. To display the details.
Also create the main() and create 2 objects in it and initialise it with information of two of your friends and display it, by calling the above functions.
Ans.
class Friend
{
String Name,Address,hobby;
Friend(String n,String a,String h)
{
Name=n;
Address=a;
hobby=h;
}
void display()
{
System.out.println(“Name:”+Name);
System.out.println(“Address:”+Address);
System.out.println(“Favourite hobby:”+hobby);
}
public static void main(String args[])
{
Friend ob1=new Friend(“Soumen”,“Delhi”,“Philately”);
Friend ob2=new Friend(“Sujit”,“Patna”,“Guitar”);
ob1.display();
ob2.display();
}
}
3. Define a class named four Side, having members as:
Data members: length, breadth
Member Functions:
i. Overloaded constructor to initialise the dimension of the four-sided figure with a square and a rectangle.
ii. Compute the area and display it.
Also create the main() method to show the implementation of the above methods.
Ans.
class FourSide
{
int length,breadth;
FourSide(int s)
{
length=breadth=s;
}
FourSide(int l,int b)
{
length=l;
breadth=b;
}
void compute()
{
int area;
area=length*breadth;
System.out.println(“Area:”+area);
}
public static void main(String args[])
{
FourSide ob1=new FourSide(12);
FourSide ob2=new FourSide(17,6);
ob1.compute();
ob2.compute();
}
}
4. The sum of n natural numbers is defined by the following formula:
n * (n + 1) / 1
Create a class named Natural, which will contain the following members:
Data members: n and s of int data type.
Member functions:
i. Parametrised constructor to initialise n.
ii. void compute( ) to calculate the sum of first n natural numbers using the above formula and store it in s.
iii. void display( ) to show the sum.
Ans.
class Natural
{
int n,s;
Natural(int t)
{
n=t;
}
void compute()
{
int i;
s=0;
for(i=1;i<=n;i++)
s+=i;
}
void display()
{
System.out.println(“Sum:”+s);
}
}
5. Define a class named Conversion having the following static methods:
i. int mTocm(int m ), which converts metre(m) to centimeter and return it.
ii. int multiply(int x, int y ), which returns the product of x and y.
Define another class named Rectangle which contains the following data members:
• length of int type which holds the length of a rectangle in metre.
• breadth of int type which holds the breadth of a rectangle in centimeter.
Create member functions:
i. Constructor to initialise the data members.
ii. Convert the length to centimetre by calling the relevant method of the above class.
iii. Compute the area by calling the relevant method of the above class and display the result.
Ans.
class Conversion
{
int n,s;
int mTocm(int m)
{
return m*100;
}
int multiply(int x,int y)
{
return x*y;
}
}
public class Rectangle
{
int length,breadth;
Rectangle(int m,int cm)
{
length=m;
breadth=cm;
}
void convert()
{
length=new Conversion().mTocm(length);
}
void compute()
{
int area;
convert();
area=new Conversion().multiply(length,breadth);
System.out.println(“Area:”+area);
}
}
6. 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:
Classname :
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’.
• void check( ) : checks whether the number is a Palindrome by invoking the function reverse( ) and display the result with an appropriate message.
Specify the class Palin giving the details of the constructor( ), void accept( ),int reverse(int) and void check( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Ans.
import java.util.*;
class Palin
{
int num,revnum;
Palin()
{
num=0;
revnum=0;
}
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a number:”);
num=sc.nextInt();
}
int reverse(int y)
{
for(int i=num;i>0;i/=10)
{
int d=i%10;
revnum=revnum*10+d;
}
return revnum;
}
void check()
{
if(num==reverse(num))
System.out.println(“Palindrome”);
else
System.out.println(“Not palindrome”);
}
public static void main(String args[])
{
Palin ob=new Palin();
ob.accept();
ob.check();
}
}
7. Design a class named Numbers, which will contain the following members:
Data Members: a, b and c of int data type.
Member Functions:
i. Parameterised constructor to initialise a and b.
ii. void show( ) to display the contents of a, b and c.
iii. void compute( ) to add a and b and store it in c.
In the main( ) create an object and initialise a and b with any value and add a and b by invoking the compute( ) function and display the contents of a, b and c using show( ) function.
Ans.
class Numbers
{
int a,b,c;
Numbers(int x,int y)
{
a=x;
b=y;
}
void show()
{
System.out.println(a+” “+b+” “+c);
}
void compute()
{
c=a+b;
}
public static void main(String args[])
{
Numbers ob=new Numbers(12,15);
ob.compute();
ob.show();
}
}
8. Create a class named Number with the following members:
Data members: a of int data type.
Member Functions:
• Parameterised constructor to initialise the data member.
• Default constructor to initialise the data member with 0.
• To display a only.
• Which accepts an instance of Number class as parameter and creates another object, whose a will contain the sum the a’s of the current and the passed object. This function should return the object newly instantiated.
Also create a main( ) with at least 3 objects to show its working.
Ans.
class Number
{
int a;
Number(int x)
{
a=x;
}
Number()
{
a=0;
}
void show()
{
System.out.println(a);
}
Number sum(Number t)
{
Number x=new Number();
x.a=a+t.a;
return x;
}
public static void main(String args[])
{
Number ob1=new Number(12);
Number ob2=new Number(15);
Number ob3;
ob3=ob1.sum(ob2);
ob3.show();
}
}
9. You are to print the telephone bill of a subscriber. Create a class having the following data members:
Phone Number of long data type (for storing the phone number).
Name of String type (for storing the name of a the subscriber).
Hire Charge a symbolic constant of int type (to store monthly hire charge say `. 200).
Units Consumed of int type (to store the monthly units consumed by the subscriber).
Bill Amount of float type (to store the bill amount that is payable).
Create member functions for the following:
i. Constructor to initialise all data members except Hire Charge and Bill Amount.
ii. Calculate the bill amount payable which is Hire Charge+(₹. 1 per unit for the first 100 units, ₹. 1.50 per unit for the next 100 units and ₹. 2.00 per unit there after.
iii. To display the Bill for the subscriber.
Ans.
import java.util.*;
class Telephone
{
long pno;
String name;
int hire;
int units;
float bill;
Telephone(long p,String n,int u)
{
pno=p;
name=n;
units=u;
}
void calculate()
{
hire=200;
bill=0;
if(units<=100)
bill=hire+units*1;
else if(units>100 && units<=200)
bill=hire+100*1+(units-100)*1.50f;
else
bill=hire+100*1+100*1.50f+(units-200)*2;
}
void show()
{
System.out.println(“BILL”);
System.out.println(“Phone No.:”+pno);
System.out.println(“Name:”+name);
System.out.println(“Hire Charge:”+hire);
System.out.println(“Units consumed:”+units);
System.out.println(“Bill:”+bill);
}
}
10. Define a class Taximeter having the following description:
Data members/instance variables:
int taxino – to store taxi number
String name – to store passenger’s name
int km – to store number of kilometers travelled
Member functions:
Taximeter() – constructor to initialise taxino to 0, name to “” and km to 0.
input() – to store taxino,name,km
calculate() – to calculate bill for a customer according to given conditions
Kilometers travelled(km) Rate/km
1 km ₹ 25
1 < km ≤ 6 ₹ 10
6 < km ≤ 12 ₹ 15
12 < km ≤ 18 ₹ 20
>18 km ₹ 25
display()- To display the details in the following format
Taxino Name Kilometres travelled Bill amount
Ans.
import java.util.*;
class Taximeter
{
int taxino;
String name;
int km;
Taximeter()
{
taxino=0;
name=“ ”;
km=0;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the taxi no.:”);
taxino=sc.nextInt();
System.out.println(“Enter the name:”);
name=sc.nextLine();
System.out.println(“Enter the kilometer:”);
km=sc.nextInt();
}
int calculate()
{
int bill=0;
if(km==1)
bill=25*km;
else if(km>1 && km<=6)
bill=10*km;
else if(km>6 && km<=12)
bill=15*km;
else if(km>12 && km<=18)
bill=20*km;
else
bill=25*km;
return bill;
}
void display()
{
System.out.println(“Taxino\t\tName\t\tKilomtres travelled\t\tBill amount”);
System.out.println(taxino+“\t\t”+name+“\t\t”+km+“\t\t”+calculate());
}
}
11. Create a class which will contain the following components:
Data Members: a and b of int type.
Member Functions:
i. Constructor to initialise a and b.
ii. Return the sum of a and b.
iii. To display the value of a and b.
Also create a static function which accepts two objects as parameters and print a and b of the object whose sum is the maximum.
In the main() create two objects, initialise them and display the data members of that object whose sum of the data-members is the maximum.
Ans.
import java.util.*;
class Numbers
{
int a,b;
Numbers(int x,int y)
{
a=x;
b=y;
}
int sum()
{
return a+b;
}
void display()
{
System.out.println(“a=”+a+“b=”+b);
}
static void compare(Numbers ob1,Numbers ob2)
{
if(ob1.sum()>ob2.sum())
ob1.display();
else
ob2.display();
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x,y;
System.out.println(“Enter 2 numbers:”);
x=sc.nextInt();
y=sc.nextInt();
Numbers ob1=new Numbers(x,y);
System.out.println(“Enter 2 numbers:”);
x=sc.nextInt();
y=sc.nextInt();
Numbers ob2=new Numbers(x,y);
compare(ob1,ob2);
}
}
12. Define a class called FruitJuice with the following description:
Instance variables/data members:
int product_code – stores the product code number
String flavour – stores the flavour of the juice.(orange, apple, etc.)
String pack_type – stores the type of packaging (tetra-pack, bottle, etc.)
int pack_size – stores package size (200ml, 400ml, etc.)
int product_price – stores the price of the product
Member Methods:
FriuitJuice() – default constructor to initialise integer data members to zero and string data members to “”.
void input() – to input and store the product code, flavour, pack type, pack size and product price.
void discount() – to reduce the product price by 10.
void display() – to display the product code, flavour, pack type, pack size and product price.
Create an object in the main method and call all the above methods in it.
Ans.
import java.util.*;
class FruitJuice
{
int product_code,pack_size,product_price;
String flavour,pack_type;
FruitJuice()
{
product_code=pack_size=product_price=0;
flavour=pack_type=””;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the product code:”);
product_code=sc.nextInt();
System.out.println(“Enter the flavour:”);
flavour=sc.nextLine();
System.out.println(“Enter the pack type:”);
pack_type=sc.nextLine();
System.out.println(“Enter the pack size:”);
pack_size=sc.nextInt();
System.out.println(“Enter the product price:”);
product_price=sc.nextInt();
}
void discount()
{
product_price-=10;
}
void display()
{
System.out.println(“Product code:”+product_code);
System.out.println(“Flavour:”+flavour);
System.out.println(“Pack type:”+pack_type);
System.out.println(“Pack size:”+pack_size);
System.out.println(“Product price:”+product_price);
}
public static void main(String args[])
{
FruitJuice ob=new FruitJuice();
ob.input();
ob.discount();
ob.display();
}
}
13. Create a class SalaryCalculation that is described as below:
Class Name : SalaryCalculation
Data members : name (String type data)
basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary AnnualSal (All double type data)
Member methods :
i. SalaryCalculation( ) – A constructor to assign name of employee (name), basic
salary (basicPay) of your choice and conveyance allowance
(conveyanceAlw) As ₹ 1000.00
ii. void SalaryCal( ) – to calculate other allowances and salaries as given:
specialAlw = 25% of basic salary.
gross = basicPay + specialAlw + conveyanceAlw.
netSalary = gross – pf.
AnnualSal = 12 months netSalary.
iii. void display( ) – to print the name and other calculations with suitable headings.
Write a program in Java to calculate all the details mentioned above and print them all.
Ans.
import java.util.*;
class SalaryCalculation
{
String name;
double basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary, AnnualSal;
SalaryCalculation()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”);
name=sc.nextLine();
System.out.println(“Enter the basic pay:”);
basicPay=sc.nextDouble();
conveyanceAlw=1000.00;
}
void SalaryCal()
{
specialAlw=25/100.0*basicPay;
pf=10/100.0*basicPay;
gross = basicPay + specialAlw + conveyanceAlw;
netSalary=gross-pf;
AnnualSal=12*netSalary;
}
void display()
{
System.out.println(“Name:”+name);
System.out.println(“Basic Pay:”+basicPay);
System.out.println(“Special Allwance:”+specialAlw);
System.out.println(“Conveyance allowance :”+conveyanceAlw);
System.out.println(“Gross:”+gross);
System.out.println(“Provident fund:”+pf);
System.out.println(“Net Salary:”+netSalary);
System.out.println(“Annual Salary:”+AnnualSal);
}
public static void main(String args[])
{
SalaryCalculation ob=new SalaryCalculation();
ob.SalaryCal();
ob.display();
}
}
14. A class Compound is created to calculate the compound interest using:
CI = P = (1+ r/100)2 – P where P – is the Principal amount, r – rate of interest and t-time period in years.
Data memebers of class: pamt, rate (double data type to store principal amount and rate of interest), time (integer to store time period)
Functions of the class:
i. Compound()-constructor to assign default values to all the data memebers.
ii. void input()-to input the principal, rate and time from the user.
iii. double findInterest()-to find and return compound interest using the given formula.
iv. void printData()-to print the principal, rate and time.
Write a main function to input required data and by invoking suitable functions print the entered data and compound interest.
Ans.
import java.util.*;
class Compound
{
double pamt, rate;
int time;
Compound()
{
pamt=rate=0.0;
time=0;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the principal:”);
pamt=sc.nextDouble();
System.out.println(“Enter the rate:”);
rate=sc.nextDouble();
System.out.println(“Enter the time:”);
time=sc.nextInt();
}
double findInterest()
{
double ci;
ci=pamt*Math.pow(1+rate/100.0,time)-pamt;
return ci;
}
void printData()
{
System.out.println(“Principal:”+pamt);
System.out.println(“Rate:”+rate);
System.out.println(“Time:”+time);
}
public static void main(String args[])
{
Compound ob=new Compound();
ob.input();
ob.printData();
System.out.println(“Compound Interest:”+ob.findInterest());
}
}
15. Define a class PhoneBill with the following descriptions.
Data members:
customerName of type character array
phoneNumber of type long
no_of_units of type int
rent of type int
amount of type float.
Member Functions:
i. calculate( ) This member function should calculate the value of amount as rent+ cost for the units.
where cost for the units can be calculated according to the following conditions.
No_of_units Cost
First 50 calls Free
Next 100 calls 0.80 @ unit
Next 200 calls 1.00 @ unit
Remaining calls 1.20 @ unit
ii. A constructor to assign initial values of customerName as “Raju”, phoneNumber as 259461, no_of_units as 50, rent as 100, amount as 100.
iii. A function accept( ) which allows user to enter customerName, phoneNumber, no_of_units and rent and should call function calculate( ).
iv. A function Display( ) to display the values of all the data members on the screen.
Ans.
import java.util.*;
class PhoneBill
{
String customerName;
long phoneNumber;
int no_of_units,rent;
float amount;
void calculate()
{
float cost=0;
if(no_of_units<=50)
cost=0;
else if(no_of_units>50 && no_of_units<=150)
cost=50*0+(no_of_units-50)*0.80f;
else if(no_of_units>150 && no_of_units<=350)
cost=50*0+100*0.80f+(no_of_units-150)*1.00f;
}
PhoneBill()
{
customerName=”Raju”;
phoneNumber=259461;
no_of_units=50;
amount=rent=100;
}
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the customer name:”);
customerName=sc.nextLine();
System.out.println(“Enter the phone number:”);
phoneNumber=sc.nextLong();
System.out.println(“Enter the no. of units:”);
no_of_units=sc.nextInt();
System.out.println(“Enter the rent:”);
rent=sc.nextInt();
}
void Display()
{
System.out.println(“Customer name:”+customerName);
System.out.println(“Phone number:”+phoneNumber);
System.out.println(“No. of units:”+no_of_units);
System.out.println(“Rent:”+rent);
System.out.println(“Amount:”+amount);
}
public static void main(String args[])
{
PhoneBill ob=new PhoneBill();
ob.accept();
ob.calculate();
ob.Display();
}
}
16. Define a class Sports with the following descriptions:
Data members:
s_code of type long
s_name of type (String)
fees of type integer
duration of type integer
Member Functions:
i Constructor to assign initial values of s_code as 1001, s_name as “Cricket”, fees as 500, duration as 70.
ii. A function newSports() which allows user to enter s_code, s_name and duration. Also assign the values to fees as per the following conditions:
s_name Fees
Table Tennis 2000
Swimming 4000
Football 3000
iii. A function displaySports() to display all the details.
Ans.
import java.util.*;
class Sports
{
String s_name;
long s_code;
int fees,duration;
Sports()
{
s_name=“Cricket”;
s_code=1001;
fees=500;
duration=70;
}
void newSports()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the code:”);
s_code=sc.nextLong();
System.out.println(“Enter the sports name:”);
s_name=sc.nextLine();
System.out.println(“Enter the duration:”);
duration=sc.nextInt();
if(s_name.equalsIgnoreCase(“Table Tennis”))
fees=2000;
else if(s_name.equalsIgnoreCase(“Swimming”))
fees=4000;
if(s_name.equalsIgnoreCase(“Football”))
fees=3000;
}
void displaySports()
{
System.out.println(“Code:”+s_code);
System.out.println(“Sports name:”+s_name);
System.out.println(“Duration:”+duration);
System.out.println(“Fees:”+fees);
}
}
17. Create a class called GeneratePrime which will be used to generate n number of prime numbers. The class should have the following members:
Data Members:
n of int data type.
Member Functions:
i. Parameterised constructor to initialise the value of n.
ii. Method called isPrime() which accepts an integer as a parameter and return true if it is a prime number otherwise return false.
Method called display() which displays the first n prime number by calling the above function.
Ans.
import java.util.*;
class GeneratePrime
{
int n;
GeneratePrime(int a)
{
n=a;
}
boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
void display()
{
int i=0,p=2;
while(i<n)
{
if(isPrime(p)==true)
{
System.out.println(p);
i++;
}
p++;
}
}
}
18. Create a class called PrimeDigits to find the sum of the prime digits in an integer. The class should have the following members.
Data Members:
n of int data type.
Member Functions:
i. Parameterised constructor to initialise the value of n.
ii. Method called isPrime() which accepts an integer as a parameter and return true if it is a prime number otherwise return false.
Method called sumOfPrimeDigits() which accepts an integer as a parameter and find the sum of prime digits only.
Ans.
import java.util.*;
class PrimeDigits
{
int n;
PrimeDigits(int a)
{
n=a;
}
boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
void sumOfPrimeDigits(int n)
{
int i=n,d,s=0;
while(i>0)
{
d=i%10;
if(isPrime(d)==true)
s=s+d;
i/=10;
}
System.out.println(“Sum of prime digits:”+s);
}
}
19. Create a class called Series which will contain the following members:
Data Members:
x of double type
n of int type
Member Functions:
i. Parameterised constructor to initialise the data members.
ii. To calculate and print the sum of the following series:
x+x/2!+x/3!+x/4!+…+x/n!
To calculate and print the sum of the following series:
x/2!+x2/3!+x3/4!+x4/5!+…+xn/(n+1)!
To calculate and print the sum of the following series:
x/2! – x2/3!+x3/4! – x4/5!+…±xn/(n+1)!
where the symbol ! stands for factorial eg. 5!=5*4*3*2*1, 3!=3*2*1
Ans.
import java.util.*;
class Series
{
double x;
int n;
Series(double x,int n)
{
this.x=x;
this.n=n;
}
void sumSeries1()
{
double s=0;
long i,p,j;
for(i=1;i<=n;i++)
{
p=1;
for(j=1;j<=i;j++)
{
p=p*j;
}
s=s+x/p;
}
System.out.println(“Sum=”+s);
}
void sumSeries2()
{
double s=0;
long i,p,j;
for(i=1;i<=n;i++)
{
p=1;
for(j=1;j<=i+1;j++)
{
p=p*j;
}
s=s+x*i/p;
}
System.out.println(“Sum=”+s);
}
void sumSeries3()
{
double s=0;
long i,p,j;
for(i=1;i<=n;i++)
{
p=1;
for(j=1;j<=i+1;j++)
{
p=p*j;
}
if(i%2!=0)
s=s+x*i/p;
else
s=s-x*i/p;
}
System.out.println(“Sum=”+s);
}
}
20. Create a class named Rounding which contains the following members:
Data members:
n and r of double type
Member Functions:
i. Constructor to read a real number from the keyboard into n.
ii. to round off n to two places of decimal and store it in r.
iii. to display the value of the data members.
Ans.
import java.util.*;
class Rounding
{
double n,r;
Rounding()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a real number in n:”);
n=sc.nextDouble();
}
void roundOff()
{
r=Math.round(n*100)/100.0;
}
void display()
{
System.out.println(“n=”+n+“r=”+r);
}
}
We believe that every student can get good marks by solving Library Classes Solutions. So, let’s start to learn Constructors Solutions class 10 for your exam.
You can also learn revision note for class 10 computer application prepared by our expert teachers at icseboards.com