Chapter 15: Encapsulation
Practice Questions
-------------------------->Objective-Type Questions<--------------------------
A. State whether true or false:
1. A class is used to implement encapsulation. [True]
2. Instance variables are used to represent behaviour of an object. [False]
3. You need to prefix the keyword default before data members which
should have default/friendly access specifier. [False]
4. The access specifier private allows accessibility of a member only within the
class where the member is declared/defined, but not outside the class. [True]
5. Java source code should always have the .jav extension. [False]
B. Fill in the blanks:
1. The access specifier protected allows accessibility within the same package by both
classes and sub-classes but only by sub-classes in a different package.
2. In case there are multiple classes in a source code the class from where the program
should start execution should have the access specifier as public.
3. The private access specifier is not allowed for a class.
4. The extends keyword is used to perform inheritance in Java.
5. The keyword used to include a class in a package is package.
C. Choose the correct answer:
1. Which among the following allows global accessibility?
a) public b) private c) protected d) All of these
Ans. a) public
2. Which among the following allows accessibility only within the class where the
member is defined or declared?
a) public b) private c) protected d) All of these
Ans. b) private
3. In case, a source code has multiple classes; the class from which the program begins
should have the ________________ access specifier.
a) public b) private c) protected d) All of these
Ans. a) public
4. Which among the following is true, if a constructor is declared as private for a class?
a) Another class may declare the object of that class.
b) An object may be declared only within that class.
c) An object may be declared in a different package.
d) None of these.
Ans. b) An object may be declared only within that class.
5. Which among the following is not true for inheritance?
a) The class which is being inherited is called the super-class and the class that inherits
it is called the sub-class.
b) The extends keyword is used to perform inheritance.
c) private members of a super-class is also inherited in the sub-class.
d) The member functions of a super-class can manipulate the values of the data-
members of a sub-class.
Ans. d) The member-functions of a super-class can manipulate the values of the data-
members of a sub-class.
6. Which among the following statements is true with respect to packages?
a) The command package <package-name>; should be the given as the first line inside
the class.
b) The command package <package-name>; should be the given just after the import
command.
c) The command package <package-name>; should be the given as the first line even
before the import statement.
d) The command package <package-name>; may be provided anywhere in the source
code.
Ans. c) The command package <package-name>; should be the given as the first line
even before the import statement.
7. Which operator is used to access individual subpackages and classes in a package?
a) + operator b) new operator c) this operator d) dot operator
Ans. d) dot operator
8. Which operator is used to import all classes within a package?
a) * b) all c) + d) None of these
Ans. a) *
9. Which menu among the following is used to create a package in BlueJ?
a) Project b) Edit c) Tools d) Help
Ans. b) Edit
10. Which among the following access specifiers allows accessibility outside that
package?
a) public and private b) public and protected
c) public and default d) private and protected.
Ans. b) public and protected
------------------------->Subjective-Type Questions<-------------------------
Answer the following questions:
1. What is a wrapper class? Give few examples of wrapper classes.
Ans. The wrapper class encapsulate or wrap the primitive data-types within a class to form
an object representation of it.
Examples of wrapper classes
2. What are access specifiers?
Ans. Access specifiers are keywords which is used to declare which entity cannot be
accessed from where. Its effect has different consequences when used on a class, class
member (variable or method), constructor. ava offers four access specifiers, listed below
in decreasing order of accessibility:
public
protected
default/friendly
private
3. Explain the statement:
Character c=‘A’;
Ans. An object named ‘c’ of the warapper class Character is being initialized with the
character constant ‘A’.
4. Given a statement:
String s= “123”;
Write a statement so that the numeric value of the variable s may be stored in an
integer.
int a=?
Ans. int a=[Link](s);
5. Given a statement:
double d=12.36;
Write a statement so that the numeric value of the variable d may be stored in a
String variable.
String a=?
Ans. String a=[Link](d);
6. Name the wrapper class function that converts an integer to a:
i) Binary Number
ii) Octal Number
iii) Hexadecimal Number
Ans. i) [Link]( ) ;
ii) [Link]( );
iii) [Link]( );
7. State the difference between parse...( ) and valueOf() method.
Ans. The parse...( ) method of the wrapper class converts a String to its corresponding
primitive data type and returns it whereas valueOf() method converts a String to the
corresponding wrapper object and returns it.
8. State the similarity difference between private and default access apecifier.
Ans. Similarity between private and default access specifier is that both allows
accessibility within the class.
Difference between private and default is that private access specifier allows accessibility only
within the class and default access specifier allows accessibility to all classes within a package.
9. What is a package? State its significance.
Ans. Package is a folder that contains compiled classes having both a name and a visibility control
mechanism for using its function in another class.
A package gives you an organized way of managing classes in Java. You can group related classes into
a package thus making it more organized. Similarly it is possible to define classes inside a package that
are not accessible by code outside the package. There may also be classes that are only exposed to other
members of the same package. This allows the classes to have intimate knowledge of each other, but
do not expose it to the entire world.
10. Why can’t a class be declared as private?
Ans. A class when defined as private, it will be impossible to access its members and
thus making it unusable.
11. Write the statement to import all classes from the Simple package.
Ans. import Simple.*;
Lab Exercises
Write programs for the following:
1. Create a class name Sentence having the following:
private data members: s of String type.
public member functions:
i) Parameterized constructor to initialize it with a sentence.
ii) To accepts a word as parameter and return true if it is palindrome else return
false.
iii) To print the longest palindrome word in s.
Create another public class called Main and input a sentence and print the longest
word in the sentence using the above class.
Ans. //Question 1
import [Link].*;
class Sentence
{
private String s;
public Sentence(String t)
{
s=t;
}
public boolean isPalindrome(String w)
{
int i;
char x;
String r="";
for(i=0;i<[Link]();i++)
{
x=[Link](i);
r=x+r;
}
if([Link](w))
return true;
else
return false;
}
public void longestPalindrome()
{
int i;
char x;
String w="",l="";
s=[Link]();
s+=" ";
for(i=0;i<[Link]();i++)
{
x=[Link](i);
if(x!=' ')
w=w+x;
else
{
if(isPalindrome(w))
{
if([Link]()>[Link]())
l=w;
}
w="";
}
}
[Link]("Longest Palindrome Word="+l);
}
public static void main(String args[])
{
String m;
Scanner sc=new Scanner([Link]);
[Link]("Enter a sentence:");
m=[Link]();
Sentence ob=new Sentence(m);
[Link]();
}
}
2. Define a class Employee having the following description: [ICSE 2008]
Data Members: int pan to store personal account number
String name to store name
double taxincome to store annual taxable income.
double tax to store tax that is calculated
461
Member functions:
input() : Store the pan number, name, taxeincome
calc() : Calculate tax for an employee
display() : Output details of an employee
Write a program to compute the tax according to the given conditions and display
the output as per given format.
Total Annual Taxable Income Tax Rate
Upto Rs. 1,00,000 No tax
From 1,00,001 to 1,50,000 10% of the income exceeding Rs.1,00,000
From 1,50,001 to 2,50,000 Rs.5000+20% of the income exceeding Rs.1,50,000
Above Rs.2,50,000 Rs. 25,000+30% of the income exceeding Rs.2,50,000
Ouput: Pan Number Name Tax-income Tax
---- ---- ---- ------ ----
---- ---- ---- ------ ----
Ans. //Question 2
import [Link].*;
class Employee
{
int pan;
String name;
double taxincome,tax;
void input()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the pan no.:");
pan=[Link]();
[Link]();//dummy input
[Link]("Enter your name:");
name=[Link]();
[Link]("Enter the annual taxable income:");
taxincome=[Link]();
}
void calc()
{
if(taxincome<=100000)
tax=0;
else if(taxincome<=150000)
tax=10/100.0*(taxincome-100000);
else if(taxincome<=250000)
tax=5000+20/100.0*(taxincome-150000);
else
tax=25000+30/100.0*(taxincome-250000);
}
void display()
{
[Link]("Pan Number\t\tName\t\tTax-income\t\tTax");
[Link](pan+"\t\t"+name+"\t\t"+taxincome+"\t\t"+tax);
}
}
3. Define a class Salary described as below:-
private data Members: Name, Address, Phone, Subject Specialization, Monthly
Salary, Income Tax.
public Member methods:
i) To accept the details of a teacher including the monthly salary.
ii) To display the details of the teacher.
iii) To compute the annual Income Tax as 5% of the annual salary above
Rs.1,75,000/-.
Write a main method to create object of the class and call the above member
method.
Ans. //Question 3
import [Link].*;
class Salary
{
private long phone;
private String name,address,subjectSpecialization;
private double monthlySalary,incomeTax;
public void input()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the phone no.:");
phone=[Link]();
[Link]();//dummy input
[Link]("Enter the name:");
name=[Link]();
[Link]("Enter the address:");
address=[Link]();
[Link]("Enter the Subject Specialization:");
subjectSpecialization=[Link]();
[Link]("Enter the monthly salary:");
monthlySalary=[Link]();
}
public void display()
{
[Link]("Phone no.:"+phone);
[Link]("Name:"+name);
[Link]("Address:"+address);
[Link]("Subject Specialization:"+subjectSpecialization);
[Link]("Monthly salary:"+monthlySalary);
[Link]("Income Tx:"+incomeTax);
}
public void calc()
{
double annualSalary;
annualSalary=12*monthlySalary;
if(annualSalary>175000)
incomeTax=5/100.0*(annualSalary-175000);
else
incomeTax=0;
}
public static void main(String args[])
{
Salary ob=new Salary();
[Link]();
[Link]();
[Link]();
}
}
4. A special number is a number in which the sum of the factorial of each digit is
equal to the number itself. For example, 145=1!+4!+5! =1+24+120
Design a class Special to check if a given number is a special number using the
given members:
Class name : Special
Data members/instance variables
n : Integer
Member functions:
Special() : constructor to assign 0 to n
Special(int) : parameterized constructor to assign a value to ‘n’.
int factorial(int p) : calculate and return the factorial of p.
void is Special() : check and display if the number ‘n’ is a special
number.
Also create another class named Main to input a number and check whether the
number is a Special Number or not.
Ans. //Question 4
import [Link].*;
class Special
{
int n;
Special()
{
n=0;
}
Special(int x)
{
n=x;
}
int factorial(int p)
{
int i,f=1;
for(i=1;i<=p;i++)
f=f*i;
return f;
}
void isSpecial()
{
int t=n,d,s=0;
while(t!=0)
{
d=t%10;
s=s+factorial(d);
t=t/10;
}
if(s==n)
[Link]("Special Number");
else
[Link]("Not a Special Number");
}
}
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int n;
[Link]("Enter a number:");
n=[Link]();
Special ob=new Special(n);
[Link]();
}
}
5. A class Modify has been defined with the following details:
Class name : Modify
Data members:
St : stores a string
Len : to store the length of the string
Member Functions:
void read() : to accept the string in Uppercase alphabets
void putin(int,char) : to insert a character at the specified position in the string
and display the changed string.
void takeout(int) : to remove character from the specified position in the
string and display the changed string
void change() : to replace each character in the original string by the
character which is at a distance of 2 moves ahead.
For example,
“ABCD” becomes “CDEF”
“XYZ” becomes “ZAP”
Specify the class Modify giving details of the functions void read(), void putin(int,
char), void takeout(int) and void change(). The main function need not be written.
Ans. //Question 5
import [Link].*;
class Modify
{
String st;
int len;
void read()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter a string:");
st=[Link]().toUpperCase();
len=[Link]();
}
void putin(int p,char x)
{
st=[Link](0,p)+x+[Link](p);
}
void takeout(int p)
{
st=[Link](0,p)+[Link](p+1);
}
void change()
{
int i;
char x;
String tst="";
for(i=0;i<len;i++)
{
x=[Link](i);
if(x=='Y')
x='A';
else if(x=='Z')
x='C';
else
x=(char)(x+2);
tst+=x;
}
st=tst;
}
}
6. Design a class named Myclass inside a package named myPackage, which will
contain two protected integer data members and a member function to add these
two data members and display them.
Now inherit this class into another class named SubClass outside myPackage.
Create member functions to initialize the two inherited data members and display
their sum. Also include a main( ) to show its implementation.
Ans. //Question 6
package myPackage;
public class Myclass
{
protected int a,b;
protected void sum()
{
int c;
c=a+b;
[Link](c);
}
}
//Question 6
import [Link];
class SubClass extends Myclass
{
void initialize(int x,int y)
{
a=x;
b=y;
public static void main(String args[])
{
SubClass ob=new SubClass();
[Link](5,6);
[Link]();
}
}
7. Create a class with the following members:
class name: Numbers
data member: int ar[ ]
Member Functions:
i) Constructor to allocate 20 spaces for ar.
ii) Generate twenty unique random numbers between 1 to 20 and store it in ar[ ].
Display the contents of ar[ ].
Also create another class named Main to implement the above class.
Ans. //Question 7
class Numbers
{
int ar[];
Numbers()
{
ar=new int[20];
}
void generate()
{
int i,j,f,r;
for(i=0;i<20;i++)
{
f=0;
r=1+(int)([Link]()*20);
for(j=0;j<i;j++)
{
if(ar[j]==r)
f=1;
}
if(f==0)
ar[i]=r;
else
i--;
}
}
void display()
{
int i;
for(i=0;i<20;i++)
{
[Link](ar[i]+" ");
}
}
public static void main(String args[])
{
Numbers ob=new Numbers();
[Link]();
[Link]();
}
}
8. Design a class with the following properties
Class Name: Student
Data Members: roll: of int type
name: of String type
Member Functions:
i) Parameterized constructor to initialize roll and name.
ii) to display only the name.
In the main () create an array of 10 objects initialize it by taking data through user
input. Now input a roll number and check which roll within the array of objects
matches. Upon matching print, the corresponding name, otherwise print a
relevant message.
Ans. //Question 8
import [Link].*;
class Student
{
int roll;
String name;
Student(int r,String n)
{
roll=r;
name=n;
}
void display()
{
[Link](name);
}
public static void main(String args[])
{
Student ob[]=new Student[10];
int i,r,f=0;
String n;
Scanner sc=new Scanner([Link]);
for(i=0;i<10;i++)
{
[Link]("Enter Roll No.:");
r=[Link]();
[Link]();//dummy input
[Link]("Enter Name:");
n=[Link]();
ob[i]=new Student(r,n);
}
[Link]("Enter a roll no. to search:");
r=[Link]();
for(i=0;i<10;i++)
{
if(ob[i].roll==r)
{
ob[i].display();
f=1;
}
}
if(f==0)
[Link]("Search Unsuccessful");
}
}
9. Design a class with the following properties
Class Name: Number System
Data Members: a and b of int data type.
Member Functions:
i) Parameterized constructor to initialize a and b with two binary numbers.
ii) boolean isBinary(int n) to check whether n is a binary number or not.
iii) Add the two binary numbers and display their result only if both the numbers
are binary.
In the main () create an object initialize it with two binary numbers and find their
sum after checking whether both the numbers are binary numbers or not.
Ans. import [Link].*;
//Question 9
class NumberSystem
{
int a,b;
NumberSystem(int x,int y)
{
a=x;
b=y;
}
boolean isBinary(int n)
{
int d;
boolean f=true;
while(n!=0)
{
d=n%10;
if(d!=1 && d!=0)
f=false;
n=n/10;
}
return f;
}
void add()
{
int d1,d2,s=0,c=0,carry=0,x;
if(isBinary(a) && isBinary(b))
{
while(a!=0 || b!=0)
{
d1=a%10;
d2=b%10;
x=d1+d2+carry;
if(x>=2)
{
x=x-2;
carry=1;
}
s=s+x*(int)[Link](10,c++);
a=a/10;
b=b/10;
}
s=s+carry*(int)[Link](10,c);
[Link]("Sum="+s);
}
else
[Link]("Not a valid binary number");
}
public static void main(String args[])
{
int x,y;
Scanner sc=new Scanner([Link]);
[Link]("Enter 2 valid binary numbers:");
x=[Link]();
y=[Link]();
NumberSystem ob=new NumberSystem(x,y);
[Link]();
}
}