Chapter 7: Constructors
CLASS – X
Fill in the blanks
Question 1
A member function having the same name as that of the class name is called constructor.
Question 2
A constructor has return no type.
Question 3
A constructor is used when an object is created
Question 4
A constructor without any argument is known as non-parameterised constructor.
Question 5
Parameterised constructor creates objects by passing value to it.
Question 6
The this keyword refers to the current object.
Question 7
The argument of a copy constructor is always passed by reference.
Question 8
The constructor generated by the compiler is known as default constructor.
Write TRUE or FALSE for the following statements
Question 1
The compiler supplies a special constructor in a class that does not have any constructor.
True
Question 2
A constructor is not defined with any return type.
True
Question 3
Every class must have all types of constructors.
False
Question 4
A constructor is a member function of a class.
True
Question 5
Constructor is used to initialize the data members of a class.
True
Question 6
A constructor may have different name than the class name.
False
Question 7
A constructor is likely to be defined after the class declaration.
False
Question 8
Copy constructor copies functions from one object to another.
False
Answer the following
Question 1
What is meant by a constructor?
A constructor is a member method that is written with the same name as the class name
and is used to initialize the data members or instance variables. It is invoked at the time of
creating any object of the class. For example:
Employee emp = new Employee();
Here, Employee() is invoking a default constructor.
Question 2
Name the different types of constructors used in a class program.
1. Parameterised constructor
2. Non-parameterised constructor
Question 3
Why do we need a constructor as a class member?
A constructor is used to initialize the objects of the class with a legal initial value.
Question 4
Explain the following terms:
(a) Constructor with default argument
Java specification doesn't support default arguments in methods so Constructor with
default argument cannot be written in Java.
(b) Parameterised constructor
A Parameterised constructor receives parameters at the time of creating an object and
initializes the object with the received values.
(c) Copy constructor
A constructor used to initialize the instance variables of an object by copying the initial
values of the instance variables from another object is known as Copy Constructor.
(d) Constructor overloading
The process of using a number of constructors with the same name but different types of
parameters is known as Constructor overloading.
Question 5
Why is an object not passed to a constructor by value? Explain.
Constructors are special member methods of the class. Objects are non-primitive data
types so they are passed by reference and not by value to constructors. If objects were
passed by value to a constructor then to copy the objects from actual arguments to formal
arguments, Java would again invoke the constructor. This would lead to an endless circular
loop of constructor calls.
Question 6
State the difference between constructor and method.
Constructor Method
It is a block of code that initializes a It is a group of statements that can be called at any point
newly created object. in the program using its name to perform a specific task.
It has the same name as class name. It should have a different name than class name.
It needs a valid return type if it returns a value otherwise
It has no return type
void
It is called implicitly at the time of It is called explicitly by the programmer by making a
object creation method call
If a constructor is not present, a default
In case of a method, no default method is provided.
constructor is provided by Java
It may or may not be inherited depending upon its access
It is not inherited by subclasses.
specifier.
Question 7
Explain two features of a constructor.
1. A constructor has the same name as that of the class.
2. A constructor has no return type, not even void.
Question 8
Differentiate between the following statements:
abc p = new abc();
abc p = new abc(5,7,9);
The first statement abc p = new abc(); is calling a non-parameterised constructor to create
and initialize an object p of class abc. The second statement abc p = new abc(5,7,9); is
calling a parameterised constructor which accepts three arguments to create and initialize an
object p of class abc.
Question 9
Fill in the blanks to design a class:
class Area
{
int l, b;
Area(int x, int y) {
l = x;
b = y;
}
}
Question 10
Create a class Rectangle with data members length, breadth and height. Use a parameterised
constructor to initialize the object. With the help of function surfacearea() and volume(),
calculate and display the surface area and volume of the rectangle.
Answer
class Rectangle {
double length;
double breadth;
double height;
public Rectangle(double l, double b, double h) {
length = l;
breadth = b;
height = h;
}
public void surfacearea() {
double sa = 2 * (length * breadth + breadth * height + length *
height);
System.out.println("Surface Area = " + sa);
}
public void volume() {
double vol = length * breadth * height;
System.out.println("Volume = " + vol);
}
}
Question 11
What are the temporary instances of a class?
If we don't assign an object created by the new operator to a variable then it is known as a
temporary instance or an anonymous object. If we want to use an object only once, then we
can use it as a temporary instance. The below example illustrates this:
class Sum {
int x;
int y;
public Sum(int a, int b) {
x = a;
y = b;
}
public void computeSum() {
int s = x + y;
System.out.println("Sum = " + s);
}
public static void main(String[] args) {
new Sum(3, 5).computeSum();
}
}
In the main method, the object of class Sum is not assigned to any variable. We use it just
to print the sum of 3 and 5 after which it is destroyed.
Question 12
Create a class Right_Triangle having data members as the perpendicular and base of a right-
angled triangle(int p, int b). Use a parameterised constructor to initialize the object. With the help
of function area( ) and diagonal( ), calculate and display the area and diagonal of the right angled
triangle.
Answer
class Right_Triangle {
int p;
int b;
public Right_Triangle(int x, int y) {
p = x;
b = y;
}
public void area() {
double a = 0.5 * p * b;
System.out.println("Area = " + a);
}
public void diagonal() {
double c = Math.sqrt(p * p + b * b);
System.out.println("Diagonal = " + c);
}
}
Solutions to Unsolved Java Programs
Question 1
Write a program by using a class with the following specifications:
Class name — Hcflcm
Data members/instance variables:
1. int a
2. int b
Member functions:
1. Hcflcm(int x, int y) — constructor to initialize a=x and b=y.
2. void calculate( ) — to find and print hcf and lcm of both the numbers.
import java.util.Scanner;
public class Hcflcm
{
private int a;
private int b;
public Hcflcm(int x, int y) {
a = x;
b = y;
}
public void calculate() {
int x = a, y = b;
while (y != 0) {
int t = y;
y = x % y;
x = t;
}
int hcf = x;
int lcm = (a * b) / hcf;
System.out.println("HCF = " + hcf);
System.out.println("LCM = " + lcm);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
int x = in.nextInt();
System.out.print("Enter second number: ");
int y = in.nextInt();
Hcflcm obj = new Hcflcm(x,y);
obj.calculate();
}
}
Output
Question 2
An electronics shop has announced a special discount on the purchase of Laptops as given
below:
Category Discount on Laptop
Up to ₹25,000 5.0%
₹25,001 - ₹50,000 7.5%
₹50,001 - ₹1,00,000 10.0%
More than ₹1,00,000 15.0%
Define a class Laptop described as follows:
Data members/instance variables:
1. name
2. price
3. dis
4. amt
Member Methods:
1. A parameterised constructor to initialize the data members
2. To accept the details (name of the customer and the price)
3. To compute the discount
4. To display the name, discount and amount to be paid after discount.
Write a main method to create an object of the class and call the member methods.
import java.util.Scanner;
public class Laptop
{
private String name;
private int price;
private double dis;
private double amt;
public Laptop(String s, int p)
{
name = s;
price = p;
}
public void compute() {
if (price <= 25000)
dis = price * 0.05;
else if (price <= 50000)
dis = price * 0.075;
else if (price <= 100000)
dis = price * 0.1;
else
dis = price * 0.15;
amt = price - dis;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Discount: " + dis);
System.out.println("Amount to be paid: " + amt);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Customer Name: ");
String str = in.nextLine();
System.out.print("Enter Price: ");
int p = in.nextInt();
Laptop obj = new Laptop(str,p);
obj.compute();
obj.display();
}
}
Output
Question 3
Write a program by using a class with the following specifications:
Class name — Calculate
Instance variables:
1. int num
2. int f
3. int rev
Member Methods:
1. Calculate(int n) — to initialize num with n, f and rev with 0 (zero)
2. int prime() — to return 1, if number is prime
3. int reverse() — to return reverse of the number
4. void display() — to check and print whether the number is a prime palindrome or not
import java.util.Scanner;
public class Calculate
{
private int num;
private int f;
private int rev;
public Calculate(int n) {
num = n;
f = 0;
rev = 0;
}
public int prime() {
f = 1;
if (num == 0 || num == 1)
f = 0;
else
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
f = 0;
break;
}
}
return f;
}
public int reverse() {
int t = num;
while (t != 0) {
int digit = t % 10;
rev = rev * 10 + digit;
t /= 10;
}
return rev;
}
public void display() {
if (f == 1 && rev == num)
System.out.println(num + " is prime palindrome");
else
System.out.println(num + " is not prime palindrome");
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int x = in.nextInt();
Calculate obj = new Calculate(x);
obj.prime();
obj.reverse();
obj.display();
}
}
Output
Question 4
Define a class Arrange described as below:
Data members/instance variables:
1. String str (a word)
2. String i
3. int p (to store the length of the word)
4. char ch;
Member Methods:
1. A parameterised constructor to initialize the data member
2. To accept the word
3. To arrange all the alphabets of word in ascending order of their ASCII values without
using the sorting technique
4. To display the arranged alphabets.
Write a main method to create an object of the class and call the above member methods.
import java.util.Scanner;
public class Arrange
{
private String str;
private String i;
private int p;
private char ch;
public Arrange(String s) {
str = s;
i = "";
p = s.length();
ch = 0;
}
public void rearrange() {
for (int a = 65; a <= 90; a++) {
for (int j = 0; j < p; j++) {
ch = str.charAt(j);
if (a == Character.toUpperCase(ch))
i += ch;
}
}
}
public void display() {
System.out.println("Alphabets in ascending order:");
System.out.println(i);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
Arrange obj = new Arrange(word);
obj.rearrange();
obj.display();
}
}
Output
Question 5
Write a program by using a class in Java with the following specifications:
Class name — Stringop
Data members:
1. String str
Member functions:
1. Stringop() — to initialize str with NULL
2. void accept() — to input a sentence
3. void encode() — to replace and print each character of the string with the second next
character in the ASCII table. For example, A with C, B with D and so on
4. void print() — to print each word of the String in a separate line
import java.util.Scanner;
public class Stringop
{
private String str;
public Stringop() {
str = null;
}
public void accept() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence: ");
str = in.nextLine();
}
public void encode() {
char[] arr = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
arr[i] = (char)(str.charAt(i) + 2);
}
str = new String(arr);
System.out.println("\nEncoded Sentence:");
System.out.println(str);
}
public void print() {
System.out.println("\nPrinting each word on a separate line:");
int s = 0;
while (s < str.length()) {
int e = str.indexOf(' ', s);
if (e == -1)
e = str.length();
System.out.println(str.substring(s, e));
s = e + 1;
}
}
public static void main(String args[]) {
Stringop obj = new Stringop();
obj.accept();
obj.print();
obj.encode();
}
}
Output
Question 6
The population of a country in a particular year can be calculated by:
p*(1+r/100) at the end of year 2000, where p is the initial population and r is the
growth rate.
Write a program by using a class to find the population of the country at the end of each year
from 2001 to 2007. The Class has the following specifications:
Class name — Population
Data Members — float p,r
Member Methods:
1. Population(int a,int b) — Constructor to initialize p and r with a and b respectively.
2. void print() — to calculate and print the population of each year from 2001 to 2007.
import java.util.Scanner;
public class Population
{
private float p;
private float r;
public Population(float a, float b)
{
p = a;
r = b;
}
public void print() {
float q = p;
for (int y = 2001; y <= 2007; y++) {
q = q * (1 + r / 100);
System.out.println("Population in " + y + ": " + q);
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter population in the year 2000: ");
float x = in.nextFloat();
System.out.print("Enter growth rate: ");
float y = in.nextFloat();
Population obj = new Population(x,y);
obj.print();
}
}
Output
Question 7
Write a program in Java to find the roots of a quadratic equation ax2+bx+c=0 with the following
specifications:
Class name — Quad
Data Members — float a,b,c,d (a,b,c are the co-efficients & d is the discriminant), r1 and r2 are
the roots of the equation.
Member Methods:
1. quad(int x,int y,int z) — to initialize a=x, b=y, c=z, d=0
2. void calculate() — Find d=b2-4ac
If d < 0 then print "Roots not possible" otherwise find and print:
r1 = (-b + √d) / 2a
r2 = (-b - √d) / 2a
import java.util.Scanner;
public class Quad
{
private float a;
private float b;
private float c;
private float d;
private float r1;
private float r2;
public Quad(float x, float y, float z)
{
a = x;
b = y;
c = z;
d = 0;
}
public void calculate() {
d= (b * b) - (4 * a * c);
if (d < 0)
System.out.println("Roots not possible");
else {
r1 = (float)((-b + Math.sqrt(d)) / (2 * a));
r2 = (float)((-b - Math.sqrt(d)) / (2 * a));
System.out.println("r1=" + r1);
System.out.println("r2=" + r2);
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
float x = in.nextFloat();
System.out.print("Enter b: ");
float y = in.nextFloat();
System.out.print("Enter z: ");
float z = in.nextFloat();
Quad obj = new Quad(x,y,z);
obj.calculate();
}
}
Output
Question 8
Define a class named FruitJuice with the following description:
Data Members Purpose
int product_code stores the product code number
String flavour stores the flavour of the juice (e.g., orange, apple, etc.)
String pack_type stores the type of packaging (e.g., tera-pack, PET bottle, etc.)
int pack_size stores package size (e.g., 200 mL, 400 mL, etc.)
int product_price stores the price of the product
Member Methods Purpose
constructor to initialize integer data members to 0 and string data members to
FruitJuice()
""
to input and store the product code, flavour, pack type, pack size and product
void input()
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
import java.util.Scanner;
public class FruitJuice
{
private int product_code;
private String flavour;
private String pack_type;
private int pack_size;
private int product_price;
public FruitJuice() {
product_code = 0;
flavour = "";
pack_type = "";
pack_size = 0;
product_price = 0;
}
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter Flavour: ");
flavour = in.nextLine();
System.out.print("Enter Pack Type: ");
pack_type = in.nextLine();
System.out.print("Enter Product Code: ");
product_code = in.nextInt();
System.out.print("Enter Pack Size: ");
pack_size = in.nextInt();
System.out.print("Enter Product Price: ");
product_price = in.nextInt();
}
public void discount() {
product_price -= 10;
}
public 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 obj = new FruitJuice();
obj.input();
obj.discount();
obj.display();
}
}
Output
Question 9
The basic salary of employees is undergoing a revision. Define a class called Grade_Revision
with the following specifications:
Data Members Purpose
String name to store name of the employee
int bas to store basic salary
int expn to consider the length of service as an experience
double inc to store increment
double nbas to store new basic salary (basic + increment)
Member Methods Purpose
Grade_Revision() constructor to initialize all data members
void accept() to input name, basic and experience
void increment() to calculate increment based on experience as per the table given below
void display() to print all the details of an employee
Experience Increment
Up to 3 years ₹1,000 + 10% of basic
3 years or more and up to 5 years ₹3,000 + 12% of basic
5 years or more and up to 10 years ₹5,000 + 15% of basic
10 years or more ₹8,000 + 20% of basic
Write the main method to create an object of the class and call all the member methods.
import java.util.Scanner;
public class Grade_Revision
{
private String name;
private int bas;
private int expn;
private double inc;
private double nbas;
public Grade_Revision() {
name = "";
bas = 0;
expn = 0;
inc = 0.0;
nbas = 0.0;
}
public void accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter basic: ");
bas = in.nextInt();
System.out.print("Enter experience: ");
expn = in.nextInt();
}
public void increment() {
if (expn <= 3)
inc = 1000 + (bas * 0.1);
else if (expn <= 5)
inc = 3000 + (bas * 0.12);
else if (expn <= 10)
inc = 5000 + (bas * 0.15);
else
inc = 8000 + (bas * 0.2);
nbas = bas + inc;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Basic: " + bas);
System.out.println("Experience: " + expn);
System.out.println("Increment: " + inc);
System.out.println("New Basic: " + nbas);
}
public static void main(String args[]) {
Grade_Revision obj = new Grade_Revision();
obj.accept();
obj.increment();
obj.display();
}
}
Output
Question 10
Define a class called Student to check whether a student is eligible for taking admission in class
XI with the following specifications:
Data Members Purpose
String name to store name
Data Members Purpose
int mm to store marks secured in Maths
int scm to store marks secured in Science
double comp to store marks secured in Computer
Member
Purpose
Methods
parameterised constructor to initialize the data members by accepting the
Student( )
details of a student
check( ) to check the eligibility for course based on the table given below
void display() to print the eligibility by using check() function in nested form
Marks Eligibility
90% or more in all the subjects Science with Computer
Average marks 90% or more Bio-Science
Average marks 80% or more and less than 90% Science with Hindi
Write the main method to create an object of the class and call all the member methods.
import java.util.Scanner;
public class Student
{
private String name;
private int mm;
private int scm;
private int comp;
public Student(String n, int m, int sc, int c) {
name = n;
mm = m;
scm = sc;
comp = c;
}
private String check() {
String course = "Not Eligible";
double avg = (mm + scm + comp) / 3.0;
if (mm >= 90 && scm >= 90 && comp >= 90)
course = "Science with Computer";
else if (avg >= 90)
course = "Bio-Science";
else if (avg >= 80)
course = "Science with Hindi";
return course;
}
public void display() {
String eligibility = check();
System.out.println("Eligibility: " + eligibility);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Name: ");
String n = in.nextLine();
System.out.print("Enter Marks in Maths: ");
int maths = in.nextInt();
System.out.print("Enter Marks in Science: ");
int sci = in.nextInt();
System.out.print("Enter Marks in Computer: ");
int compSc = in.nextInt();
Student obj = new Student(n, maths, sci, compSc);
obj.display();
}
}
Output
Question 11
Define a class Bill that calculates the telephone bill of a consumer with the following
description:
Data Members Purpose
int bno bill number
String name name of consumer
int call no. of calls consumed in a month
double amt bill amount to be paid by the person
Member
Purpose
Methods
Bill() constructor to initialize data members with default initial value
Bill(...) parameterised constructor to accept billno, name and no. of calls consumed
to calculate the monthly telephone bill for a consumer as per the table given
Calculate()
below
Display() to display the details
Units consumed Rate
First 100 calls ₹0.60 / call
Next 100 calls ₹0.80 / call
Next 100 calls ₹1.20 / call
Above 300 calls ₹1.50 / call
Fixed monthly rental applicable to all consumers: ₹125
Create an object in the main() method and invoke the above functions to perform the desired
task.
import java.util.Scanner;
public class Bill
{
private int bno;
private String name;
private int call;
private double amt;
public Bill() {
bno = 0;
name = "";
call = 0;
amt = 0.0;
}
public Bill(int bno, String name, int call) {
this.bno = bno;
this.name = name;
this.call = call;
}
public void calculate() {
double charge;
if (call <= 100)
charge = call * 0.6;
else if (call <= 200)
charge = 60 + ((call - 100) * 0.8);
else if (call <= 300)
charge = 60 + 80 + ((call - 200) * 1.2);
else
charge = 60 + 80 + 120 + ((call - 300) * 1.5);
amt = charge + 125;
}
public void display() {
System.out.println("Bill No: " + bno);
System.out.println("Name: " + name);
System.out.println("Calls: " + call);
System.out.println("Amount Payable: " + amt);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Name: ");
String custName = in.nextLine();
System.out.print("Enter Bill Number: ");
int billNum = in.nextInt();
System.out.print("Enter Calls: ");
int numCalls = in.nextInt();
Bill obj = new Bill(billNum, custName, numCalls);
obj.calculate();
obj.display();
}
}
Output
Question 12
Define a class called BookFair with the following description:
Data Members Purpose
String Bname stores the name of the book
double price stores the price of the book
Member
Purpose
Methods
BookFair( ) Constructor to initialize data members
void input( ) To input and store the name and price of the book
To calculate the price after discount. Discount is calculated as per the table
void calculate( )
given below
void display( ) To display the name and price of the book after discount
Price Discount
Less than or equal to ₹1000 2% of price
More than ₹1000 and less than or equal to ₹3000 10% of price
Price Discount
More than ₹3000 15% of price
Write a main method to create an object of the class and call the above member methods.
import java.util.Scanner;
public class BookFair
{
private String bname;
private double price;
public BookFair() {
bname = "";
price = 0.0;
}
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter name of the book: ");
bname = in.nextLine();
System.out.print("Enter price of the book: ");
price = in.nextDouble();
}
public void calculate() {
double disc;
if (price <= 1000)
disc = price * 0.02;
else if (price <= 3000)
disc = price * 0.1;
else
disc = price * 0.15;
price -= disc;
}
public void display() {
System.out.println("Book Name: " + bname);
System.out.println("Price after discount: " + price);
}
public static void main(String args[]) {
BookFair obj = new BookFair();
obj.input();
obj.calculate();
obj.display();
}
}
Output