Constructors
For which purpose a constructor is used?
- To initialise the instance variables
- To provide the instance variables
- To organise the instance variables
- To simplify the instance variables.
Answer
To initialise the instance variables
Reason — A constructor is used to initialise data members with default or user-defined values at the time of creation of an object.
Which of the following statements is false?
- A constructor has same name as class name.
- A constructor returns initial value.
- A constructor is called while creating an object.
- A constructor is not used for arithmetical and logical operations.
Answer
A constructor returns initial value.
Reason — A constructor has no return type as its primary function is to set initial values of data members at the time of creation of an object.
A constructor is always:
- private
- protected
- secure
- public
Answer
public
Reason — A constructor is always public because it is always called from outside the class while creating an object.
Which constructor initialises data members with default values?
- Parameterized constructor
- Non-parameterized constructor
- Copy constructor
- Default constructor
Answer
Default constructor
Reason — Default constructor initialises data members with default values.
What is not true for a constructor?
- It is used only to initialize the data members.
- It returns a unique value.
- It may not use parameter.
- None of the above.
Answer
It returns a unique value.
Reason — A constructor has no return type as it doesn't return any value.
A member function having the same name as that of the class name is called constructor.
A constructor has no return type.
A constructor is used when an object is created
A constructor without any argument is known as non-parameterised constructor.
Parameterised constructor creates objects by passing value to it.
The this keyword refers to the current object.
The argument of a copy constructor is always passed by reference.
The constructor generated by the compiler is known as default constructor.
The compiler supplies a special constructor in a class that does not have any constructor.
True
A constructor is not defined with any return type.
True
Every class must have all types of constructors.
False
A constructor is a member method of a class.
True
Constructor is used to initialize the data members of a class.
True
A constructor may have different name than the class name.
False
A constructor is likely to be defined after the class declaration.
False
Copy constructor copies functions from one object to another.
False
While creating a class, a specific method called constructor is defined to initialise the instance variables. Such method may or may not use parameters. In a case where the constructor is not defined in the class, the system creates on its own to put the default initial value to the instance variables. The initial values can also be duplicated from one instance to another.
Based on the above discussion, answer the following questions:
(a) Which name resembles with the constructor name?
(b) What type of constructor is used with parameters?
(c) What type of constructor initialises the instance variables with default value?
(d) Which constructor is used to duplicate the initial values from one constructor to other?
Answer
(a) Class name
(b) Parameterised constructor
(c) Default constructor
(d) Copy constructor
What is meant by a constructor?
Answer
A constructor is a member method having the same name as that of a class and is used to initialise the instance variables of the objects. 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.
Name the different types of constructors used while defining a class.
Answer
The different types of constructors used while defining a class are as follows:
- Parameterised constructor
- Non-parameterised constructor
Why do we need a constructor as a class member?
Answer
A constructor is used to initialize the objects of the class with a legal initial value.
Explain the following terms:
(a) Constructor with default argument
(b) Parameterised constructor
(c) Copy constructor
(d) Constructor overloading
Answer
(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 is a member method with the same name as the class name which is used to initialize the instance variables with the help of parametric values, passed at the time of creating an object.
(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.
Why is an object not passed to a constructor by value? Explain.
Answer
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.
State the difference between constructor and method.
Answer
Constructor | Method |
---|---|
It is a block of code that initializes a newly created object. | It is a group of statements that can be called at any point 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 has no return type | It needs a valid return type if it returns a value otherwise void |
It is called implicitly at the time of object creation | It is called explicitly by the programmer by making a method call |
If a constructor is not present, a default constructor is provided by Java | In case of a method, no default method is provided. |
It is not inherited by subclasses. | It may or may not be inherited depending upon its access specifier. |
Explain two features of a constructor.
Answer
Two features of a constructor are:
- A constructor has the same name as that of the class.
- A constructor has no return type, not even void.
Distinguish between parameterised constructor and non-parameterised constructor.
Answer
Parameterised constructor | Non-parameterised constructor |
---|---|
It initialises the instance variables with the help of parametric values passed at the time of creating an object. | It initialises the instance variables of an object with definite values readily available within it. |
It is defined with formal parameters in its parameter list. | It is defined with empty parameter list. |
For example, Test(int x, int y) { a = x; b = y; } | For example, Test() { a = 10; b = 5; } |
Name two ways of creating objects in a constructor.
Answer
The object can be created in two ways:
- Created by compiler
- Created by programmer
Differentiate between the following statements:
abc p = new abc();
abc p = new abc(5,7,9);
Answer
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.
Fill in the blanks to design a class:
class ...............
{
int l, b;
Area(int ..............., int ...............) {
l = ...............;
b = ...............;
}
}
Answer
class Area
{
int l, b;
Area(int x, int y) {
l = x;
b = y;
}
}
Write a program by using a class with the following specifications:
Class name — Hcflcm
Data members/instance variables:
- int a
- int b
Member Methods:
- Hcflcm(int x, int y) — constructor to initialize a=x and b=y.
- 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();
}
}
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:
- name
- price
- dis
- amt
Member Methods:
- A parameterised constructor to initialize the data members
- To accept the details (name of the customer and the price)
- To compute the discount
- 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();
}
}
Write a program by using a class with the following specifications:
Class name — Calculate
Instance variables:
- int num
- int f
- int rev
Member Methods:
- Calculate(int n) — to initialize num with n, f and rev with 0 (zero)
- int prime() — to return 1, if number is prime
- int reverse() — to return reverse of the number
- 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();
}
}
Define a class Arrange described as below:
Data members/instance variables:
- String str (a word)
- String i
- int p (to store the length of the word)
- char ch;
Member Methods:
- A parameterised constructor to initialize the data member
- To accept the word
- To arrange all the alphabets of word in ascending order of their ASCII values without using the sorting technique
- 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();
}
}
Write a program by using a class in Java with the following specifications:
Class name — Stringop
Data members:
- String str
Member functions:
- Stringop() — to initialize str with NULL
- void accept() — to input a sentence
- 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
- 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();
}
}
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:
- Population(int a,int b) — Constructor to initialize p and r with a and b respectively.
- 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();
}
}
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:
- quad(int x,int y,int z) — to initialize a=x, b=y, c=z, d=0
- 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();
}
}
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 |
---|---|
FruitJuice() | constructor to initialize integer data members to 0 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 |
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();
}
}
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();
}
}
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 |
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 Methods | Purpose |
---|---|
Student( ) | parameterised constructor to initialize the data members by accepting the 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();
}
}
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 Methods | Purpose |
---|---|
Bill() | constructor to initialize data members with default initial value |
Bill(...) | parameterised constructor to accept billno, name and no. of calls consumed |
Calculate() | to calculate the monthly telephone bill for a consumer as per the table given 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();
}
}
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 Methods | Purpose |
---|---|
BookFair( ) | Constructor to initialize data members |
void input( ) | To input and store the name and price of the book |
void calculate( ) | To calculate the price after discount. Discount is calculated as per the table 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 |
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();
}
}