Page |1
DDEC INTERNATIONAL SCHOOL
Ghatampur Kanpur Nagar
IMPORTANT QUESTION/ANSWER
COMPUTER APPLICATION
TOPIC - CONSTRUCTORS/STRING HANDLING
ASSIGNMENT QUESTIONS
Question 1
What is a constructor ? What does it do ?
Answer
A constructor is a member function with the same name as that of its class but no
return type.
A constructor is used to initialize the objects of that class type with legal initial
values.
Question 2
What is that class called which does not have a public constructor ?
Answer
A class which does not have a public constructor is called a private class as only
the member functions may declare objects of the class.
Question 3
When is a constructor automatically invoked ?
Answer
A constructor is automatically invoked when the object of a class is created.
SHIVAM TRIPATHI
Page |2
Question 4
Write two characteristics of a constructor.
Answer
Two characteristics of a constructor are:
1. It has the same name as that of its class.
2. It has no return type, not even void.
Question 5
Write a class specifier (along with its constructor) that creates a class student
having two private data members : rollno and grade and two public functions init(
) and display( ).
(Do not write full definitions of member functions except for constructor).
Answer
class student
{
private int rollno;
private char grade;
public student() {
rollno = 0;
grade = '\0';
}
public student(int roll, char g)
{
rollno = roll;
grade = g;
}
public void init() {}
public void display() {}
}
SHIVAM TRIPATHI
Page |3
Question 6
Can you think of the benefits of a private class if any ? What are they ?
Answer
The benefits of a private class (i.e., a class with a private constructor) are:
1. Controlled object creation — By making the constructor private, we can
control the number of objects of a class that can be created. We can also
enforce certain rules or constraints on how the object is created and used.
2. Better memory management — By limiting the number of objects of a
class that can be created, we can reduce memory usage and improve
performance.
Question 7
Here is a skeleton definition of a class :
class Sample
{
int i;
char c;
float f;
:
//public members
:
}
Implement the constructor.
Answer
The constructor of the class is given below:
public Sample(int a, char b, float c)
{
i = a;
c = b;
f = c;
}
Question 8
SHIVAM TRIPATHI
Page |4
Define a constructor function for a Date class that initializes the Date objects with
given initial values. In case initial values are not provided, it should initialize the
object with default values.
Answer
public Date()
{
day = 1;
month = 1;
year = 1970;
}
public Date(int d, int m, int y)
{
day = d;
month = m;
year = y;
}
Question 9
What condition(s) a function must specify in order to create objects of a class ?
Answer
Every time an object is created, the constructor is automatically invoked. If the
function creating the object, does not have access privilege for the constructor, it
cannot be invoked for that function. Thus, the object cannot be created by such
function.
Therefore, it is essential for a function to have access privilege for the constructor
in order to create objects of a class.
Question 10
Constructor functions obey the usual access rules. What does this statement mean
?
Answer
Constructor functions obey the usual access rules. It means that a private or
protected constructor is not available to the non-member functions.
SHIVAM TRIPATHI
Page |5
With a private or protected constructor, one cannot create an object of the same
class in a non-member function. Only the member functions of that class can
create an object of the same class and invoke the constructor.
Question 11
How are parameterized constructors different from non-parameterized
constructors?
Answer
Parameterised constructor Non-parameterised constructor
Parameterised constructor receives
Non-parameterised constructor does not
parameters and uses them to
accept parameters and initialises the object's
initialise the object's member
member variables with default values.
variables.
Non-parameterised constructors are
Parameterised constructors need to
considered default constructors. If no
be explicitly defined for the class.
constructor is explicitly defined, then the
They are never created
compiler automatically creates a non-
automatically by the compiler.
parameterized constructor.
For example, For example,
Test(int x, int y) Test()
{ {
a = x; a = 10;
b = y; b = 5;
} }
Question 12
What are benefits/drawbacks of temporary instances ?
Answer
SHIVAM TRIPATHI
Page |6
The benefit of temporary instances is that they live in the memory as long as they
are being used or referenced in an expression and after this, they are deleted by
the compiler. The memory is freed as soon as they are deleted rather than staying
in the memory till the program completes execution.
The drawback of temporary instances is that they are anonymous i.e., they do not
bear a name. Thus, they cannot be reused in a program.
Question 13
How do we invoke a constructor ?
Answer
A constructor is invoked automatically when an object of a class is created. The
constructor is called using the new keyword followed by the name of the class
and a set of parentheses. If the constructor requires arguments, the arguments are
passed inside the parentheses.
For example, suppose we have a class named Person with a parameterized
constructor that takes two arguments name and age. To create an object of this
class and invoke the constructor, we would use the following code:
Person personObj = new Person("John", 30);
Question 14
How can objects be initialized with desired values at the time of object creation ?
Answer
Objects can be initialized with desired values at the time of object creation by
using parameterized constructor and passing the desired values as arguments at
the time of creation of object.
Question 15
When a compiler can automatically generate a constructor if it is not defined then
why is it considered that writing constructors for a class is a good practice ?
Answer
Writing constructors for a class is considered a good practice for the following
reasons:
SHIVAM TRIPATHI
Page |7
1. Control over object creation — By writing our own constructors, we can
control how objects of our class are created and initialised. It ensures
initialising member variables to specific values and executing certain
initialisation logic before the object is used.
2. Parameter validation — We can prevent runtime errors and bugs by
validating input parameters and ensuring only valid objects are created.
3. Flexibility — Multiple constructors allows users of the class to create
objects in different ways, depending on their needs. This makes the class
more flexible and easier to use.
Question 16
'Accessibility of a constructor greatly affects the scope and visibility of their
class.' Elaborate this statement.
Answer
Every time an object is created, it is automatically initialised by the constructor of
the class. Therefore, it is very much necessary for the constructor of a class to be
accessible by the function in which the object is created. If the constructor of a
class is declared 'private' or 'protected', then the scope and visibility of the
constructor (and the class) is defined by the rules of the access specifier.
In such a case, a function not having access to constructor of a class cannot
declare and use objects of that class. Hence, accessibility of a constructor greatly
affects the scope and visibility of their class.
Question 17
List some of the special properties of the constructor functions.
Answer
Some of the special properties of the constructor functions are as follows:
1. It has the same name as that of its class.
2. It doesn't have any return type, not even void.
3. It adheres to the rules of access specifiers.
4. It can be parameterized or non-parameterized.
5. It is used to create and initialize objects from a class.
SHIVAM TRIPATHI
Page |8
6. It can be overloaded to provide multiple ways of creating objects with
different initialisation parameters
7. It is always called implicitly when an object is created using
the new keyword.
Question 18
What is a parameterized constructor ? How is it useful ?
Answer
Parameterized constructors are the constructors that receive parameters and
initialize objects with received values. For example:
class XYZ
{
private int i;
private float j;
XYZ(int a, float b) //parameterized constructor
{
i=a;
j = b;
}
:
//other members
:
}
Parameterized constructors are useful in the following ways:
1. Control over object creation — By writing our own constructors, we can
control how objects of our class are created and initialised. It ensures
initialising member variables to specific values and executing certain
initialisation logic before the object is used.
2. Parameter validation — We can prevent runtime errors and bugs by
validating input parameters and ensuring only valid objects are created.
Question 19
Design a class to represent a bank account. Include the following members:
SHIVAM TRIPATHI
Page |9
Data members
1. Name of the depositor
2. Account number
3. Type of account
4. Balance amount in the account
Methods
1. To assign initial values
2. To deposit an amount
3. To withdraw an amount after checking balance
4. To display the name and balance
5. Do write proper constructor functions
Answer
class BankAccount
{
private String name;
private long accno;
private char type;
private double bal;
BankAccount() {
name = "";
accno = 0;
type = '\0';
bal = 0.0d;
}
BankAccount(String n, long accnumber, char t, double b) {
name = n;
accno = accnumber;
type = t;
bal = b;
}
public void deposit(double amt) {
bal = bal + amt;
System.out.println("Amount deposited: Rs. " + amt);
SHIVAM TRIPATHI
P a g e | 10
System.out.println("Balance: Rs. " + bal);
}
public void withdraw(double amt) {
if(amt <= bal) {
bal = bal - amt;
System.out.println("Amount withdrawn: Rs. " + amt);
System.out.println("Balance: Rs. " + bal);
}
else {
System.out.println("Insufficient Balance");
}
}
public void display()
{
System.out.println("Name: " + name);
System.out.println("Balance: Rs. " + bal);
}
}
ASSIGNMENT QUESTIONS
Question 1
What are String and StringBuffer classes of Java?
Answer
In Java, we can work with characters by using String and StringBuffer class.
String class — The instances of String class can hold unchanging string, which
once initialized cannot be modified. For example,
String s1 = new String("Hello");
StringBuffer class — The instances of StringBuffer class can hold mutable
strings, that can be changed or modified. For example,
StringBuffer sb1 = new StringBuffer("Hello");
SHIVAM TRIPATHI
P a g e | 11
Question 2
How are Strings different from StringBuffers ?
Answer
The string objects of Java are immutable i.e., once created, they cannot be
changed. If any change occurs in a string object, then original string remains
unchanged and a new string is created with the changed string.
On the other hand, StringBuffer objects are mutable. Thus, these objects can be
manipulated and modified as desired.
Question 3
How can you convert a numeric value enclosed in a string format ?
Answer
We can convert a numeric value enclosed in a string format into a numeric value
by using valueOf() method.
For example, the given statement will return the numeric value of the String
argument "15".
int num = Integer.valueOf("15");
Question 4
Write the return type of the following library functions :
1. isLetterOrDigit(char)
2. replace(char, char)
Answer
1. boolean
2. String
Question 5
State the data type and values of a and b after the following segment is executed.
SHIVAM TRIPATHI
P a g e | 12
String s1 = "Computer", s2 = "Applications";
a = (s1.compareTo(s2));
b = (s1.equals(s2));
Answer
Data type of a is int and value is 2. Data type of b is boolean and value is false.
Explanation
compareTo() method compares two strings lexicographically and returns the
difference between the ASCII values of the first differing characters in the
strings. Thus, a will be of int data type and store the value 2 as the difference
between ASCII values of 'A' and 'C' is 2.
equals() method compares two String objects and returns true if the strings are
same, else it returns false. Thus, b will be of boolean data type and result
in false as both the strings are not equal.
Question 6
What do the following functions return for :
String x = "hello";
String y = "world";
(i) System.out.println(x + y);
(ii) System.out.println(x.length( ));
(iii) System.out.println(x.charAt(3));
(iv) System.out.println(x.equals(y));
Answer
(i) System.out.println(x + y);
Output
helloworld
Explanation
+ operator concatenates String objects x and y.
SHIVAM TRIPATHI
P a g e | 13
(ii) System.out.println(x.length( ));
Output
Explanation
length() returns the length of the String object. Since x has 5 characters, the
length of the string is 5.
(iii) System.out.println(x.charAt(3));
Output
Explanation
chatAt() returns the character at the given index. Index starts from 0 and
continues till length - 1. Thus, the character at index 3 is l.
(iv) System.out.println(x.equals(y));
Output
false
Explanation
equals() method checks for value equality, i.e., whether both objects have the
same value regardless of their memory location. As values of x and y are not the
same, so the method returns false.
Question 7
What will the following code output ?
String s = "malayalam" ;
System.out.println(s.indexOf('m'));
System.out.println(s.lastIndexOf('m'));
Answer
SHIVAM TRIPATHI
P a g e | 14
Output
0
8
Explanation
indexOf() returns the index of the first occurrence of the specified character
within the current String object. The first occurrence of 'm' is at index 0, thus 0 is
printed first.
lastIndexOf() returns the index of the last occurrence of the specified character
within the String object. The last occurrence of 'm' is at index 8, thus 8 is printed
next.
Question 8
If:
String x = "Computer";
String y = "Applications";
What do the following functions return?
(i) System.out.println(x.substring(1,5));
(ii) System.out.println(x.indexOf(x.charAt(4)));
(iii) System.out.println(y + x.substring(5));
(iv) System.out.println(x.equals(y));
Answer
(i) System.out.println(x.substring(1,5));
Output
ompu
Explanation
x.substring(1,5) will return a substring of x starting at index 1 till index 4 (i.e. 5 -
1 = 4).
SHIVAM TRIPATHI
P a g e | 15
(ii) System.out.println(x.indexOf(x.charAt(4)));
Output
Explanation
charAt() method returns the character at a given index in a String.
Thus, x.charAt(4) will return the character at the 4th index i.e., u. indexOf()
method returns the index of the first occurrence of a given character in a string.
Thus, it returns the index of u, which is 4.
(iii) System.out.println(y + x.substring(5));
Output
Applicationster
Explanation
x.substring(5) will return the substring of x starting at index 5 till the end of the
string. It is "ter". This is added to the end of string y and printed to the console as
output.
(iv) System.out.println(x.equals(y));
Output
false
Explanation
equals() method checks for value equality, i.e., whether both objects have the
same value regardless of their memory location. As the values of both x and y are
different so it returns false.
Question 9
State the method that:
(i) converts a string to a primitive float data type.
SHIVAM TRIPATHI
P a g e | 16
(ii) determines if the specified character is an uppercase character.
Answer
(i) Float.parseFloat()
(ii) Character.isUpperCase()
Question 10
What will be the output of the following code snippet when combined with
suitable declarations and run?
StringBuffer city = new StringBuffer("Madras");
StringBuffer string = new StringBuffer( );
string.append(new String(city));
string.insert(0, "Central ");
String.out.println(string);
Answer
The given snippet will generate an error in the statement —
String.out.println(string); as the correct statement for printing is —
System.out.println(string);. After this correction is done, the output will be as
follows:
Output
Central Madras
Explanation
Statement Remark
StringBuffer city = new It creates a StringBuffer objectcity which stores
StringBuffer("Madras"); "Madras".
StringBuffer string = new
It creates an empty StringBuffer object string.
StringBuffer( );
SHIVAM TRIPATHI
P a g e | 17
Statement Remark
It adds the value of city i.e. "Madras" at the end
string.append(new String(city)); of the StringBuffer object string. string = "
Madras".
It modifies StringBuffer object string and adds
string.insert(0, "Central "); "Central" at 0 index or beginning. Now, string
= "Central Madras".
System.out.println(string); It prints "Central Madras".
Question 11
What will be the output for the following program segment?
String s = new String ("abc");
System.out.println(s.toUpperCase( ));
Answer
Output
ABC
Explanation
String s stores "abc".
toUpperCase( ) method converts all of the characters in the String to upper case.
Thus, "abc" is converted to "ABC" and printed on the output screen.
Question 12
Give the output of the following program :
class MainString
{
public static void main(String[ ] args)
SHIVAM TRIPATHI
P a g e | 18
{
StringBuffer s = new StringBuffer("String");
if((s.length( ) > 5) &&
(s.append("Buffer").equals("X")))
; // empty statement
System.out.println(s);
}
}
Answer
Output
StringBuffer
Explanation
The expression s.length( ) > 5 will result in true because the length of
String s is 6 which is > 5.
In the expression s.append("Buffer".equals("X")), first the value of String s will
be modified from String to StringBuffer and then it will be compared to "X". The
result will be false as both the values are not equal.
Now, the condition of if statement can be solved as follows:
if((s.length( ) > 5) && (s.append("Buffer").equals("X")))
if(true && false)
if(false)
Thus, execution will move to the next statement following the if block —
System.out.println(s); which will print StringBuffer on the screen.
Question 13
Write a program to do the following :
(a) To output the question "Who is the inventor of Java" ?
(b) To accept an answer.
(c) To print out "Good" and then stop, if the answer is correct.
(d) To output the message "try again", if the answer is wrong.
SHIVAM TRIPATHI
P a g e | 19
(e) To display the correct answer when the answer is wrong even at the third
attempt and stop.
import java.util.Scanner;
public class KboatQuiz
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String q = "Who is the inventor of JAVA?";
String a = "James Gosling";
int i;
System.out.println(q);
for(i = 1; i <= 3; i++)
{
String ans = in.nextLine();
ans.trim();
if(ans.equalsIgnoreCase(a))
{
System.out.println("Good");
break;
}
else if(i < 3)
{
System.out.println("Try Again");
}
}
if(i == 4)
{
System.out.println("Correct Answer: " + a);
}
}
}
Output
SHIVAM TRIPATHI
P a g e | 20
SHIVAM TRIPATHI
P a g e | 21
Question 14
Write a program to extract a portion of a character string and print the extracted
string. Assume that m characters are extracted, starting with the nth character.
import java.util.Scanner;
public class KboatExtractSubstring
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter string : ");
String s = in.nextLine();
int len = s.length();
System.out.print("Enter start index : ");
int n = in.nextInt();
if(n < 0 || n >= len)
{
System.out.println("Invalid index");
System.exit(1);
SHIVAM TRIPATHI
P a g e | 22
System.out.print("Enter no. of characters to extract : ");
int m = in.nextInt();
int substrlen = n + m;
if( m <= 0 || substrlen > len)
{
System.out.println("Invalid no. of characters");
System.exit(1);
}
String substr = s.substring(n, substrlen);
System.out.println("Substring = " + substr);
}
}
Output
Question 15
Write a program, which will get text string and count all occurrences of a
particular word.
SHIVAM TRIPATHI
P a g e | 23
import java.util.Scanner;
public class KboatWordFrequency
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
System.out.println("Enter a word:");
String ipWord = in.nextLine();
str += " ";
String word = "";
int count = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
if (str.charAt(i) == ' ') {
if (word.equalsIgnoreCase(ipWord))
count++ ;
word = "";
}
else {
word += str.charAt(i);
}
}
if (count > 0) {
System.out.println(ipWord + " is present " + count + " times.");
}
else {
System.out.println(ipWord + " is not present in sentence.");
}
}
}
Output
SHIVAM TRIPATHI
P a g e | 24
Question 16
Write a program to accept a string. Convert the string to uppercase. Count and
output the number of double letter sequences that exist in the string.
Sample Input : "SHE WAS FEEDING THE LITTLE RABBIT WITH AN
APPLE"
Sample Output : 4
import java.util.Scanner;
public class KboatLetterSeq
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
String s = in.nextLine();
String str = s.toUpperCase();
int count = 0;
int len = str.length();
for (int i = 0; i < len - 1; i++) {
SHIVAM TRIPATHI
P a g e | 25
if (str.charAt(i) == str.charAt(i + 1))
count++;
}
System.out.println("Double Letter Sequence Count = " + count);
}
}
Output
Question 17
Design a class to overload a function check( ) as follows :
(i) void check(String str, char ch) - to find and print the frequency of a character
in a string.
Example:
Input :
str = "success" ch= 's'
Output :
number of s present is = 3
(ii) void check (String s1) - to display only vowels from string s1, after
converting it to lower case.
SHIVAM TRIPATHI
P a g e | 26
Example:
Input:
sl = "computer"
Output : o u e
public class KboatOverload
{
void check (String str , char ch ) {
int count = 0;
int len = str.length();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Frequency of " + ch + " = " + count);
}
void check(String s1) {
String s2 = s1.toLowerCase();
int len = s2.length();
System.out.println("Vowels:");
for (int i = 0; i < len; i++) {
char ch = s2.charAt(i);
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u')
System.out.print(ch + " ");
}
}
}
Output
SHIVAM TRIPATHI
P a g e | 27
SHIVAM TRIPATHI