0% found this document useful (0 votes)
185 views236 pages

Class 10 Computer App With BlueJ Notes

The document is a textbook solution for ICSE Computer Applications with Blue J, covering various topics in Object Oriented Programming and Java. It includes chapters on concepts such as classes, objects, data types, and methods, along with exercises and answers. The content is structured in a way to facilitate understanding of programming principles and practices.

Uploaded by

ircnautical
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
185 views236 pages

Class 10 Computer App With BlueJ Notes

The document is a textbook solution for ICSE Computer Applications with Blue J, covering various topics in Object Oriented Programming and Java. It includes chapters on concepts such as classes, objects, data types, and methods, along with exercises and answers. The content is structured in a way to facilitate understanding of programming principles and practices.

Uploaded by

ircnautical
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Textbook Solution

Understanding ICSE
Computer Applications with Blue J
Contents

Chapter 1: Revision of Class IX Syllabus 1


Part I: Introduction to Object Oriented Programming
Concepts 1
Part II: Elementary Concept of Objects and Classes 4
Part III: Values and Data Types 7
Part IV: Operators in Java 11
Part V(a): Introduction to Java 17
Part V(b): Input in Java 20
Part VI: Mathematical Library Methods 26
Part VII: Conditional Statements in Java 32
Part VIII: Iterative Constructs in Java 51
Part IX: Nested Loops 74

Chapter 2: Library Classes 90

Chapter 3: Arrays (Single Dimensional and


Double Dimensional) 104

Chapter 4: String Handling 125

Chapter 5: User Defined methods 151

Chapter 6: Class as the Basis of all Computation


(Objects and Classes) 175

Chapter 7: Constructors 199


Chapter 8: Encapsulation and Inheritance 217
Chapter 1 Revision of Class IX Syllabus
Part I
Introduction to Object Oriented Programming Concepts

III. Write Short Answers:


1. What is object oriented programming? Name two object oriented
programming languages.
Ans. Object Oriented Programming is an approach in which stress is laid on
data rather than functions. The data values remain associated with the
functions of a particular block of the program so as to encourage data
security. Two Object Oriented Programming languages are C++ and
Java.
2. Name four basic principles of object oriented programming.
Ans. The four basic principles of object oriented programming are:
(i) Encapsulation (ii) Abstraction
(iii) Inheritance (iv) Polymorphism
3. Why do we prefer object oriented approach in complex programming?
Explain.
Ans. We prefer object oriented approach in complex programming for the
following reasons:
(i) Data values are secured.
(ii) Mishandling of data is protected.
(iii) Error detection and correction becomes easier.
(iv) Easier in coding complex programs.
4. What is meant by a base class and a derived class?
Ans. The class that is inherited is known as base class and the class that inherits
from the base is known as derived class.
5. Mention two limitations of procedure oriented programming approach.
Ans. The two limitations of procedure oriented programming approach are:
(i) No restriction on data values.
(ii) No reusability concept hence time management, testing and length
of the program increases.
6. What is meant by encapsulation?
Ans. Wrapping of data and functions that operate on that data into a single
unit is called Encapsulation.
7. Define the following with an example each.
(a) Inheritance
(b) Polymorphism
Ans. (a) Inheritance: It is the property by vitue of which one class acquires
some features of the existing class or another class.

1
For example,
Suppose, 'Mensuration' is defined as the Base class along with
the derived classes 'Two Dimensional' and 'Three Dimensional' to
calculate parameters of different shapes (say, area or volume). Using
the property of inheritance, the components in the Base class can be
used to perform various tasks in the derived classes.
(b) Polymorphism: In object oriented programming, Polymorphism
provides the means to perform a single action in multiple ways.
For example,
The term 'cell' in Physics refers to a device that supplies current to the
electrical circuits. In Biology, it means a fundamental and functional
part of human body/plant. The same term is also referred to a small
room such as Administrative Cell, Examination Cell, etc.
8. In what way is Data Hiding related to Data Abstraction?
Ans. Data Abstraction focuses on the observable behaviour of an object,
whereas Data Hiding focuses upon the implementation that gives rise
to this behaviour. In other words, Data Abstraction cares about what
something does but not concerned about how it does. Whereas, data
hiding cares about how something does such that others do not have to
worry about the implementations. Hence, we can say that Encapsulation
is a way to implement Data Abstraction.
9. Give an example to explain Data Abstraction.
Ans. When you drive a car, you use steering wheel, accelerator, clutch, brake,
etc.
You are not concerned about how they are designed to do their functions.
Similarly, in object oriented programming, only the essential information
about the data is known to the outside world.
10. What is meant by Data Hiding?
Ans. Data Hiding means restricting direct access to the implementation details
of an object and providing a well-defined interface through methods to
use the functionality of the object.
11. Give two differences between Data Hiding and Encapsulation.
Ans. The differences between data hiding and encapsulation are:
(i) Data hiding focuses more on data security whereas, encapsulation
focuses more on hiding the complexity of the system.
(ii) Data hiding focuses on restricting the use of data whereas,
encapsulation deals with wrapping of data and functions.
12. 'Encapsulation reduces the complexity and makes the system easier'.
Explain this statement with a real world example.
Ans. Encapsulation means wrapping of data and methods into a single unit
that can be used together in a specific task.
Let us take the example of an ATM machine. To withdraw money from
an ATM machine, we insert the ATM card and thereafter enter the PIN
and the amount that we want to withdraw. The ATM machine then
processes our request and finally we receive money.

2
In this context, money refers to as the data and the various processes of
verification (pin, balance in the account) are the methods. The data and
methods are encapsulated in the ATM (treated as a class). Since, the user
does not have to understand the actual working of the ATM machine,
so encapsulation reduces the complexity and makes the system (ATM
machine) easier to use.
13. Give two differences between Procedure Oriented languages and Object
Oriented languages.
Ans. Differences between Procedure Oriented languages and Object Oriented
languages are:
(i) In POP, the programs are divided into functions. Whereas in OOP,
the programs are divided into objects.
(ii) POP does not support the property of inheritance. Whereas, OOP
supports inheritance.
14. Which of the Object Oriented programming principles explain the
following illustrations? Justify.
(a) The variables and methods are put together in a Class.
(b) Withdrawing money from ATM
Ans. (a) Encapsulation
Wrapping of data and functions of an object as a unit that can be
used together in a specific operation is known as Encapsulation. In
the picture, the variables and methods are being encapsulated in a
class.
(b) Data Abstraction
Here, the user knows the essential features of the ATM machine
without knowing the background details to get cash from the
machine as per his/her need.

Introduction to Object Oriented Programming Concepts 3


Chapter 1 Revision of Class IX Syllabus
Part II
Elementary Concept of Objects and Classes

III. Answer the following questions:


1. How will you define a software object?
Ans. A software object replaces the characteristics and behaviour of a real
world object with data members and member methods, respectively.
2. Define class and object with an example.
Ans. An object is an entity which possesses specific characteristics and
common behaviour. Whereas, class is a blueprint or a template that
describes the characteristics and behaviour of similar types of objects.
Let us take the example of a house (class). An architect makes the
blueprint for a house which explains exactly what properties each
individual building (object) will have when constructed. In other words,
we can say that looking at the blueprint, the builders make a physical
building. Moreover, the same blueprint can be used to make as many
buildings as they want. Each building will have the same layout and
properties. However, each building may have different characteristics
(known as object) but they share the common behaviour (people living
in the building).
3. What does the following statement mean?
Employee staff = new Employee( );
Ans. This statement creates a new object of class Employee. The newly created
object will now implicitly possess the characteristics and behaviour
described within the class.
4. A class is also referred to as 'Object Factory'. Comment.
Ans. A class has the complete description of the data elements to create similar
types of objects that will possess different characteristics and common
behaviour. A class is just like a factory where it can produce similar items
(objects) based on a particular design. Hence, class is also referred to as
'Object Factory'.
5. Why is a class known as composite data type?
Ans. When the user creates a class, it becomes a data type for his/her program.
Thus, class is referred to as a user defined data type. This data type
includes different primitive types such as int, float, char, etc. Hence, it
is also said to be composite data type.
6. A statement is given as:
'Study_Table' is an object of the class 'Furniture'.
Write down Java statement for the same.
Ans. Furniture Study_Table = new Furniture( );

4
7. Class and Objects are inter-related. Explain.
Ans. A class is used to create various objects that have different characteristics
and common behaviour. Each object follows all the features defined
within a class. That is why class is also referred to as a blueprint or
prototype of an object. This way we can say that they are inter-related.
8. Why is an Object called an 'Instance' of a class? Explain.
Ans. The data members declared within a class are also known as instance
variables. When an object of a class is created, it includes instance
variable described within the class. This is the reason why an object is
called as an instance of a class.
9. Write a statement to create an object 'Keyboard' of the class 'Computer'.
Ans. Computer Keyboard = new Computer( );
10. Write a difference between class and object.
Ans. Class is a blueprint or prototype of an object. Whereas, an object is a
unique entity having some characteristics and behaviour.
11. Mention three characteristics and two methods for the following Classes:
(a) class Mobile_Phone
Ans. Characteristics Methods
colour makecall( )
model receivecall( )
company

(b) class Bike


Ans. Characteristics Methods
colour input( )
model display( )
Reg_Number

(c) class Fruits


Ans. Characteristics Methods
name input()
quantity output()
cost

(d) class Pen


Ans. Characteristics Methods
name input( )
type display( )
company

Elementary Concept of Objects and Classes 5


12. Design a program in Java to calculate the discount given to a customer
on purchasing LED Television. The program also displays the amount
paid by the customer after discount. The details are given as:
Class name : Television
Data members : int cost, int discount, int amount
Member functions:
Accept( ) : to input the cost of Television
Calculate( ) : to calculate the discount
Display( ) : to show the discount and the amount paid after
discount
Ans. class Television
{
int cost, discount, amount;
void Accept( )
{
// Input the cost of Television
……………………………….
}
void Calculate( )
{
//Calculate the discount
…………………………………..
}
void Display( )
{
//Show the discount and the amount to be paid after discount
…………………………………….
}
}

6
Chapter 1 Revision of Class IX Syllabus
Part III
Values and Data Types

III. Write short answers:


1. What is meant by data type? Name two types of data type.
Ans. Data types are used to identify the type of data a memory location can
hold and also to handle the associated operations. Data Types are of two
types:
• Primitive Data Types • Non-Primitive Data Types
2. Why is it necessary to define data type in Java programming?
Ans. Whenever, we need to store a value, the respective data type must be
mentioned so that the system may structure the memory location for its
proper storage. It also helps in preventing errors during compilation.
3. Define the following with an example:
Ans. (a) variable
A variable represents a memory location through a symbolic name
which holds a value of a particular data type. The name of variable
is used in the program to refer to the stored value.
For example, int num;
Here, the variable num can hold an integer value.
(b) constant
The term 'constant' refers to as the fixed value which can't be changed
in the program.
For example, int m = 30;
(c) boolean data type
A boolean data type is used to store one of the two boolean values
i.e., true or false. For example, boolean p = false;
(d) coercion
In a mixed-mode expression, when the data type of the result gets
converted into its higher most data type available in the expression
without any intervention by the user is known as Coercion.
For example, int a = 425;
double b = 52500.45;
double res = a + b;
(e) primitive data type
Primitive data types are the basic or fundamental data types used
to declare a variable.
For example, int, long, float, double, char, etc.
(f) non-primitive data type
A non-primitive data type is one that is derived from primitive
data types. A number of primitive data types are used together to
represent a non-primitive data type.
For example, array

7
4. What is a token? Name different types of tokens.
Ans. A token is the smallest element of a program that is meaningful to the
compiler. The different types of tokens in Java are:
• Identifiers
• Literals
• Operators
• Separators
• Keywords
5. Explain the term 'type casting'.
Ans. In a mixed mode expression, the process of converting of pre-defined
type into a specific type as per the user's choice is known as type casting.
6. Assign the following to a variable with suitable data type.
Ans. (a) m = 22 / 7
double m = (22.0 / 7.0);
(b) p= 1.4142135 (value of square root of 2)
double p = 1.4142135;
(c) k= 0.00004545
double k = 0.00004545;
(d) n=24.50
float n = 24.50;
7. Distinguish between:
Ans. (a) Token and Identifier
Token Identifier
A token is the smallest element Identifier is used to name a block
of a program that is meaningful of statements by which they are
to the compiler. identified in a Java program.
(b) Character and Boolean literal
Character literal Boolean literal
Character literal is a single letter, A boolean literal can take only
a digit or any special symbol one of the two boolean values
enclosed within a pair of single represented by the words true
quotes. or false.

8. Explain the term type conversion. How is implicit conversion different


from explicit conversion?
Ans. The process of converting from one data type to another data type is
called type conversion. In an implicit conversion, the result of a mixed
mode expression is obtained in the higher most data type of the variables
without any intervention by the user. Whereas, the explicit conversion
is performed with the user's intervention.
For example:
int a = 10;
float b = 25.5, c;
c = a + b;
Here, the resultant data type will be of float type (by default).

8
In case of explicit type conversion, the data gets converted to a type as
specified by the programmer.
For example:
int a = 10;
double b = 25.5;
int c = (int)(a + b);
Here, the resultant data type will be of int type.
9. Classify the following as primitive or non-primitive data types.
Ans. (a) char : primitive
(b) arrays : non-primitive
(c) int : primitive
(d) classes : non-primitive
10. In what way is static initialisation of data type different from dynamic
initialisation?
Ans. In static initialisation, the initial value of the variable is provided as a
literal at the time of declaration.
For example:
int score = 99;
double p = 3.412;
char ch = 'A';
Dynamic initialisation is used to initialise a variable at runtime. In this
system, the variable is initialised with the value which is the outcome
of some expression or a function.
For example:
double x = 3.14, y = 5.4042;
double z = x + y;
11. Predict the return data type of 'r' and 'n' from the snippet:
int p; float m;
r = p+m;
n = m/3*([Link](4,3));
[Link](r);
[Link](n);
Ans. Return data type of r is float and n is double.
12. Give reason whether the following assignments are correct or not.
Ans. (a) int m =155;
It is correct as 155 is an integer and assigned to an int variable m.
(b) float f = 0.002654132;
It is incorrect as data type of 0.002654132 is double but it is assigned
to a float variable.
(c) String str = 'Computer';
It is incorrect as the String literal 'Computer' is enclosed in single
quotes. It should be in double quotes.
(d) boolean p = false;
It is correct as false is a valid boolean literal and it is assigned to a
boolean variable.

Values and Data Types 9


(e) String b = "true";
It is correct as "true" is a string literal not a boolean literal. It is
enclosed in double quotes. So, it is correctly assigned to a String
variable.
(f) char ch = "apps";
It is incorrect as "apps" is a string literal not a character literal and
it is assigned to a variable ch of char data type.
(g) String st= "Application";
It is correct as "Application" is a string literal and it is correctly
assigned to a String variable.
(h) double n = 455.29044125;
It is correct as 455.29044125 is a literal of double data type and it is
correctly assigned to a double variable.

10
Chapter 1 Revision of Class IX Syllabus
Part IV
Operators in Java

V. Answer the following questions:


1. What is an operator? What are the three main types of operators? Name
them.
Ans. An operator is a symbol or sign used to specify an operation to be
performed in Java programming. The three main types of operators are
Arithmetical, Logical and Relational.
2. How is Java expression different from statement?
Ans. An expression is a set of variables, constants and operators i.e. an
expression is a combination of operators and operands. When an
expression is assigned to a variable, the complete set is referred to as a
statement.
3. Explain the following with one example each.
Ans. (a) Arithmetic operator
Arithmetic operators are used to perform mathematical operations
on the operands. The operands of arithmetic operators must be of
numeric type. The arithmetical operators are further categorised
into Unary, Binary and Ternary.
For example:
int a = 10 + 20;
Here, the addition arithmetic operator is represented by the symbol
‘+’ which will add 10 and 20. So, the variable a will result in 30.
(b) Relational operator
Relational operators are used to determine the relationship between
the operands. The relational operators compare the operands to
check if the operands are equal to (==), not equal to (!=), less than
(<), less than equal to (<=), etc. each other. The result of an operation
involving relation operators results in a boolean value (true or false).
For example:
int a = 8;
int b = 10;
boolean c = a < b;
Here, as a is less than b. So, the result of a < b is true and boolean
variable c becomes true.
(c) Logical operator
Logical operators operate on boolean expressions to combine the
results of the boolean expression into a single boolean value (true
or false).
For example:
int a = 7;

11
int b = 10;
boolean c = (a < b) && (a % 2) == 0;
Here, the result of first boolean expression (a < b) is true but the result
of second boolean expression (a % 2) is false. So, the final value of
the boolean variable c results in false.
(d) Ternary operator
Ternary operator operates on three operands.
Syntax: (test condition) ? expression 1 : expression 2
If the condition is true then the result of ternary operator is the value
of expression 1. Otherwise, the result is the value of expression 2.
For example:
sale=25000;
comm= (sale>15000)? sale*5/100:0;
Here, the ternary operator checks, if the value of variable is more than
15000 then expression 1 is true, i.e., comm = 5% of sale. Otherwise,
it will result in comm=0.
4. Distinguish between:
Ans. (a) Unary & Binary arithmetic operator
Unary Arithmetic Operator Binary Arithmetic Operator
It operates on a single operand. It operates on two operands.
For example: For example:
Increment (++) and Decrement Multiplication (*) and Division
(--) (/)

(b) Postfix increment and Prefix increment


Postfix Increment Prefix Increment
It works on the principle of USE- It works on the principle of
THEN-CHANGE. CHANGE-THEN-USE.
The increment operator (++) is The increment operator (++) is
written after the operand. written before the operand.

(c) Postfix decrement and Prefix decrement


Postfix Decrement Prefix Decrement
It works on the principle of USE- It works on the principle of
THEN-CHANGE. CHANGE-THEN-USE.
The decrement operator (--) is The decrement operator (--) is
written after the operand. written before the operand.

(d) (p!= q) and !(p == q)


(p != q) !(p == q)
This expression uses the It is a logical NOT (!) operator
relational operator != (Not equal used with a conditional operand
to) to determine, if values of p that reverses the result.
and q are different.

12
5. What is the difference between:
(a) / and % operator?
Ans. / %
It is a division operator. It is a modulus operator.
It returns the quotient of division It returns the remainder of division
operation. operation.
(b) = and == ?
Ans. = ==
It is the assignment operator used It is the equality operator used
for assigning a value to a variable. to check, if a variable is equal to
For example: int m = 45; another value/variable or not.
For example: if (m == 45)

6. What will be the output of the following code?


(a) int k=5, j=9;
k+= k++ – ++j + k;
[Link]("k="+k);
[Link]("j="+j);
Solution:
k+= k++ – ++j + k
⇒ k = k + (k++ – ++j + k)
⇒ k = 5 + (5 – 10 + 6)
⇒k=5+1
⇒k=6
Output:
k=6
j=10
(b) If int y =10 then find int z = (++y*(y+++5));
Solution:
z = (++y*(y+++5))
⇒ z = (11 * (11 + 5))
⇒ z = (11 * 16)
⇒ z = 176
Output:
z = 176
(c) Give the output of the following expression:
a+= a++ + ++a + – –a + a– –; when a = 7
Solution:
a+= a++ + ++a + – –a + a– –
⇒ a = a + (a++ + ++a + – –a + a– –)
⇒ a = 7 + (7 + 9 + 8 + 8)
⇒ a = 7 + 32
⇒ a = 39
Output:
a = 39
(d) What is the value of y after the execution?
y+= ++y + y– – + – –y; when int y=8

Operators in Java 13
Solution:
y+= ++y + y– – + – –y
⇒ y = y + (++y + y– – + – –y)
⇒ y = 8 + (9 + 9 + 7)
⇒ y = 8 + 25
⇒ y = 33
Output:
y = 33
(e) Evaluate the following if the value of x=7, y=5:
x+=x++ + x + ++y
Solution:
x+=x++ + x + ++y
⇒ x = x + (x++ + x + ++y)
⇒ x = 7 + (7 + 8 + 6)
⇒ x = 7 + 21
⇒ x = 28
Output:
x = 28
(f) Give the output of the following:
(i) int x=2, y=4, z=l;
int result= (++z) + y+ (++x) + (z++);
Solution:
result = (++z) + y + (++x) +(z++)
= (2) + 4+ (3) +(2)
= 11
Output:
result = 11
(ii) int f= 10, m=9;
String e=(m%f==9)? "YES": "NO";
[Link]. print(e);
Output:
YES
7. Rewrite the following program segment using if-else statements instead
of the ternary operator.
Ans. (a) String grade = (marks>=90)?"A": (marks>=80)? "B": "C";
String grade;
if (marks >= 90)
grade = "A";
else if (marks >= 80)
grade = "B";
else
grade = "C";
(b) commission = (sale > 5000)? sale*10/100: 0;
if (sale > 5000)
commission = sale * 10 / 100;
else
commission = 0;
(c) net = (salary > 10000)? salary – (8.33/100)*salary : salary –
(5/100)*salary

14
if (salary > 10000)
net = salary – (8.33/100) * salary;
else
net = salary – (5/100) * salary;
(d) s = (a + b < c || a + c <= b || b + c <= a)? "Triangle is not possible":
"Triangle is possible";
if (a + b < c || a + c <= b || b + c <= a)
s = "Triangle is not possible";
else
s = "Triangle is possible";
(e) c = (x >= 'A' && x<= 'Z')? "Uppercase Letter": "Lowercase Letter";
if (x >= 'A' && x <= 'Z')
c = "Uppercase Letter";
else
c = "Lowercase Letter";
8. Rewrite the following program segment using logical operators:
if (x > 5)
if (x > y)
[Link] (x+y);
Ans. if ((x > 5) && (x > y))
[Link] (x+y);
9. Rewrite the following using ternary operator.
Ans. (a) if (x % 2 == 0)
[Link]("Even");
else
[Link]("Odd");
[Link](x % 2 == 0? "Even": "Odd");
(b) if (bill > 10000)
discount=bill*10.0/100;
else
discount=bill*5.0/100;
discount = bill > 10000? bill*10.0/100: bill*5.0/100;
(c) if(income < 10000)
tax = 0;
else
tax = 12;
tax = income < 10000? 0: 12;
(d) if(a > b)
{
if (a > c)
g = a;
else
g = c;
}
else if (b > c)
g = b;

Operators in Java 15
else
g = c;
g = a > b? a > c? a: c: b > c? b: c;
(e) if (p >= 4750)
k = p * 5 / 100;
else
k = p * 10 / 100;
k = (p >= 4750)? p * 5 / 100: p * 10 / 100;
(f) if(n1>n2)
r = true;
else
r = false;
r = (n1>n2)? true: false;

16
Chapter 1 Revision of Class IX Syllabus
Part V(a)
Introduction to Java

IV. Write short answers:


1. What is meant by a package? Give an example.
Ans. Package is a collection of classes such that each class includes different
built-in functions. For example: [Link]
2. Name a Java package which is imported by default.
Ans. [Link]
3. Write a package that is used for input/output operations in Java.
Ans. [Link] is used for input/output operations in Java.
4. Explain the significance of the following Java library packages.
Ans. (a) [Link]
It is one of the built-in packages in Java that contains classes and
interfaces of the Java programming language. The lang package
contains classes such as Boolean, Integer (primitive data type), Math
(exponential, logarithm, square root), etc. which are considered the
building blocks of a Java program.
(b) [Link]
It contains the classes that helps the user to perform all the input-
output operations. These streams also support all data types,
characters, files, etc. to fully execute the I/O operations.
(c) [Link]
It contains the classes which provides various mathematical methods
to work on math calculations. Some of them include min( ), max( ),
avg( ), round( ), sin( ), cos( ), tan( ), etc.
5. (a) Java interpreter is called Java Virtual machine. Explain.
Ans. Java Virtual Machine takes Byte code as input and converts it into
Machine Code one line at a time. This Byte code can be generated by
compiling source code written in any JVM language like Scala, Kotlin,
etc. not just Java. Hence, Java interpreter is called Java Virtual Machine.
(b) Name two ways of writing Java programs.
Ans. Two ways of writing Java programs are:
• Java Application
• Java Applet
6. Define the terms:
Ans. (a) Source code: A set of statements written in a high level programming
language like Java, C++, Python, etc. is called as source code.
(b) Machine code: Machine code is a low level programming language.
In machine code, the instructions are written as a sequence of 0s and
1s. It is directly understood and executed by the processor.

17
(c) Byte code: Java compiler converts Java source code into an
intermediate binary code called Byte code. This Byte code can't be
executed directly by the processor. It needs to be converted into
machine code for its execution.
7. What is BlueJ? What are the features of BlueJ?
Ans. BlueJ is an integrated development environment (IDE) for the Java
programming language. It is a Windows based application for Java. It
uses compiler as well as interpreter to convert source code into machine
code.
Features of BlueJ:
• It uses a menu driven approach to carry out various tasks.
• It supports graphical user interface.
• It facilitates easier debugging.
8. Write down the syntax of output statement in Java with an example.
Ans. We commonly use two output statements in Java.
(i) Syntax: [Link](<output value>);
This statement displays the values on the output screen. After
printing the value, it places the cursor at the start of the next line.
So the next printing happens at the start of the next line.
For example:
int a =10, b = 15;
[Link](a);
[Link](b);
Output:
10
15
(ii) Syntax: [Link](<output message>);
This statement also prints data on the output screen but on the same
line. After printing the value, the cursor remains on the same line at
the end of the printed value. So the next printing starts in the same
line just after the end of the previous printed value.
For example:
[Link]("JVM stands for");
[Link]("Java ");
[Link]("Virtual ");
[Link]("Machine");
Output:
JVM stands for Java Virtual Machine
9. What is meant by Java reserved words? Name five Java reserved words
which are commonly used in Java programming.
Ans. In Java, a reserved word is a word that has a pre-defined meaning in the
language. Moreover, the reserved words cannot be used as names for
variables, methods, classes or any other identifier. The reserved words
are also known as keywords.
Five commonly used Java reserved words are public, class, int, double,
char.

18
10. Differentiate between the output statements [Link]( ) and
[Link]( ).
Ans. The differences are:
[Link]( ) [Link]( )
It displays the output of the It displays the output of the
program and the cursor moves to program but the cursor remains at
the next line. the end of the data in the same line.
Next printing takes place from the Next printing takes place from the
next line. same line.

11. A Java program uses a Compiler as well as an Interpreter. Explain.


Ans. Java compiler compiles Java source code to Byte code. The Byte code
can not run on the processor directly as the processor only understands
Machine Code. This task is performed by Java Virtual Machine (JVM)
which takes this Byte code as input and converts it into Machine Code
line by line. So, JVM acts as an interpreter for converting Byte code to
Machine Code. In this way, a Java program uses both a compiler as well
as an interpreter.

Introduction to Java 19
Chapter 1 Revision of Class IX Syllabus
Part V(b)
Input in Java

III. Explain the following functions:


1. [Link]([Link]( ));
Ans. This is an input function of the InputStreamReader class that accepts an
integer value at the time of execution.
2. (char)([Link]( ));
Ans. This is an input function of the InputStreamReader class that accepts a
character at the time of execution.
3. next( );
Ans. The next( ) function is an input function of the Scanner class that accepts
a word at the time of execution.
4. public static void main(int b);
Ans. This is one of the methods to accept an integer value from the user at
the time of execution to the main( ) function using function argument.
5. nextLine( );
Ans. The nextLine( ) function is an input function of the Scanner class that
accepts a string including spaces at the time of execution.
IV. Answer the following:
1. What are the different ways to give input in a Java program?
Ans. Java provides the following ways to give input in a program:
• Using Function Argument
• Using InputStreamReader class
• Using Scanner class
• Using Command Line Arguments
2. What is the use of the keyword 'import' in Java programming?
Ans. The keyword 'import' is used to import built-in and user-defined
packages into our Java programs.
For example: import [Link].*;
It will provide the facility to avail the Scanner class to perform various
tasks in Java programming.
3. What is a Run Time error? Explain with an example.
Ans. The errors that occur during the execution of the program primarily due
to the state of the program which can only be resolved at run time are
called Run Time errors.
Refer the following code:
import [Link].*;
class Sample
{
public static void main(String args[])
{

20
Scanner in = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]( );
double ans = [Link](n);
[Link]("Result = " + ans);
}
}
The above program will work for all positive values of n, entered by
the user. When the user enters a negative number, a run time error will
occur. As we know that the square root of a negative number cannot be
determined. So, it is a run time error.
4. What are the different types of errors that take place during the execution
of a program? Name them.
Ans. Logical errors, Syntax errors and Runtime errors occur during the
execution of the program.
5. Give two differences between Syntax error and Logical error.
Ans. The differences are:
Syntax Error Logical Error
Syntax errors occur when we Logical errors occur due to our
violate the rules of writing the mistakes in the programming logic.
statements of the programming
language.
Program is unable to compile and Program compiles and executes but
execute. does not give the desired output.

V. Unsolved Java Programs:


Q.1 In an election, there are two candidates X and Y. On the election day,
80% of the voters go for polling, out of which 60% vote for X. Write a
program to take the number of voters as input and calculate:
• number of votes received by X
•number of votes received by Y
Prog. import [Link].*;
public class Polling
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
long tvoters, voters, xvoters, yvoters;
[Link]("Enter the number of voters: ");
tvoters = [Link]( );
voters = [Link](0.8 * tvoters);
xvoters = [Link](0.6 * voters);
yvoters = voters – xvoters;
[Link]("Total Votes: " + tvoters);
[Link]("Votes received by X: " + xvoters);
[Link]("Votes received by Y: " + yvoters);
}
}

Input in Java 21
Q.2 A shopkeeper offers 10% discount on the printed price of a mobile phone.
However, a customer has to pay 9% GST on the remaining amount. Write
a program in Java to calculate the amount to be paid by the customer
taking printed price as an input.
Prog. import [Link].*;
public class Phone
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
double mp, dis, gst, price;
[Link]("Enter the Marked Price: ");
mp = [Link]( );
dis = mp*0.1;
price = mp–dis;
gst = price*0.09;
[Link]("Price after 10% discount and 9% GST: " +
(price+gst));
}
}
Q.3 Write a program to input time in seconds. Display the time after
converting it into hours, minutes and seconds.
Sample Input: Time in seconds: 5420
Sample Output: 1 Hour 30 Minutes 20 Seconds
Prog. import [Link].*;
public class Time
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int time, hrs, min, sec;
[Link]("Time in seconds: ");
time = [Link]( );
hrs = time / 3600;
min = (time % 3600)/60;
sec = (time % 3600) % 60;
[Link](hrs+" Hour "+min+" Minutes " +sec+" Seconds");
}
}
Q.4 The driver took a drive to a town 240 km at a speed of 60 km/h. Later in
the evening, he drove back at 20 km/h less than the usual speed. Write
a program to calculate:
• the total time taken by the driver
• the average speed during the whole journey
[Hint: average speed = total distance / total time]

22
Prog. public class Journey
{
public static void main(String args[])
{
int dist = 240, speed = 60, rspeed = speed – 20;
float time_reach, time_return, total_time, avg_speed;
time_reach = dist / speed;
time_return = dist / rspeed;
total_time = time_reach + time_return;
avg_speed = (dist * 2) / total_time;
[Link]("Total time: " + total_time);
[Link]("Average speed: " + avg_speed);
}
}
Q.5 Write a program to input two unequal numbers. Display the numbers
after swapping their values in the variables without using a third
variable.
Sample Input: a = 76, b = 65
Sample Output: a = 65, b = 76
Prog. import [Link].*;
public class Swap
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int num1, num2;
[Link]("Enter two unequal numbers:");
[Link]("Enter first number: ");
num1 = [Link]( );
[Link]("Enter second number: ");
num2 = [Link]( );
if (num1 == num2)
[Link]("Invalid Input! Numbers are equal.");
else
{
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2;
}
[Link]("After swapping first number: " + num1);
[Link]("After swapping second number: " + num2);
}
}
Q.6 A certain amount of money is invested for 3 years at the rate of 6%, 8%
and 10% per annum compounded annually. Write a program to calculate:
• the amount after 3 years.
• the compound interest after 3 years.
Accept certain amount of money (Principal) as an input.
[Hint: A = P * (1 + (R1 / 100))T * (1 + (R2 / 100))T * (1 + (R3 / 100))T and
CI = A – P]

Input in Java 23
Prog. import [Link].*;
public class Interest
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int p, r1=6, r2=8, r3=10;
double amt, ci;
[Link]("Enter the principal: ");
p = [Link]( );
amt = p*(1+(r1/100))*(1+(r2/100))*(1+(r3/100));
ci = amt – p;
[Link]("Amount after 3 years: " + amt);
[Link]("Compound Interest: " + ci);
}
}
Q.7 The co-ordinates of two points A and B on a straight line are given as
(x1, y1) and (x2, y2). Write a program to calculate the slope (m) of the
line by using formula:
Slope = (y2 – y1) / (x2 – x1)
Take the co-ordinates (x1, y1) and (x2, y2) as input.
Prog. import [Link].*;
public class Slope
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int x1, y1, x2, y2;
float slope;
[Link]("Enter x coordinate of point A: ");
x1 = [Link]( );
[Link]("Enter y coordinate of point A: ");
y1 = [Link]( );
[Link]("Enter x coordinate of point B: ");
x2 = [Link]( );
[Link]("Enter y coordinate of point B: ");
y2 = [Link]( );
slope = (y2 – y1) / (x2 – x1);
[Link]("Slope of line: " + slope);
}
}
Q.8 A dealer allows his customers a discount of 25% and still gains 25%.
Write a program to input the cost of an article and display its selling
price and marked price.
Sample Input: 600
Sample Output: Selling Price = 750
Marked Price = 1000

24
Prog. import [Link].*;
public class MP_SP
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int cp, dis = 25, pp = 25;
double sp, mp;
[Link]("Enter cost price: ");
cp = [Link]( );
sp = ((100 + pp)/100.0)*cp;
mp = (100.0/(100 – dis))*sp;
[Link]("Selling Price: " + sp);
[Link]("Marked Price: " + mp);
}
}

Input in Java 25
Chapter 1 Revision of Class IX Syllabus
Part VI
Mathematical Library Methods

V. Explain the following functions:


1. [Link]( )
Ans. It returns a positive double value, greater than or equal to 0.0 and less
than 1.0.
2. [Link]( )
Ans. It returns the value of the first argument raised to the power of the second
argument. The return type of this method is double.
3. [Link]( )
Ans. It returns the cube root of its argument as a double type value.
4. [Link]( )
Ans. It returns the natural logarithm of its argument. It always returns a
double data type value.
VI. Distinguish between:
1. [Link]( ) and [Link]( )
[Link]( ) [Link]( )
It returns the next higher double It returns the lower double type
type value, greater than or equal value, less than or equal to the
to the argument. argument.
double a = [Link](65.5); double b = [Link](65.5);
Output: 66.0 Output: 65.0

2. [Link]( ) and [Link]( )


[Link]( ) [Link]( )
This function returns the nearest It rounds off its argument to the
integer of a given fractional nearest integer and returns its
number. The return data type will value as long type, irrespective of
always be double. its argument (int, float or double).
double a = [Link](1.5); long a = [Link](1.5);
double b =[Link](2.5); long b = [Link](2.5);
Both will result in a value of 2.0 The first will have a value of 2 and
second will have a value of 3.

VII. Unsolved Java Programs:


Q.1 Write a program to calculate the value of the given expression:
1/a2 + 2/b2 + 3/c2
Take the values of a, b and c as input from the console. Finally, display
the result of the expression to its nearest whole number.

26
Prog. import [Link].*;
public class Expression
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int a, b, c;
double ans;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of b: ");
b = [Link]( );
[Link]("Enter the value of c: ");
c = [Link]( );
ans = (1/[Link](a,2)) + (2/[Link](b,2)) +
(3/[Link](c,2));
long round_ans = [Link](ans);
[Link]("Result rounded to whole number: " + round_ans);
}
}
Q.2 For every natural number m>1; 2m, m2–1 and m2+1 form a Pythagorean
triplet.
Write a program to input the value of 'm' through console to display a
'Pythagorean Triplet'.
Sample Input: 3
Then 2m=6, m2–1=8 and m2+1=10
Thus 6, 8, 10 form a 'Pythagorean Triplet'.
Prog. import [Link].*;
public class PTriplet
{
public static void main(String args[])
{
int m, f_Triplet, s_Triplet, th_Triplet;
Scanner in = new Scanner([Link]);
[Link]("Enter the value of m: ");
m = [Link]( );
if (m < 2)
{
[Link]("Invalid Input! m should be greater than 1");
}
else
{
f_Triplet = 2 * m;
s_Triplet = (int)([Link](m,2)–1);
th_Triplet = (int)([Link](m,2)+1);
[Link]("Pythagorean Triplets are:");
[Link]("First Triplet: "+f_Triplet);
[Link]("Second Triplet: "+s_Triplet);

Mathematical Library Methods 27


[Link]("Third Triplet: "+th_Triplet);
}
}
}
Q.3 Write a program to input a number. Calculate its square root and cube
root. Finally, display the result by rounding it off.
Sample Input: 5
Square root of 5= 2.2360679
Rounded form= 2
Cube root of 5 = 1.7099759
Rounded form= 2
Prog. import [Link].*;
public class Roots
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int num;
double sqrt_val, cbrt_val;
long rd_sqrt, rd_cbrt;
[Link]("Enter a number: ");
num = [Link]( );
sqrt_val = [Link](num);
cbrt_val = [Link](num);
rd_sqrt = [Link](sqrt_val);
rd_cbrt = [Link](cbrt_val);
[Link]("Square root of " + num + " = " + sqrt_val);
[Link]("Rounded form = " + rd_sqrt);
[Link]("Cube root of " + num + " = " + cbrt_val);
[Link]("Rounded form = " + rd_cbrt);
}
}
Q.4 The volume of a sphere is calculated by using formula:
4 22
v = * *r3
3 7
Write a program to calculate the radius of a sphere by taking its volume
as
 an input. 3 7
Hint: radius = 3 volume * *
 4 22
Prog. import [Link].*;
public class Sphere
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter volume of sphere: ");
double v = [Link]( );
double r = [Link](v * (3/4.0)*(7/22.0));

28
[Link]("Radius of sphere = " + r);
}
}
Q.5 A trigonometrical expression is given as:
tan A–tan B
1+tanA*tanB
Write a program to calculate the value of the given expression by taking
the values of angles A and B (in degrees) as input.
 22
Hint: radian= *degree
7*180
Prog. import [Link].*;
public class Trigono_Exp
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
double ang_A, ang_B, ang_Arad, ang_Brad, num, denom, exp;
[Link]("Enter angle A in degrees: ");
ang_A = [Link]( );
[Link]("Enter angle B in degrees: ");
ang_B = [Link]( );
ang_Arad = (22 * ang_A)/(7*180);
ang_Brad = (22 * ang_B)/(7*180);
num = [Link](ang_Arad) – [Link](ang_Brad);
denom = 1 + [Link](ang_Arad) * [Link](ang_Brad);
exp = num/denom;
[Link]("Value of expression = " + exp);
}
}
Q.6 The standard form of quadratic equation is represented as:
ax2 + bx + c = 0
where d = b2 – 4ac, known as ‘Discriminant’ of the equation.
Write a program to input the values of a, b and c. Calculate the value of
discriminant and display the output.
Prog. import [Link].*;
public class Quadratic
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int a, b, c;
double d;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of b: ");
b = [Link]( );
[Link]("Enter the value of c: ");

Mathematical Library Methods 29


c = [Link]( );
d = [Link](b,2)–(4*a*c);
[Link]("Discriminant = "+d);
}
}
Q.7 The sum of first n odd natural numbers can be calculated as n 2, where
n is the number of odd natural terms.
For example,
Sum= 1+ 3 + 5 + 7; number of odd natural terms = 4
Therefore, Sum= 42=16
Write a program to input number of odd natural terms and display the
sum of the given series:
(a) 1 + 3 + 5 +...................................................+ 29 + 31
Prog. import [Link].*;
public class Sum
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int n,sum;
[Link]("Enter the number of terms of the series: ");
n = [Link]( );
sum = n*n
[Link]("1+3+5+… .........................+29+31 = "+sum);
}
}
(b) 1 + 3 + 5 + 7 + .................................................. + 47 + 49
Prog. import [Link].*;
public class Sum
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int n,sum;
[Link]("Enter the number of terms of the series: ");
n = [Link]( );
sum = n*n
[Link]("1+3+5+… .........................+47+49 = "+sum);
}
}
Q.8 Write a program to input the sum. Calculate and display the compound
interest in 3 years, when the rates for the successive years are r1%, r2%
and
 r3% respectively. r1 r2 r3
Hint: A = P* 1 + *1 + *1 + , CI=A–P

100 100 100

30
Prog. import [Link].*;
public class Interest
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int p, r1, r2, r3;
double amt, ci;
[Link]("Enter the principal: ");
p = [Link]( );
[Link]("Enter the rate r1: ");
r1 = [Link]( );
[Link]("Enter the rate r2: ");
r2 = [Link]( );
[Link]("Enter the rate r3: ");
r3 = [Link]( );
amt = p*(1+(r1/100))*(1+(r2/100))*(1+(r3/100));
ci = amt – p;
[Link]("Amount after 3 years: " + amt);
[Link]("Compound Interest: " + ci);
}
}

Mathematical Library Methods 31


Chapter 1 Revision of Class IX Syllabus
Part VII
Conditional Statements in Java

IV. Convert the following constructs as directed:


1. switch case construct into if-else-if:
switch (n)
{
case 1:
s=a+b;
[Link]("Sum="+s);
break;
case 2:
d=a–b;
[Link]("Difference="+d);
break:
case 3:
p=a*b;
[Link]("Product="+p);
break;
default:
[Link]("Wrong Choice!");
}
Ans. if (n == 1)
{
s = a + b;
[Link]("Sum="+s);
}
else if (n == 2)
{
d = a – b;
[Link]("Difference="+d);
}
else if (n == 3)
{
p = a * b;
[Link]("Product="+p);
}
else
{
[Link]("Wrong Choice!");
}

32
2. if-else-if construct into switch case:
if(var==1)
[Link]("Distinction");
else if(var==2)
[Link]("First Division");
else if(var==3)
[Link]("Second Division");
else
[Link]("invalid");
Ans. switch (var)
{
case 1:
[Link]("Distinction");
break;
case 2:
[Link]("First Division");
break;
case 3:
[Link]("Second Division");
break;
default:
[Link]("invalid");
}
V. Answer the following questions:
1. What is meant by 'conditional' statement? Explain.
Ans. The order in which the statements of a program are executed is known as
control flow. By default, the statements of a program are executed from
top to bottom, but most of the times our programs require to modify this
top to bottom approach, based on some condition. So, the statements
that help us to alter the flow of the program are known as conditional
statements.
2. What is the significance of [Link](0)?
Ans. The [Link](0) terminates the execution of the program by ignorning
the Java Virtual Machine, executing the current program.
For example:
To find the square root of a number, if the user enters a negative number
then it is not possible to find the square root of the number. In such
situation, we can use [Link](0) to terminate the program.
3. Is it necessary to include 'default' case in a switch statement? Justify.
Ans. The 'default' case is an optional in a switch statement. It is included to
take care of the situation when none of the case values match in the
switch block for a given value of control variable.

Conditional Statements in Java 33


For example:
int n = 2;
switch(n)
{
case 0:
[Link]("Value of control variable is (0) zero");
break;
case 1:
[Link]("Value of control variable is 1");
break;
case 2:
[Link]("Value of control variable is 2");
break;
default:
[Link]("Value of control variable is greater than 2");
}
Even if we do not include the default case, the program is syntactically
correct but we will not get any output when value of control variable is
other than 0, 1 or 2.
4. What will happen if 'break' statement is not used in a switch case?
Explain.
Ans. In a switch case, the use of break statement is an optional. The omission
of break statement will lead to fall through where program execution
continues into the next case and onwards till end of switch statement is
reached.
5. When does 'Fall through' occur in a switch statement? Explain.
Ans. In case a break statement is not used at the end of each switch case
block, the control enters into the next case and onwards till end of switch
statement is reached. This condition is said to be fall through.
6. What is a compound statement? Give an example.
Ans. Two or more statements can be grouped together by enclosing them
between opening and closing curly braces. Such a group of statements
is known as a compound statement.
For example:
if (num1 < num2)
{
[Link]("First number is less than the second number");
num1 = 10;
num2 = 20;
[Link]("The value of first number is " + num1);
[Link]("The value of second number is " + num2);
}
7. Explain if-else-if construct with an example.
Ans. The if-else-if construct is used to test multiple conditions and then take
a decision. It provides multiple branching of control statements.

34
For example:
if (marks < 35)
[Link]("No Grade awarded");
else if (marks < 60)
[Link]("Grade C awarded");
else if (marks < 80)
[Link]("Grade B awarded");
else if (marks < 95)
[Link]("Grade A awarded");
else
[Link]("Grade A+ awarded");
8. Give two differences between the switch statement and the if-else
statement.
Ans. The differences are:
switch if-else
The switch statement can only test, The if-else can test for any boolean
if the expression is equal to any of expression such as less than,
its control variable. greater than, equal to, not equal
to, etc.
It is a multiple branching flow of It is a bi-directional flow of control
control statement. statement.

VI. Unsolved Java Programs:


Q.1 A triangle is said to be an 'Equable Triangle', if the area of the triangle is
equal to its perimeter. Write a program to enter three sides of a triangle.
Check and print whether the triangle is equable or not.
For example, a right angled triangle with sides 5, 12 and 13 has its area
and perimeter both equal to 30.
Prog. import [Link].*;
public class EquableTriangle
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
double a, b, c, p, s, ar;
[Link]("Enter the three sides of a triangle:");
[Link]("Enter the first side: ");
a = [Link]( );
[Link]("Enter the second side: ");
b = [Link]( );
[Link]("Enter the third side: ");
c = [Link]( );
p = a + b + c;
s = p / 2;
ar = [Link](s * (s – a) * (s – b) * (s – c));
if (ar == p)
[Link]("Equable Triangle");

Conditional Statements in Java 35


else
[Link]("Not an Equable Triangle");
}
}
Q.2 A special two-digit number is such that when the sum of its digits is
added to the product of its digits, the result is equal to the original two-
digit number.
For example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Total of the sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits
to the product of its digits. If the value is equal to the number input,
display the message "Special 2 - digit number" otherwise, display the
message "Not a special two-digit number".
Prog. import [Link].*;
public class Sp_Number
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int num, num1, digit1, digit2, dsum, dprod, gsum;
[Link]("Enter a 2-digit number: ");
num = [Link]( );
if (num < 10 || num > 99)
{
[Link]("Invalid input!");
[Link](0);
}
num1 = num;
digit1 = num % 10;
digit2 = num / 10;
dsum = digit1 + digit2;
dprod = digit1 * digit2;
gsum = dsum + dprod;
if (gsum == num)
[Link]("Special 2-digit number");
else
[Link]("Not a special 2-digit number");
}
}

36
Q.3 The standard form of quadratic equation is given by: ax2 + bx + c = 0,
where d = b2 – 4ac, is known as discriminant that determines the nature
of the roots of the equation as:

Condition Nature
if d >= 0 Roots are real
if d < 0 Roots are imaginary
Write a program to determine the nature and the roots of a quadratic
equation, taking a, b, c as input. If d = b2 – 4ac is greater than or equal
to zero, then display "Roots are real", otherwise display "Roots are
imaginary". The roots are determined by the formula as:
–b+ b2 – 4ac –b– b2 – 4ac
r1 = , r2 =
2a 2a
Prog. import [Link].*;
public class QuadRoots
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int a, b, c;
double d, r1, r2;
[Link]("Enter a: ");
a = [Link]( );
[Link]("Enter b: ");
b = [Link]( );
[Link]("Enter c: ");
c = [Link]( );
d = [Link](b, 2) – (4 * a * c);
if (d >= 0)
{
[Link]("Roots are real.");
r1 = (–b + [Link](d)) / (2 * a);
r2 = (–b – [Link](d)) / (2 * a);
[Link]("Roots of the equation are:");
[Link]("r1 = " + r1);
[Link]("r2 = " + r2);
}
else
[Link]("Roots are imaginary.");
}
}

Conditional Statements in Java 37


Q.4 An air-conditioned bus charges fare for the passengers based on the
distance travelled as per the tariff are given below:

Distance Travelled Fare


Up to 10 km Fixed charge Z 80
11 km to 20 km Z 6/km
21 km to 30 km Z 5/km
31 km and above Z 4/km
Design a program to input distance travelled by the passenger. Calculate
and display the fare to be paid.
Prog. import [Link].*;
public class BusFare
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int dist, fare;
[Link]("Enter distance travelled: ");
dist = [Link]( );
fare = 0;
if (dist <= 0)
fare = 0;
else if (dist <= 10)
fare = 80;
else if (dist <= 20)
fare = 80 + (dist – 10) * 6;
else if (dist <= 30)
fare = 80 + 60 + (dist – 20) * 5;
else if (dist > 30)
fare = 80 + 60 + 50 + (dist – 30) * 4;
[Link]("Fare = " + fare);
}
}
Q.5 An ICSE school displays a notice on the school notice board regarding
admission in Class XI for choosing stream according to the marks
obtained in English, Maths and Science in Class 10 Council Examination.

Marks obtained in different subjects Stream


Eng, Maths and Science >= 80% Pure Science
Eng and Science >= 80%, Maths >= 60% Bio. Science
Eng, Maths and Science >= 60% Commerce
Print the appropriate stream allotted to a candidate. Write a program to
accept marks in English, Maths and Science from the console.

38
Prog. import [Link].*;
public class Admission
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int eng, maths, sci;
[Link]("Enter marks in English: ");
eng = [Link]( );
[Link]("Enter marks in Maths: ");
maths = [Link]( );
[Link]("Enter marks in Science: ");
sci = [Link]( );
if (eng >= 80 && sci >= 80 && maths >= 80)
[Link]("Pure Science");
else if (eng >= 80 && sci >= 80 && maths >= 60)
[Link]("Bio. Science");
else if (eng >= 60 && sci >= 60 && maths >= 60)
[Link]("Commerce");
else
[Link]("Can not allot stream");
}
}
Q.6 A bank announces new rates for Term Deposit Schemes for their
customers and Senior Citizens as given below:
Term Rate of Interest Rate of Interest
(General) (Senior Citizen)
Up to 1 year 7.5% 8.0%
Up to 2 years 8.5% 9.0%
Up to 3 years 9.5% 10.0%
More than 3 years 10.0% 11.0%
The senior citizen rates are applicable to the customers whose age is 60
years or more. Write a program to accept the sum (p) in term deposit
scheme, age of the customer and the term. The program displays the
information in the following format:
Amount Term Age Interest earned Amount Paid
Deposited
xxx xxx xxx xxx xxx
Prog. import [Link].*;
public class BankDeposit
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);

Conditional Statements in Java 39


int sum, age;
double term, interest, amt;
[Link]("Enter sum: ");
sum = [Link]( );
[Link]("Enter age: ");
age = [Link]( );
[Link]("Enter term: ");
term = [Link]( );
interest = 0.0;
if (age < 60)
{
if (term <= 1)
interest = (sum * 7.5 * term)/100;
else if (term <= 2)
interest = (sum * 8.5 * term)/100;
else if (term <= 3)
interest = (sum * 9.5 * term)/100;
else
interest = (sum * 10.0 * term)/100;
}
else
{
if (term <= 1)
interest = (sum * 8.0 * term)/100;
else if (term <= 2)
interest = (sum * 9.0 * term)/100;
else if (term <= 3)
interest = (sum * 10.0 * term)/100;
else
interest = (sum * 11.0 * term) / 100;
}
amt = sum + interest;
[Link]("Sum Deposit"+"\t"+"Term"+"\t"+"Age"+"\t"+ "Interest"+"\t"+"Amount");
[Link](sum +"\t\t"+ term + "\t"+age+"\t"+interest+"\t\t"+amt);
}
}
Q.7 A courier company charges differently for 'Ordinary' booking and
'Express' booking based on the weight of the parcel as per the tariff
given below:
Weight of parcel Ordinary booking Express booking
Up to 100 gm Z 80 Z 100
101 to 500 gm Z 150 Z 200
501 gm to 1000 gm Z 210 Z 250
More than 1000 gm Z 250 Z 300
Write a program to input weight of a parcel and type of booking ('O' for
ordinary and 'E' for express). Calculate and print the charges accordingly.

40
Prog. import [Link].*;
public class Courier
{
public static void main(String args[])
{
double wt, charge;
char ch;
Scanner in = new Scanner([Link]);
[Link]("Enter weight of parcel: ");
wt = [Link]( );
[Link]("Enter type of booking 'O' or 'E':");
ch = [Link]( ).charAt(0);
charge = 0;
if (ch == 'O')
{
if (wt <= 0)
charge = 0;
else if (wt <= 100)
charge = 80;
else if (wt <= 500)
charge = 150;
else if (wt <= 1000)
charge = 210;
else
charge = 250;
}
if (ch == 'E')
{
if (wt <= 0)
charge = 0;
else if (wt <= 100)
charge = 100;
else if (wt <= 500)
charge = 200;
else if (wt <= 1000)
charge = 250;
else
charge = 300;
}
[Link]("Parcel charges = " + charge);
}
}

Conditional Statements in Java 41


Q.8 Write a program to input a number and check whether it is a perfect
square or not. If the number is not a perfect square then find the least
number to be added to input number, so that the resulting number is a
perfect square.
Example 1:
Sample Input: 2025
2025 = 45
Sample Output: It is a perfect square.
Example 2:
Sample Input: 1950
1950 = 44.1588………
Least number to be added= 452 – 1950 = 2025 – 1950 = 75
Prog. import [Link].*;
public class PerfectSquare
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int num, sqroot1, diff;
double sqroot, temp;
[Link]("Enter a number: ");
num = [Link]( );
if(num < 0)
{
[Link]("Invalid Input! Entered a negative number.");
[Link](0);
}
else
{
sqroot = [Link](num);
sqroot1 = (int)(sqroot);
if (num == sqroot1*sqroot1)
{
[Link](num + " is a perfect square.");
}
else
{
sqroot1+= 1;
temp = [Link](sqroot1, 2);
diff = (int)temp – num;
[Link](num + " is not a perfect square.");
[Link]("Least number to be added = " + diff);
}
}
}
}

42
Q.9 Write a program that accepts three numbers from the user and displays
them either in "Increasing Order" or in "Decreasing Order" as per the
user's choice.
Choice 1: Ascending order
Choice 2: Descending order
Sample Input: 394, 475, 296
Choice: 2
Sample Output:
First number : 475
Second number : 394
Third number : 296
The numbers are in decreasing order.
Prog. import [Link].*;
public class SortNumbers
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int a, b, c, ch;
[Link]("Enter first number: ");
a = [Link]( );
[Link]("Enter second number: ");
b = [Link]( );
[Link]("Enter third number: ");
c = [Link]( );
int max = 0, mid = 0, min = 0;
[Link]("Choice 1: Ascending Order");
[Link]("Choice 2: Descending Order");
[Link]("Enter your choice: ");
ch = [Link]( );
if(ch != 1 && ch != 2)
{
[Link]("Wrong choice");
}
else
{
if(a>b && a>c)
{
max = a;
if(b>c)
{
mid = b;
min = c;
}
else
{
mid = c;
min = b;
}

Conditional Statements in Java 43


}
if(b>a && b>c)
{
max = b;
if(a>c)
{
mid = a;
min = c;
}
else
{
mid = c;
min = a;
}
}
if(c>a && c>b)
{
max = c;
if(a>b)
{
mid = a;
min = b;
}
else
{
mid = b;
min = a;
}
}
}
if(ch == 1)
{
[Link]("Numbers arranged in ascending order:");
[Link]("First number: " + min);
[Link]("Second number: " + mid);
[Link]("Third number: " + max);
}
else
{
[Link]("Numbers arranged in descending order:");
[Link]("First number: " + max);
[Link]("Second number: " + mid);
[Link]("Third number: " + min);
}
}
}

44
Menu Driven/Switch Case programs
Q.10 Write a menu driven program to calculate:
(a) Area of a circle = p*r*r, where p = (22/7)
(b) Area of a square = side*side
(c) Area of a rectangle = length*breadth
Enter 'c' to calculate area of circle, 's' to calculate area of square and 'r'
to calculate area of rectangle.
Prog. import [Link].*;
public class MenuArea
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
double r, ar1, side, ar2, l, b, ar3;
char choice;
[Link]("Enter c to calculate area of circle");
[Link]("Enter s to calculate area of square");
[Link]("Enter r to calculate area of rectangle");
[Link]("Enter your choice: ");
choice = [Link]( ).charAt(0);
switch(choice)
{
case 'c':
[Link]("Enter radius of circle: ");
r = [Link]( );
ar1 = (22.0/7.0) * r * r;
[Link]("Area of circle = " + ar1);
break;
case 's':
[Link]("Enter side of square: ");
side = [Link]( );
ar2 = side * side;
[Link]("Area of square = " + ar2);
break;
case 'r':
[Link]("Enter length of rectangle: ");
l = [Link]( );
[Link]("Enter breadth of rectangle: ");
b = [Link]( );
ar3 = l * b;
[Link]("Area of rectangle = " + ar3);
break;
default:
[Link]("Wrong choice!");
}
}
}

Conditional Statements in Java 45


Q.11 Write a program using switch case to find the volume of a cube, a sphere
and a cuboid. For an incorrect choice, an appropriate error message
should be displayed.
(a) Volume of a cube = s * s *s
(b) Volume of a sphere = (4/3) * π * r * r * r (π = 22/7)
(c) Volume of a cuboid = l*b*h
Prog. import [Link].*;
public class MenuVolume
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int choice;
double cs, vcube, r, vsph, l, b, h, vcuboid;
[Link]("1. Volume of Cube");
[Link]("2. Volume of Sphere");
[Link]("3. Volume of Cuboid");
[Link]("Enter your choice: ");
choice = [Link]( );
switch(choice)
{
case 1:
[Link]("Enter side of cube: ");
cs = [Link]( );
vcube = [Link](cs, 3);
[Link]("Volume of cube = " + vcube);
break;
case 2:
[Link]("Enter radius of sphere: ");
r = [Link]( );
vsph = (4.0/3.0) * (22.0/7.0) * [Link](r, 3);
[Link]("Volume of sphere = " + vsph);
break;
case 3:
[Link]("Enter length of cuboid: ");
l = [Link]( );
[Link]("Enter breadth of cuboid: ");
b = [Link]( );
[Link]("Enter height of cuboid: ");
h = [Link]( );
vcuboid = l * b * h;
[Link]("Volume of cuboid = " + vcuboid);
break;
default:
[Link]("Wrong choice!");
}
}
}

46
Q.12 The relative velocity of two trains travelling in opposite directions is
calculated by adding their velocities. In case, the trains are travelling in
the same direction, the relative velocity is the difference between their
velocities. Write a program to input the velocities and length of the trains.
Write a menu driven program to calculate the relative velocities and the
time taken to cross each other.
Prog. import [Link].*;
public class Velocity
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int choice;
double speed1, speed2, len1, len2, rspeed, time;
[Link]("1. Trains travelling in same direction");
[Link]("2. Trains travelling in opposite directions");
[Link]("Enter your choice: ");
choice = [Link]( );
[Link]("Enter velocity of first train: ");
speed1 = [Link]( );
[Link]("Enter length of first train: ");
len1 = [Link]( );
[Link]("Enter velocity of second train: ");
speed2 = [Link]( );
[Link]("Enter length of second train: ");
len2 = [Link]( );
rspeed = 0.0;
switch(choice)
{
case 1:
rspeed = [Link](speed1 – speed2);
break;
case 2:
rspeed = speed1 + speed2;
break;
default:
[Link]("Wrong choice!");
}
time = (len1 + len2) / rspeed;
[Link]("Relative Velocity = " + rspeed);
[Link]("Time taken to cross each other = " + time);
}
}

Conditional Statements in Java 47


Q.13 In order to purchase an old car, the depreciated value can be calculated
as per the tariff given below:

No. of years used Rate of depreciation


1 10%
2 20%
3 30%
4 50%
Above 4 years 60%
Write a menu driven program to input showroom price and the number
of years the car is used ('1' for one year old, '2' for two years old and so
on). Calculate the depreciated value. Display the original price of the
car, depreciated value and the amount to be paid.
Prog. import [Link].*;
public class CarValue
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int choice, price;
double dvalue=0.0, amt;
[Link]("Enter showroom price: ");
price = [Link]( );
[Link]("1. One year old car");
[Link]("2. Two years old car");
[Link]("3. Three years old car");
[Link]("4. Four years old car");
[Link]("5. More than four years old car");
[Link]("Enter your choice: ");
choice = [Link]( );
switch(choice)
{
case 1:
dvalue = 0.1 * price;
break;
case 2:
dvalue = 0.2 * price;
break;
case 3:
dvalue = 0.3 * price;
break;
case 4:
dvalue = 0.5 * price;
break;
case 5:
dvalue = 0.6 * price;

48
break;
default:
[Link]("Wrong Choice!!");
[Link](0);
}
amt = price – dvalue;
[Link]("Original Price = " + price);
[Link]("Depricated Value = " + dvalue);
[Link]("Amount to be paid = " + amt);
}
}
Q.14 You have a saving account in a bank with some balance amount in your
account. Now, you want to perform the following tasks, as per your
choice. The tasks are as under.
1. Money Deposited
2. Money Withdrawn
3. Check balance
0. To quit
Write a menu driven program to take input from the user and perform
the above tasks. The program checks the balance before withdrawal and
finally displays the current balance after transaction. For an incorrect
choice, an appropriate message should be displayed.
Prog. import [Link].*;
public class BankAccount
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int ch;
double amt, bal;
[Link]("Enter 1: To deposit money");
[Link]("Enter 2: To withdraw money");
[Link]("Enter 3: To check balance");
[Link]("Enter 0: To quit");
[Link]("Enter your choice: ");
ch = [Link]( );
amt = 0.0;
bal = 9500.0; //Initial balance
switch(ch)
{
case 0:
[Link]("Thank you!");
[Link]("Visit Again");
break;
case 1:
[Link]("Enter deposited amount : ");
amt = [Link]( );
bal += amt;

Conditional Statements in Java 49


[Link]("Money deposited");
[Link]("Total balance = " + bal);
break;
case 2:
[Link]("Enter withdrawal amount : ");
amt = [Link]( );
if(amt > bal)
{
[Link]("Insufficient balance??");
}
else
{
bal – = amt;
[Link]("Money withdrawn");
[Link]("Total balance = " + bal);
break;
}
case 3:
[Link]("Total balance = " + bal);
break;
default:
[Link]("Invalid Request!!");
}
}
}

50
Chapter 1 Revision of Class IX Syllabus
Part VIII
Iterative Constructs in Java

IV. Rewrite the following programs:


1. Using for loop:
int i=1;
int d=5;
do
{
d=d*2;
[Link](d);
i++;
}
while (i<=5);
Ans. int d=5;
for (int i = 1; i <= 5; i++)
{
d=d*2;
[Link](d);
}
2. Using while loop:
import [Link].*;
class Number
{
public static void main(String args[])
{
int n,r;
Scanner in = new Scanner([Link]);
[Link]("Enter a number");
n=[Link]( );
do
{
r=n%10;
n=n/10;
[Link](r);
}
while(n!=0);
}
}
Ans. import [Link].*;
class Number
{
public static void main(String args[])

51
{
int n,r;
Scanner in = new Scanner([Link]);
[Link]("Enter a number");
n=[Link]( );
while (n != 0)
{
r=n%10;
n=n/10;
[Link](r);
}
}
}
V. Answer the following questions:
1. What is 'for' loop? What are the parameters used in 'for' loop?
Ans. The for loop is an entry-controlled loop. This loop is used when number
of iterations is fixed and known. So, it is also referred to as a fixed or
known iterative looping construct. The parameters used in a for loop are:
• an initial value for the loop control variable
• a condition: The loop will iterate as long as this condition remains true.
• an update expression to modify the control variable after every
iteration.
2. Define the following with their constructs:
Ans. (a) Entry controlled loop
An entry-controlled loop checks the condition in the beginning. If the
condition is true, the program control enters the body of the loop.
For example, for and while loops
(b) Exit controlled loop
An exit-controlled loop checks the condition after executing its body.
If the condition is true, loop will perform the next iteration, otherwise
program control will exit the loop.
For example, do-while loop
3. Write down the syntax of:
Ans. (a) do - while
do
{
//body of the loop
………………….
………………….
} while (condition);
(b) while loop
while (condition)
{
//body of the loop
……………………
……………………
}

52
4. What is the purpose of using
Ans. (a) break statement
The 'break' statement is used in a loop to send the control to exit the
loop, if certain condition is true.
(b) continue statement in a program?
When the 'continue' statement is invoked, the control goes back to
check the condition and jumps to the next iteration of the loop by
skipping the remaining statements of the current iteration.
5. Distinguish between while and do-while loop.
Ans. while do-while
It is an entry-controlled loop. It is an exit-controlled loop.
It follows a top-down approach. It follows a bottom-top approach.

6. What is meant by an infinite loop? Give an example.


Ans. A loop which continues iterating indefinitely and never stops is termed
as infinite loop.
For example:
for (; ;)
{
………………………;
………………………;
}
7. State one difference and one similarity between while loop and do-while
loop.
Ans. Similarity: Both while and do-while are suitable in situations where
numbers of iterations is not known.
Difference: The while is an entry-controlled loop, whereas do-while is
an exit-controlled loop
VI. Unsolved Java Programs:
Q.1 Write the programs in Java to display the first ten terms of the following
series:
(a) 0, 1, 2, 3, 6, ………………………………
Prog. public class Tribonacci
{
public static void main(String args[])
{
int a = 0, b = 1, c = 2, n;
[Link](a + ", " + b + ", " + c);
for (int i = 0; i < 7; i++)
{
n = a + b + c;
[Link](", " + n);
a = b;
b = c;
c = n;
}
}
}
Iterative Constructs in Java 53
(b) 1, –3, 5, –7, 9, ……………………
Prog. public class Series
{
public static void main(String args[])
{
int term = 1;
[Link](term);
for (int i = 2; i <= 10; i++)
{
term += 2;
if (i % 2 == 0)
[Link](", " + (–term));
else
[Link](", " + term);
}
}
}
(c) 0, 3, 8, 15, ………………………
Prog. public class Series
{
public static void main(String args[])
{
int term = 0;
[Link](term);
for (int i = 3; i < 20; i = i + 2)
{
term += i;
[Link](", " + term);
}
}
}
(d) 1, 11, 111, 1111, ………………………
Prog. public class Series
{
public static void main(String args[])
{
int term = 1;
for (int i = 1; i <= 10; i++)
{
[Link](term + ", ");
term = term * 10 + 1;
}
}
}

54
(e) 1, 12, 123, 1234, ……………………….
Prog. public class Series
{
public static void main(String args[])
{
int i, t=0,c=1;
for (i = 0; i < 10; i++)
{
t=(10*t)+c;
[Link](t+",");
c++;
}
}
}
Q.2 Write the programs in Java to find the sum of the following series:
(a) s = 1 + 1 + 2 + 3 + 5 + ......... to n terms
Prog. import [Link].*;
public class Series
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int n, a, b, i, sum, temp;
[Link]("Enter number of terms: ");
n = [Link]( );
a = 1; b = 1;
sum = a + b;
for (i = 3; i <= n; i++)
{
temp = a + b;
sum += temp;
a = b;
b = temp;
}
[Link]("Sum=" + sum);
}
}
(b) s = 2 – 4 + 6 – 8 + ........ to n
Prog. import [Link].*;
public class Series
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int n, sum, i, a=2;
[Link]("Enter the value of n: ");
n = [Link]( );

Iterative Constructs in Java 55


sum = 0;
for (i=1; i<=n; i++)
{
if (i % 2 == 0)
sum –= a;
else
sum += a;
a=a+2;
}
[Link]("Sum = "+ sum);
}
}
(c) s = 1 + (1+2) + (1+2+3) + ....... + (1+2+3+ ........ + n)
Prog. import [Link].*;
public class Series
{
public static void main(String args[])
{
int n, sum, i, term;
Scanner in = new Scanner([Link]);
[Link]("Enter the value of n: ");
n = [Link]( );
sum = 0; term = 0;
for ( i = 1; i <= n; i++)
{
term += i;
sum += term;
}
[Link]("Sum=" + sum);
}
}
(d) s = 1 + (1*2) + (1*2*3) + .......................... + (1*2*3* ........ * n)
Prog. import [Link].*;
public class Series
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int n, sum, i, term;
[Link]("Enter the value of n: ");
n = [Link]( );
sum = 0; term = 1;
for (i = 1; i <= n; i++)
{
term *= i;
sum += term;
}

56
[Link]("Sum=" + sum);
}
}
(e) s = 1+(1+2)/(1*2)+(1+2+3)/(1*2*3)+.......+ (1+2+3 ....... + n)/(1*2*3* ....... * n)
Prog. import [Link].*;
public class Series
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int n, sum=0;
double sum_series=0.0, prod=1;
[Link]("Enter the value of n: ");
n = [Link]( );
for (int i = 1; i <= n; i++)
{
sum += i;
prod *= i;
double term = sum / prod;
sum_series += term;
}
[Link]("Sum=" + sum_series);
}
}
Q.3 Write the programs to find the sum of the following series:
(a) s = a + a2 + a3 + ........ + an
Prog. import [Link].*;
public class Series
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int a, i, n, sum=0;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
for (i = 1; i <= n; i++)
{
sum += [Link](a, i);
}
[Link]("Sum=" + sum);
}
}

Iterative Constructs in Java 57


(b) s = (a+1) + (a+2) + (a+3) +......... + (a+n)
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, n, sum=0;
[Link]("Enter the value a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
for (int i = 1; i <= n; i++)
{
sum += a + i;
}
[Link]("Sum=" + sum);
}
}
(c) s = (a/2) + (a/5) + (a/8) + (a/11) + ........ + (a/20)
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, i;
double sum = 0;
[Link]("Enter the value of a: ");
a = [Link]( );
for (i = 2; i <= 20; i = i + 3)
{
sum += a / (double)i;
}
[Link]("Sum=" + sum);
}
}
(d) s = (1/a) + (2/a2) + (3/a3) + ........ to n
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, i, n;
double sum = 0;

58
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
for (i = 1; i <= n; i++)
{
sum += (i/[Link](a, i));
}
[Link]("Sum=" + sum);
}
}
(e) s = a – a3 + a5 – a7 +......... to n
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, b=1, n, i, sum=0;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
for (i = 1; i <= n; i ++)
{
if (i % 2 == 0)
sum –= [Link](a, b);
else
sum += [Link](a, b);
b=b+2;
}
[Link]("Sum=" + sum);
}
}
Q.4 Write a program to accept a number and check whether the number is
perfect or not.
[A number is said to be perfect, if the sum of the factors (including 1 and
excluding the number itself) is the same as the original number.]
Sample Input: 6
Sample Output: It is a perfect number.
The factors of 6 = 1, 2, 3 and 1 + 2 + 3 = 6
Prog. import [Link].*;
public class Perfect
{
public static void main (String args[])
{

Iterative Constructs in Java 59


Scanner in=new Scanner([Link]);
int a,n,s=0;
[Link]("Enter a number:");
n=[Link]( );
for(a=1;a<n;a++)
{
if(n%a==0)
s=s+a;
}
if(s==n)
[Link](a + " is a perfect number");
else
[Link](a + " is not a perfect number");
}
}
Q.5 Write a program to enter two numbers and check whether they are
co-prime or not.
[Two numbers are said to be co-prime, if their HCF is 1 (one).]
Sample Input: 14, 15
Sample Output: They are co-prime.
Prog. import [Link].*;
public class Coprime
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int a, b, i, p, hcf=0;
[Link]("Enter first number: ");
a = [Link]( );
[Link]("Enter second number: ");
b = [Link]( );
p=a*b;
for (i = 1; i < p; i++)
{
if (a % i == 0 && b % i == 0)
hcf = i;
}
if (hcf == 1)
[Link](a + " and " + b + " are co-prime");
else
[Link](a + " and " + b + " are not co-prime");
}
}

60
Q.6 Write a program to input a number. Display the product of the successors
of even digits of the number entered by user.
Sample Input: 2745
Sample Output: 15
[Hint: The even digits are: 2 and 4
The product of successors of even digits is: 3*5= 15]
Prog. import [Link].*;
public class Successor
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, num1, prod=1, digit;
[Link]("Enter a number: ");
num = [Link]( );
num1 = num;
prod = 1;
while (num!= 0)
{
digit = num % 10;
num /= 10;
if (digit % 2 == 0)
{
[Link]("Even digits in " + num1+":"+digit );
prod = prod * (digit + 1);
}
}
if (prod == 1)
[Link]("No even digits present in " + num1);
else
[Link]("Product of even digits successors is " + prod);
}
}
Q.7 Write a program to input a number and check and print whether it is a
Pronic number or not. [Pronic number is the number which is the product
of two consecutive integers.]
For example,
12 = 3 * 4
20 = 4 * 5
42 = 6 * 7
Prog. import [Link].*;
public class Pronic
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, i, f=0;
[Link]("Enter a number: ");
num = [Link]( );

Iterative Constructs in Java 61


for (i = 1; i < num; i++)
{
if (i*(i+1) == num)
f=1;
}
if (f==1)
[Link](num + " is a pronic number");
else
[Link](num + " is not a pronic number");
}
}
Q.8 A prime number is said to be 'Twisted Prime', if the new number obtained
after reversing the digits is also a prime number. Write a program to
accept a number and check whether the number is 'Twisted Prime' or
not.
Sample Input: 167
Sample Output: 761
167 is a 'Twisted Prime'.
Prog. import [Link].*;
public class TwistedPrime
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, i, t, rnum=0, digit;
boolean isPrime = true;
[Link]("Enter a number (2-digit or more): ");
num = [Link]( );
for (i = 2; i <= num/2; i++)
{
if (num % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
t = num;
while (t!= 0)
{
digit = t % 10;
t /= 10;
rnum = rnum * 10 + digit;
}
for (i = 2; i <= rnum / 2; i++)
{
if (rnum % i == 0)
{

62
isPrime = false;
break;
}
}
}
if (isPrime)
[Link](num + " is a twisted prime number");
else
[Link](num + " is not a twisted prime number");
}
}
Q.9 Write a program to input a number and check whether it is a prime
number or not. If it is not a prime number then display the next number
that is prime.
Sample Input: 14
Sample Output: 17
Prog. import [Link].*;
public class PrimeCheck
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, num1, i, c=0, c1=0;
[Link]("Enter a number: ");
num = [Link]( );
for (i = 1; i <= num; i++)
{
if (num % i == 0)
c++;
}
if (c==2)
[Link](num + " is a prime number");
else
{
num1=num;
while (c1!=2)
{
num1=num+1;
c1=0;
for (i=1; i<=num1; i++)
{
if (num1% i == 0)
c1++;
}
}
if (c1==2)
[Link]("Next prime number = " + num1);
}
}
}

Iterative Constructs in Java 63


Q.10 A number is said to be Duck if the digit zero is (0) present in it. Write a
program to accept a number and check whether the number is Duck or
not. The program displays the message accordingly. (The number must
not begin with zero.)
Sample Input: 5063
Sample Output: It is a Duck number.
Sample Input: 7453
Sample Output: It is not a Duck number.
Prog. import [Link].*;
public class DuckNumber
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int n, c=0, d;
[Link]("Enter a number: ");
n=[Link]( );
while(n!=0)
{
d= n%10;
if(d==0)
{
c=1;
}
n=n/10;
}
if (c==1)
[Link]("Duck Number");
else
[Link]("Not a Duck Number");
}
}
Q.11 A computerised bus charges fare from each of its passengers based on
the distance travelled as per the tariff given below:

Distance (in km) Charges


First 5 km Z 80
Next 10 km Z 10/km
More than 15 km Z 8/km
As the passenger enters the bus, the computer prompts "Enter distance
you intend to travel". On entering the distance, it prints his/her ticket
and the control goes back for the next passenger. At the end of the
journey, the computer prints the following:
(i) the number of passenger travelled
(ii) total fare received
Write a program to perform the above task.
[Hint: Perform the task based on user controlled loop]

64
Prog. import [Link].*;
public class BusTravel
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int dist, tf = 0, tp = 0;
[Link]("Enter distance as –1 to complete the journey");
while (true)
{
[Link]("Enter distance you intend to travel: ");
dist = [Link]( );
int f = 0;
if (dist == –1)
break;
else if (dist <= 5)
f = 80;
else if (dist <= 15)
f = 80 + ((dist – 5) * 10);
else
f = 80 + 100 + ((dist – 15) * 8);
tf += f;
tp++;
[Link]("Your fare is " + f);
}
[Link]("Total Passengers: " + tp);
[Link]("Total Fare: " + tf);
}
}
Q.12 A special two-digit number is such that when the sum of its digits is
added to the product of its digits, the result is equal to the original
two-digit number.
For example:
Sample Input: 59
Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits
to the product of its digits. If the value is equal to the number input, then
display the message "Special two-digit number" otherwise, display the
message "Not a special two-digit number".
Prog. import [Link].*;
public class SplNumber
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, num1, c=0, dsum=0, dprod=1;

Iterative Constructs in Java 65


[Link]("Enter a 2-digit number: ");
num = [Link]( );
num1 = num;
while (num1!= 0)
{
int digit = num1% 10;
num1/= 10;
dsum += digit;
dprod *= digit;
c++;
}
if (c!= 2)
[Link]("Invalid input! Enter a 2-digit number");
else if ((dsum + dprod) == num)
[Link]("Special 2-digit number");
else
[Link]("Not a special 2-digit number");
}
}
Q.13 Write a program to input a number. Check and display whether it is a
Niven number or not.
[A number is said to be Niven if it is divisible by the sum of its digits].
Sample Input: 126
Sum of its digits = 1 + 2 + 6 = 9 and 126 is divisible by 9.
Prog. import [Link].*;
public class Niven
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num,sum=0,d,p;
[Link]("Enter a number");
num = [Link]( );
p=num;
do
{
d=num%10;
sum=sum+d;
num=num/10;
}
while(num!=0);
if(p%sum==0)
[Link]("Niven Number");
else
[Link]("Not a Niven Number");
}
}

66
Q.14 Write a program to accept a number and check whether it is a 'Spy
Number' or not. (A number is spy if the sum of its digits equals the
product of its digits.)
For example:
Sample Input: 1124
Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1*1*2*4 = 8
Prog. import [Link].*;
public class SpyNumber
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, d, sum=0, num1, prod=1;
[Link]("Enter a number: ");
num = [Link]( );
num1 = num;
while (num1 > 0)
{
d = num1 % 10;
sum += d;
prod *= d;
num1 /= 10;
}
if (sum == prod)
[Link](num + " is a Spy Number");
else
[Link](num + " is not a Spy Number");
}
}
Q.15 Write a program to input a number and check whether it is a Harshad
number or not. [A number is said to be Harshad number, if it is divisible
by the sum of its digits. The program displays the message accordingly.]
For example:
Sample Input: 132
Sum of digits=6 and 132 is divisible by 6.
Sample Output: It is a Harshad Number.
Sample Input: 353
Sample Output: It is not a Harshad Number.
Prog. import [Link].*;
public class HarshadNum
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, d, sum=0, num1;
[Link]("Enter a number: ");
num = [Link]( );
num1 = num;

Iterative Constructs in Java 67


while (num1 > 0)
{
d = num1 % 10;
sum += d;
num1 /= 10;
}
if (num % sum==0)
[Link](num + " is a Harshad Number");
else
[Link](num + " is not Harshad Number");
}
}
Q.16 Write a program to input a number and check whether the number is a
Dudeney number or not. A number is Dudeney, if the cube of the sum
of the digits is equal to the number itself.
For example: 512 = (5+1+2)3 = (8)3 = 512
Prog. import [Link].*;
public class DudencyNum
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int num, d, sum=0, num1;
[Link]("Enter a number: ");
num = [Link]();
num1 = num;
while (num1 > 0)
{
d = num1 % 10;
sum += d;
num1 /= 10;
}
if (sum*sum*sum == num)
[Link](num + " is a Dudeney Number");
else
[Link](num + " is not Dudeney Number");
}
}
Q.17 You can multiply two numbers 'm' and 'n' by repeated addition method.
For example,
5 * 3 = 15 can be performed by adding 5 three times ⇒ 5 + 5 + 5 = 15
Similarly, successive subtraction of two numbers produces 'Quotient'
and 'Remainder' when a number 'a' is divided by 'b' (a>b).
For example, 5/2 ⇒ Quotient = 2 and Remainder = 1
Follow steps shown below:
Process Result Counter
5–2 3 1
3–2 1 2

68
Sample Output: The last counter value represents 'Quotient' ⇒ 2
The last result value represents 'Remainder' ⇒ 1
Write a program to accept two numbers. Perform multiplication and
division of the numbers as per the process shown above by using switch
case statement.
Prog. import [Link].*;
public class Arithmetic
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, b, ch;
[Link]("Enter first number: ");
a = [Link]( );
[Link]("Enter second number: ");
b = [Link]( );
[Link]("1. Multiplication");
[Link]("2. Division");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
int res = 0;
for (int i = 1; i <= b; i++)
{
res += a;
}
[Link]("Multiplication result = " + res);
break;
case 2:
int c = 0, t = a;
while (t > b)
{
t –= b;
c++;
}
[Link]("Quotient = " + c);
[Link]("Remainder = " + t);
break;
default:
[Link]("Incorrect Choice!!");
break;
}
}
}

Iterative Constructs in Java 69


Q.18 A Tech Number has even number of digits. If the number is split into
two equal halves, then the square of sum of these halves is equal to the
number itself.
Write a program to generate and print all four-digit tech numbers.
For example, 3025
Square of sum of the halves of 3025 = (30 + 25)2
= (55)2
= 3025 is a Tech Number.
Prog. import [Link].*;
class TechNumber
{
public static void main(String args[ ])
{
int i, a, b, sum;
String n;
[Link]("Four Digits Tech Numbers are:");
for(i = 1000; i < 9999; i++)
{
n = [Link](i);
a = [Link]([Link](0,2));
b = [Link]([Link](2));
sum = (int)[Link]((a+b),2);
if (sum == i)
[Link](i);
}
}
}
Q.19 Using a switch statement, write a menu driven program to:
(a) generate and display the first 10 terms of the Fibonacci series
0, 1, 1, 2, 3, 5, ………………
The first two Fibonacci numbers are 0 and 1, and each subsequent
number is the sum of the previous two.
(b) find the sum of the digits of an integer that is input by the user.
Sample Input: 15390
Sample Output: Sum of the digits = 18
For an incorrect choice, an appropriate error message should be
displayed.
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, b, ch, i, t, num, sum=0;
[Link]("1. Fibonacci Series");
[Link]("2. Sum of digits");
[Link]("Enter your choice: ");
ch = [Link]( );

70
switch (ch)
{
case 1:
a = 0; b = 1;
[Link](a + " " + b);
for (i = 3; i <= 10; i++)
{
t = a + b;
[Link](" " + t);
a = b;
b = t;
}
break;
case 2:
[Link]("Enter a number: ");
num = [Link]( );
while (num != 0)
{
sum += num % 10;
num /= 10;
}
[Link]("Sum of Digits " + " = " + sum);
break;
default:
[Link]("Incorrect choice!!");
break;
}
}
}
Q.20 Using switch statement, write a menu driven program for the following:
(a) To find and display the sum of the series given below:
S = x1 – x2 + x3 – x4 + x5 – ............................................................20
(b) To find and display the sum of the series given below:
S = 1/a2 + 1/a4 + 1/a6 + 1/a8 + ....................................................... to n
terms
For an incorrect option, an appropriate error message should be
displayed.
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int x, ch, i, a, n, p;
double sum=0;
[Link]("1. Sum of First Series");
[Link]("2. Sum of Second Series");
[Link]("Enter your choice: ");

Iterative Constructs in Java 71


ch = [Link]( );
switch (ch)
{
case 1:
[Link]("Enter the value of x : ");
x = [Link]( );
for (i = 1; i <= 20; i++)
{
if(i%2 == 0)
sum = sum – [Link](x,i);
else
sum = sum + [Link](x,i);
}
[Link]("Sum of first series " + " = " + sum);
break;
case 2:
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
p=2;
for (i = 1; i <= n; i++)
{
sum = sum + 1/[Link](a,p);
p = p + 2;
}
[Link]("Sum of second series " + " = " + sum);
break;
default:
[Link]("Incorrect choice!!");
break;
}
}
}
Q.21 Write a menu driven program to perform the following tasks:
(a) Tribonacci numbers are a sequence of numbers similar to Fibonacci
numbers, except that a number is formed by adding the three
previous numbers. Write a program to display the first twenty
Tribonacci numbers.
For example: 1, 1, 2, 4, 7, 13, ……………………………………….
(b) Write a program to display all Sunny numbers in the range from 1
to n.
[Hint: A number is said to be sunny number, if square root of (n+1)
is an integer.]
For example: 3, 8, 15, 24, 35, .............................. are sunny numbers.
For an incorrect option, an appropriate error message should be
displayed.

72
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, b, c, n, ch, i, num, rt;
[Link]("1. Tribonacci Series");
[Link]("2. To check Sunny Number");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
a = 1; b = 1; c = 2;
[Link](a + ", " + b + ", " + c);
for (i = 0; i < 17; i++)
{
n = a + b + c;
[Link](", " + n);
a = b;
b = c;
c = n;
}
break;
case 2:
[Link]("Enter a number: ");
num = [Link]( );
rt = (int)[Link]((num+1));
if(rt*rt == (num+1))
[Link]("Sunny Number");
else
[Link]("Not a Sunny Number");
break;
default:
[Link]("Incorrect choice!!");
break;
}
}
}

Iterative Constructs in Java 73


Chapter 1 Revision of Class IX Syllabus
Part IX
Nested Loops

III. Answer the following questions:


1. What is a nested loop?
Ans. When a loop is contained inside another loop, it is referred to as a nested
loop.
2. Write down the syntax of a nested for loop.
Ans. The syntax of nested loop:
for (<initial value>; <test condition>; <update value>)
{
for (<initial value>; <test condition>; <update value>)
{
……………………………………….
executable statement(s)
……………………………………….
}
}
3. What action will you take to terminate an outer loop from the block of
an inner loop?
Ans. An outer loop can be terminated from the block of an inner loop by using
Labelled break statement (i.e., break outer). It is as shown below:
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 10; j++)
{
[Link](j);
if (i == 3)
break outer;
}
}
4. Give two differences between 'Break' and 'Continue'.
Ans. The differences are:
break continue
It is used for unusal termination of It takes the control to the
the loop. next iteration by skipping the
remaining statements of the
current iteration.
It is used in switch-case and loops. It is only used in loops.

74
5. What is the significance of 'break outer' and 'continue outer' in a nested
loop?
Ans. The 'break outer' will terminate the loop that is labelled as outer in a
nested loop and transfer the control to the just after the loop. Where as,
the 'continue outer' will skip the remaining statements of the nested loop
and go for the next iteration of the loop, labelled as 'continue outer'.
6. Write down the constructs (syntax) of:
Ans. (a) Nested do-while loop
do
{
//statements of outer do-while loop
…………………………………………….
…………………………………………….
do
{
//statements of inner do-while loop
…………………………………………..
…………………………………………..
}
while (<condition>);
…………………………………………..
}
while (<condition>);
(b) Nested while loop
while (<condition>)
{
//statements of outer while loop
………………………………………..
………………………………………..
while (<condition>)
{
//statements of inner while loop
…………………………………...
…………………………………...
}
………………………………...
………………………………...
}
IV. Unsolved Java Programs
Q.1 Write programs to find the sum of the following series:
(a) S = 1 + (3/2!) + (5/3!) + (7/4!) +......... to n
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int n, i, j=1, k, f;

Nested Loops 75
double sum = 0;
[Link]("Enter the value of n: ");
n = [Link]( );
for (i = 1; i <= n; i++)
{
f = 1;
for (k = 1; k <= i; k++)
{
f *= k;
}
sum = sum + ((double)j/f);
j=j+2;
}
[Link]("Sum=" + sum);
}
}
(b) S = a + (a/2!) + (a/3!) + (a/4!) + ........ + (a/n!)
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, n, i, j, f;
double sum = 0;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
for (i = 1; i <= n; i++)
{
f = 1;
for (j = 1; j <= i; j++)
{
f *= j;
}
sum += ((double)a/f);
}
[Link]("Sum=" + sum);
}
}
(c) S = a – (a/2!) + (a/3!) – (a/4!) + ........ to n
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{

76
Scanner in = new Scanner([Link]);
int a, n, i, j, f;
double sum = 0;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
for (i = 1; i <= n; i++)
{
f = 1;
for (j = 1; j <= i; j++)
{
f *= j;
}
if (i % 2 == 0)
sum –= (double)a/f;
else
sum += (double)a/f;
}
[Link]("Sum=" + sum);
}
}
(d) S = (a/2!) – (a/3!) + (a/4!) – (a/5!) + ........ + (a/10!)
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, n, i, j, f;
double sum = 0;
[Link]("Enter the value of a: ");
a = [Link]( );
for (i = 2; i <= 10; i++)
{
f = 1;
for (j = 1; j <= i; j++)
{
f *= j;
}
if (i % 2 == 0)
sum += (double)a/f;
else
sum –= (double)a/f;
}
[Link]("Sum=" + sum);
}
}

Nested Loops 77
(e) S = (2/a) + (3/a2) + (5/a3) + (7/a4) + ........ to n
Prog. import [Link].*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, n, pr, i, j, k;
double sum = 0;
[Link]("Enter the value of a: ");
a = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
pr = 1;
for (i = 1; i <= n; i++)
{
for (j = pr+1; j <= Integer.MAX_VALUE; j++)
{
boolean isPrime = true;
for (k = 2; k <= j/2; k++)
{
if (j % k == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
sum += j/[Link](a, i);
pr = j;
break;
}
}
}
[Link]("Sum=" + sum);
}
}
Q.2 Write a program to input two numbers and check whether they are twin
prime numbers or not.
[Hint: Twin prime numbers are the prime numbers whose difference is 2.
For example: (5,7), (11,13), ........ and so on.]
Prog. import [Link].*;
public class TwinPrime
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int m, n, i, c1=0, c2=0;

78
[Link]("Enter first number: ");
m = [Link]( );
[Link]("Enter second number: ");
n = [Link]( );
for(i=2;i<m;i++)
{
if(m%i==0)
c1=1;
}
for(i=2;i<n;i++)
{
if(n%i==0)
c2=1;
}
if((c1==0 && c2==0) && (m–n==2||n–m==2))
[Link](m+ " and " +n+ " are twin primes");
else
[Link](m+ " and " +n+ " are not twin primes");
}
}
Q.3 Write a program to display all the numbers between 100 and 200 which
don't contain zeros at any position.
For example: 111, 112, 113, ........ , 199
Prog. public class NonZero
{
public static void main(String args[ ])
{
int i, c = 0, t;
for (i = 100; i <= 200; i++)
{
boolean isNoZero = true;
t = i;
while (t > 0)
{
if (t % 10 == 0)
{
isNoZero = false;
break;
}
t /= 10;
}
if (isNoZero)
{
[Link](i + " ");
c++;
}
if (c == 10) // to display 10 numbers in a line
{
[Link]( );

Nested Loops 79
c = 0;
}
}
}
}
Q.4 Write a program to display all prime palindrome numbers between 10
and 1000.
[Hint: A number which is prime as well a palindrome is said to be 'Prime
Palindrome' number.]
For example: 11, 101, 131, 151,
Prog. public class PrimePalin
{
public static void main(String args[ ])
{
int i, num, rnum, c = 0, d;
for (i = 10; i <= 1000; i++)
{
num = i; rnum = 0;
while (num!= 0)
{
d = num % 10;
num /= 10;
rnum = rnum * 10 + d;
}
if (rnum == i)
{
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
[Link](i + " ");
c++;
if (c == 10)
{
[Link]( );
c = 0;
}
}
}
}
}
}

80
Q.5 Write a program in Java to enter a number containing three digits or
more.
Arrange the digits of the entered number in ascending order and display
the result.
Sample Input: 4972
Sample Output: 2, 4, 7, 9
Prog. import [Link].*;
public class Sort
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num, num1, i, j, c;
[Link]("Enter a number having 3 or more digits: ");
num = [Link]( );
[Link]("Digits in ascending order:");
for (i = 0; i <= 9; i++)
{
num1 = num;
c = 0;
while (num1 != 0)
{
if (num1 % 10 == i)
c++;
num1 /= 10;
}
for (j = 1; j <= c; j++)
{
[Link](i + ", ");
}
}
[Link]( );
}
}
Q.6 Write a program to input a number and check whether it is 'Magic
Number' or not. Display the message accordingly.
A number is said to be a magic number, if the eventual sum of digits of
the number is one.
Sample Input: 55
Then, 5 + 5 = 10, 1 + 0 = 1
Sample Output: Hence, 55 is a Magic Number.
Similarly, 289 is a Magic Number.
Prog. import [Link].*;
public class MagicNum
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);

Nested Loops 81
int num, n, sum, d;
[Link]("Enter a number: ");
num = [Link]( );
n = num;
while (n > 9)
{
sum = 0;
while (n != 0)
{
d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}
if (n == 1)
[Link](num + " is Magic Number");
else
[Link](num + " is not Magic Number");
}
}
Q.7 A number is said to be Multiple Harshad number, when divided by the
sum of its digits, produces another Harshad number. Write a program
to input a number and check whether it is a Multiple Harshad number
or not.
[When a number is divisible by the sum of its digit, it is called Harshad
number].
Sample Input: 6804
[Hint: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378
378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21
21 ⇒ 2+1 = 3 ⇒ 21/3 = 7]
Sample Output: Multiple Harshad Number
Prog. import [Link].*;
public class MultipleHarshad
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
int num, dividend, divisor, c, t, d;
[Link]("Enter a number: ");
num = [Link]( );
dividend = num;
c = 0;
while (dividend > 1)
{
divisor=0;
t = dividend;

82
while (t > 0)
{
d = t % 10;
divisor += d;
t /= 10;
}
if (dividend % divisor == 0 && divisor!= 1)
{
dividend = dividend / divisor;
c++;
}
else
break;
}
if (dividend == 1 && c > 1)
[Link](num + " is Multiple Harshad Number");
else
[Link](num + " is not Multiple Harshad Number");
}
}
Q.8 Write the programs to display the following patterns:
(a) 1
31
531
7531
97531
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 1; i < 10; i = i + 2)
{
for (j = i; j > 0; j = j – 2)
{
[Link](j + " ");
}
[Link]( );
}
}
}
(b) 1 2 3 4 5
6 7 8 9
10 11 12
13 14
15

Nested Loops 83
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, a = 1;
for (i = 5; i > 0; i– –)
{
for (j = 1; j <= i; j++)
{
[Link]((a++)+ "\t");
}
[Link]( );
}
}
}
(c) 15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i , j, a = 15;
for (i = 5; i > 0; i– –)
{
for (j = 1; j <= i; j++)
{
[Link]((a– –) + "\t");
}
[Link]( );
}
}
}
(d) 1
10
101
1010
10101
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, a = 1, b = 0;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)

84
{
if (j % 2 == 0)
[Link](b + " ");
else
[Link](a + " ");
}
[Link]( );
}
}
}
(e) 5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, k;
for (i = 0; i < 5; i++)
{
for (j = i; j > 0; j– –)
{
[Link](" ");
}
for (k = 5 – i; k > 0; k– –)
{
[Link]((5 – i) + " ");
}
[Link]( );
}
}
}
(f) 1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, k;
for (i = 1; i <= 5; i++)
{
for (j = 1; j < i; j++)
[Link](i + " ");

Nested Loops 85
for (k = i; k <= 5; k++)
[Link](k + " ");
[Link]( );
}
}
}
(g) *
* #
* # *
* # * #
* # * # *
Prog. public class Pattern
{
public static void main(String args[])
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
if (j % 2 == 0)
[Link]("# ");
else
[Link]("* ");
}
[Link]( );
}
}
}
(h) 5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 5; j >= i; j– –)
{
[Link](j + " ");
}
[Link]( );
}
}
}

86
(i)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, a = 1;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
[Link]((a++)+"\t");
}
[Link]( );
}
}
}
Q.9 Write a program to generate a triangle or an inverted triangle till n terms
based upon the user's choice.
Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice: 1
Enter the number of terms: 5
Sample Output:
1
22
333
4444
55555
Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice: 2
Enter the number of terms: 6
Sample Output:
666666
55555
4444
333
22
1

Nested Loops 87
Prog. import [Link].*;
public class Pattern
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j, n, ch;
[Link]("Type 1 for a triangle");
[Link]("Type 2 for an inverted triangle");
[Link]("Enter your choice: ");
ch = [Link]( );
[Link]("Enter the number of terms: ");
n = [Link]( );
switch (ch)
{
case 1:
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++)
{
[Link](i + " ");
}
[Link]( );
}
break;
case 2:
for (i = n; i > 0; i– –)
{
for (j = 1; j <= i; j++)
{
[Link](i + " ");
}
[Link]( );
}
break;
default:
[Link]("Incorrect Choice");
}
}
}
Q.10 Using the switch case statement, write a menu driven program for the
following:
(a) To input a number and display only those factors of the numbers
which are prime.
Sample Input: 84
Sample Output: 2, 3, 7
(b) A program that displays the multiplication table from 1 to 10, as shown:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30

88
……………………………………………..
……………………………………………..
……………………………………………..
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j, c, ch, num;
[Link]("Enter 1 for prime factors");
[Link]("Enter 2 for multiplication tables");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
[Link]("Enter a number: ");
num = [Link]( );
for(i = 2; i <= num/2; i++)
{
c = 0;
if(num % i == 0)
{
for (j = 1; j <= i; j++)
{
if(i % j == 0)
c++;
}
if(c == 2)
[Link](i + " ");
}
}
break;
case 2:
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= 10; j++)
[Link]((i * j) + " ");
[Link]( );
}
break;
default:
[Link]("Incorrect Choice!!");
}
}
}

Nested Loops 89
Chapter 2

Library Classes

VI. Write the purpose of the following functions:


1. [Link]( )
Ans. It is used to convert string data into float data.
2. [Link]( )
Ans. It is used to convert double data to a string.
3. [Link]( )
Ans. It is used to convert string data into the Integer wrapper object.
4. [Link]( )
Ans. It is used to check if the character given as its argument is a digit.
5. [Link]( )
Ans. It is used to check if the character given as its argument is a whitespace.
VII. Answer the following questions:
1. What is a package?
Ans. Package is a collection of classes such that each class includes different
built-in functions. For example, [Link], [Link], etc.
2. What is the significance of '*' while importing a package?
Ans. The asterisk(*) sign indicates that all the classes in the imported package
can be used in the program.
3. Define a wrapper class.
Ans. The wrapper class is a class that contains a primitive data type. Whenever
an object to a wrapper class is created, a field in memory is allocated to
contain a primitive data.
For example,
Integer is a wrapper class that contains primitive data type 'int' and the
following functions:
• [Link]( ): To convert a string into integer data type.
• [Link]( ): To convert an integer data type into string.
4. Differentiate between:
(a) isUpperCase( ) and toUpperCase( )
Ans. isUpperCase( ) toUpperCase( )
It is used to check whether the It is used to convert the character
character given as its argument is given as its argument to uppercase
in uppercase or not.
Its return type is boolean. Its return type is char.

90
(b) parseInt( ) and toString( ) functions
Ans. parseInt( ) toString( )
It converts a string to an integer. It converts an integer to a string.
Its return type is int. Its return type is String.
(c) primitive type and composite type data
Ans. Primitive Data Types Composite Data Types
Primitive data types are the Composite data types are created
fundamental data types in Java. by using primitive data types.
Primitive data types are built-in Composite data types are defined
data types defined by Java language by the programmer.
specification.
5. (a) int res = 'A';
What is the value of res?
Ans. The value of res is 65.
(b) Name the package that contains wrapper classes.
Ans. [Link]
(c) Write the prototype of a function check which takes an integer as
an argument and returns a character.
Ans. char check(int n)
VIII. Unsolved Java Programs on Character Manipulations:
Q.1 Write a program in Java to input a character. Find and display the next
10th character in the ASCII table.
Prog. import [Link].*;
public class Dis_Char
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a character: ");
char ch = [Link]( ).charAt(0);
char nextCh = (char)(ch + 10);
[Link]("Tenth character from " + ch + " is " + nextCh);
}
}
Q.2 Write a program in Java to generate all the alternate letters in the range
of letters from A to Z.
Prog. public class Dis_Letters
{
public static void main(String args[ ])
{
char ch;
for (ch = 'A'; ch <= 'Z'; ch = (char)(ch + 2))
[Link](ch);
}
}

Library Classes 91
Q.3 Write a program to input a set of 20 letters. Convert each letter into
uppercase. Find and display the number of vowels and number of
consonants present in the set of given letters.
Prog. import [Link].*;
public class Dis_Letters
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter any 20 letters:");
int vc = 0, cc = 0;
char ch;
for (int i = 0; i < 20; i++)
{
ch = [Link]( ).charAt(0);
ch = [Link](ch);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
vc++;
else if (ch >= 'A' && ch <= 'Z')
cc++;
}
[Link]("Number of Vowels = " + vc);
[Link]("Number of Consonants = " + cc);
}
}
Q.4 Write a program in Java to accept an integer number N such that
0 < N< 27. Display the corresponding letter of the English alphabet
(i.e., the letter at position N).
[Hint: If N =1 then display A]
Prog. import [Link].*;
public class Dis_Letter
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int n;
char ch;
[Link]("Enter an integer: ");
n = [Link]( );
if (n > 0 && n < 27)
{
ch = (char)(n + 64);
[Link]("Corresponding letter = " + ch);
}
else
[Link]("Enter a number in the range 1 to 26");
}
}

92
Q.5 Write a program to input two characters from the keyboard. Find the
difference (d) between their ASCII codes. Display the following messages:
If d=0 : both the characters are same.
If d<0 : ASCII value of first character is less than the second.
If d>0 : ASCII value of second character is more than the first.
Sample Input: D
P
Sample Output: d= (68–80) = –12
Prog. import [Link].*;
public class ASCIIDiff
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int d;
char ch1, ch2;
[Link]("Enter first character: ");
ch1 = [Link]( ).charAt(0);
[Link]("Enter second character: ");
ch2 = [Link]( ).charAt(0);
d = (int)ch1 – (int)ch2;
if (d > 0)
[Link]("Second character is smaller");
else if (d < 0)
[Link]("First character is smaller");
else
[Link]("Both the characters are same");
}
}
Q.6 Write a program to input a letter. Find its ASCII code. Reverse the ASCII
code and display the equivalent character.
Sample Input: Y
Sample Output: ASCII Code = 89
Reverse the code = 98
Equivalent character: b
Prog. import [Link].*;
public class ASCIIReverse
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, r, d;
char chr;
[Link]("Enter a letter: ");
chr = [Link]( ).charAt(0);
a = (int)chr;
[Link]("ASCII Code = " + a);
r = 0;
while (a > 0)

Library Classes 93
{
d = a % 10;
r = r * 10 + d;
a /= 10;
}
[Link]("Reversed Code = " + r);
[Link]("Equivalent character = " + (char)r);
}
}
Q.7 Write a program to input vowels in lowercase and display their ASCII
values.
Prog. import [Link].*;
public class ASCII
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a;
char ch;
[Link]("Enter vowels in lowercase:");
[Link]("Vowels ASCII Values");
for(a=1; a<=5; a++)
{
ch = [Link]( ).charAt(0);
[Link](ch +"\t\t" + (int)ch);
}
}
}
Q.8 Write a program to input a set of any 10 integer numbers. Find the sum
and product of the numbers. Join the sum and product to form a single
number. Display the concatenated number.
[Hint: Let sum=245 and product = 1346 then the number after joining
sum and product will be 2451346]
Prog. import [Link].*;
public class ValueConcat
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter any 10 integers:");
long sum = 0, prod = 1, cn;
int i, n;
String st;
for (i = 0; i < 10; i++)
{
n = [Link]( );
sum += n;

94
prod *= n;
}
st = [Link](sum) + [Link](prod);
cn = [Link](st);
[Link]("Sum = " + sum);
[Link]("Product = " + prod);
[Link]("Concatenated Number = " + cn);
}
}
Q.9 Write a menu driven program to generate the uppercase letters from ‘Z’
to ‘A’ and lowercase letters from ‘a’ to ‘z’ as per the user’s choice.
Enter ‘1’ to display uppercase letters from ‘Z’ to ‘A’ and Enter ‘2’ to
display lowercase letters from ‘a’ to ‘z’.
Prog. import [Link].*;
public class Letters
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int ch, c=0, i;
[Link]("Enter '1' to display uppercase letters from Z
to A");
[Link]("Enter '2' to display lowercase letters from a
to z");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
for (i = 90; i > 64; i– –)
{
char chr = (char)i;
[Link](chr);
[Link](" ");
c++;
//Print 10 characters per line
if (c == 10)
{
[Link]( );
c = 0;
}
}
break;
case 2:
for (i = 97; i < 123; i++)
{
char chr = (char)i;
[Link](chr);

Library Classes 95
[Link](" ");
c++;
//to display 10 characters per line
if (c == 10)
{
[Link]( );
c = 0;
}
}
break;
default:
[Link]("Incorrect Choice!!");
}
}
}
Q.10 Write a menu driven program to display
(i) first five uppercase letters
(ii) last five lowercase letters as per the user's choice.
Enter '1' to display uppercase letters and '2' to display lowercase letters.
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, ch;
[Link]("Enter '1' to display uppercase letters");
[Link]("Enter '2' to display lowercase letters");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
for (i = 65; i <= 69; i++)
[Link]((char)i);
break;
case 2:
for (i = 118; i <= 122; i++)
[Link]((char)i);
break;
default:
break;
}
}
}

96
Q.11 Using switch case statement, write a menu driven program to perform
the following tasks:
(a) To generate and print the letters from A to Z along with their Unicode.
Letters Unicode
A 65
B 66
…… ……..
…… ……..
Z 90
(b) To generate and print the letters from z to a along with their Unicode.
Letters Unicode
z 122
y 121
…… ……..
…… ……..
a 97
Prog. // To display the pattern as per the user's choice
import [Link].*;
public class Display_Pattern
{
public static void main(String args[ ])
{
Scanner in=new Scanner([Link]);
int k;
char ch;
String str;
[Link]("Enter 1 to display uppercase letters and the
'Unicode'");
[Link]("Enter 2 to display lowercase letters and the
'Unicode'");
[Link]("Enter your choice:");
k=[Link]( );
switch(k)
{
case 1:
[Link]("Letters\t\tUnicode");
for(ch='A'; ch<='Z'; ch++)
{
[Link](ch +"\t\t" + (int)ch);
}
break;
case 2:
[Link]("Letters\t\tUnicode");
for(ch='z'; ch>='a'; ch– –)
{
[Link](ch +"\t\t" + (int)ch);
}
break;

Library Classes 97
default:
[Link]("Entered wrong choice!!");
}
}
}
Q.12 Write a program in Java to display the following patterns:
(a) ABCDE
ABCD
ABC
AB
A
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, p;
for (i = 5; i >=1; i– –)
{
p=65;
for (j = 1; j <= i; j++)
{
[Link]((char)p);
p++;
}
[Link]( );
}
}
}

(b) A
B C
D E F
G H I J
K L M N O
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, p=65;
for (i = 1; i <=5; i++)
{
for (j = 1; j <= i; j++)
{
[Link]((char)p);
p++;
}
[Link]( );
}
}
}

98
(c) A B C D E
B C D E
C D E
D E
E
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, p=65, k=p;
for (i = 5; i >=1; i– –)
{
p=k;
for (j = 1; j <= i; j++)
{
[Link]((char)p);
p++;
}
k++;
[Link]( );
}
}
}
(d) A*B*C*D*E*
A*B*C*D*
A*B*C*
A*B*
A*
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for(i = 69; i >= 65; i– –)
{
for (j = 65; j <= i; j++)
{
[Link]((char)j + "*");
}
[Link]( );
}
}
}

Library Classes 99
(e) A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, p=65;
for (i = 1; i <=5; i++)
{
for (j = 1; j <= 5; j++)
{
[Link]((char)p);
}
[Link]( );
p++;
}
}
}
(f) A B C D E
ABCDA
ABCAB
ABABC
AAB C D
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, k, p;
for (i = 5; i >=1; i– –)
{
p=65;
for (j = 1; j <= i; j++)
{
[Link]((char)p);
p++;
}
int m=65;
for (k = 5; k >i; k– –)
{
[Link]((char)m);
m++;
}
[Link]( );
}
}
}

100
Q.13 Write a program in Java to generate a triangle or an inverted triangle till
n terms based upon the user's choice of the triangle to be displayed.
Pattern 1: Pattern 2:
Sample Output: Sample Output:
***** ABCDE
**** ABCD
*** ABC
** AB
* A
Sample Input: Enter 1 to display Pattern 1 and 2 to display Pattern 2
Enter your choice: 1 or 2
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int ch, c=0, i, j, k, p;
[Link]("Enter '1' to display Pattern 1");
[Link]("Enter '2' to display Pattern 2");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
for (i = 5; i >=1; i– –)
{
for (k = 5; k > i; k– –)
{
[Link](" ");
}
for (j = 1; j <= i; j++)
{
[Link]("*");
}
[Link]( );
}
break;
case 2:
for (i = 5; i >=1; i--)
{
p=65;
for (j = 1; j <= i; j++)
{
[Link]((char)p);
p++;
}
[Link]();

Library Classes 101


}
break;
default:
[Link]("Incorrect Choice!!");
}
}
}
Q.14 Write a menu driven program to perform the following operations as
per the user's choice:
(i) To print the value of c = a2 + 2 ab, where a varies from 1.0 to 20.0
with increment of 2.0 and b = 3.0 as a constant.
(ii) To display the following pattern using for loop:
A
AB
ABC
ABCD
ABCDE
Display proper message for an invalid choice.
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int ch, a, b = 3, c=0, i, j;
[Link]("Enter '1' to display the values of the series");
[Link]("Enter '2' to display Pattern");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
for (a = 1; a <=20; a=a+2)
{
c=a*a+2*a*b;
[Link]("When a = "+a+" : Value = "+c);
}
break;
case 2:
char chr='A';
[Link]("The pattern:");
for(i=chr; i<=(chr+4); i++)
{
for(j=chr; j<=i; j++)
{
[Link]((char)j);
}

102
[Link]( );
}
break;
default:
[Link]("Incorrect Choice!!");
}
}
}

Library Classes 103


Chapter 3

Arrays
(Single Dimensional and Double Dimensional)

V. Write short answers


1. What is meant by Dimensional Array?
Ans. A dimensional array is a structure created in the memory to represent
a number of values of the same data type with the variables having the
same variable name along with different subscripts.
2. Name the two types of Dimensional Array.
Ans. Two types of dimensional array are:
• Single Dimensional Array (SDA)
• Double Dimensional Array (DDA)
3. What is the need of Dimensional Array? Explain.
Ans. Generally, the variables are useful for keeping track of a single piece
of information. But, when we collect more and more information, the
variables become more in numbers and organising them in a proper
way becomes a complicated task. In such situations, we need arrays to
resolve the problems in a much better and efficient way.
4. 'Array is a composite data type'. Explain this statement.
Ans. The data type that represents a number of similar or different data under
a single declaration is called a composite data type. A dimensional array
is the concept of using a number of variables declared with the same
data type. This is the reason why a dimensional array is said to be a
composite data type.
5. Define the following with their constructs:
Ans. (a) Single Dimensional Array
A single dimensional array is a structure that is represented along
X-axis by using a number of variables with the same name having
different subscripts.
Syntax: <data type> <array-variable>[ ] = new <data type>[<size>];
(b) Double Dimensional Array
A double dimensional array is a structure that is represented along
X-axis and Y-axis, where X-axis represents number of rows and Y-axis
represents number of columns respectively.
Syntax: <data type> <array variable>[ ][ ] = new <data type>[<rows>]
[columns];
VI. Differentiate between the following
1. Subscript and Subscripted variable
Ans. Subscript is the index of the element in the array. Whereas, subscripted
variable is the name of the array and is used with a subscript to access
a single element of the array.

104
2. char a[5] and int a[5]
Ans. The char a[5] is an array of char data type that can hold 5 characters
whereas, int a[5] is an array of int data type that can hold 5 integer values.
3. Ordinary variable and array variable
Ans. An ordinary variable can hold only one value whereas, an array variable
refers to as a group of values of the same data type by using a subscript.
4. String a[5] and String a[ ]
Ans. The String a[5] is an array of String data type that can hold 5 strings
whereas, String a[ ] is an array of String data type that can hold unfixed
number of cells in the memory.
5. Sorting and Searching
Ans. Sorting Searching
Sorting means to arrange the Searching means to look for a
elements of the array in ascending target value in an array.
or descending order.
For example, Bubble sort and For example, Linear search and
Selection sort Binary search
6. Linear search and Binary search
Ans. Linear Search Binary Search
Linear search works on sorted and Binary search works on only sorted
unsorted arrays. arrays (ascending or descending).
Each element of the array is Array is successively divided into
checked against the target value two halves and then the target
until the element is found or end element is searched either in the
of the array is reached. first-half or in the second-half.
7. Selection sort and Bubble sort
Ans. Selection sort Bubble sort
It selects the smallest element from It compares adjacent elements
unsorted sub-array and swaps and swaps them, if they are in an
it with the left-most unsorted incorrect order.
element.
It performs lesser number of swaps It performs more number of swaps
to sort the same array relative to to sort the array.
bubble sort.
8. length and length( )
Ans. length length( )
It is an attribute used by Java It is a member method used by
arrays. String class.
It returns the length of an array i.e. It returns the number of characters
the number of elements stored in present in a string.
an array.

Arrays (Single Dimensional and Double Dimensional) 105


VII. Unsolved Java Programs on Single and Double Dimensional Arrays:
Q.1 Write a program in Java to store 20 numbers (even and odd numbers)
in a Single Dimensional Array (SDA). Calculate and display the sum of
all even numbers and all odd numbers separately.
Prog. import [Link].*;
public class Sum
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int arr[ ] = new int[20];
int i, sum_odd = 0, sum_even = 0;
[Link]("Enter 20 numbers:");
for (i = 0; i < 20; i++)
{
arr[i] = [Link]( );
}
for (i = 0; i < 20; i++)
{
if (arr[i] % 2 == 0)
sum_even += arr[i];
else
sum_odd += arr[i];
}
[Link]("Sum of odd numbers = " + sum_odd);
[Link]("Sum of even numbers = " + sum_even);
}
}
Q.2 Write a program in Java to declare an array of size twenty of double data
type.
Accept the elements into the array and perform the following:
• Calculate and print the product of all the elements.
• Print the square of each element.
Prog. import [Link].*;
public class Array
{
public static void main(String args[ ])
{
double ar[ ] = new double [4];
double prod = 1;
int i;
Scanner in = new Scanner([Link]);
for (i = 0; i < 4; i++)
{
[Link]("Enter the number ar[" + i + "]:");
ar[i] = [Link]( );
}
for (i = 0; i < 4; i++)

106
{
prod = prod * ar[i];
}
[Link]( );
[Link]("Product of array elements = "+prod);
[Link]( );
[Link]("Square of array elements:");
for (i = 0; i < 4; i++)
{
[Link](ar[i]*ar[i]);
}
}
}
Q.3 Write a program in Java to store 10 numbers (including positive and
negative numbers) in a Single Dimensional Array (SDA). Display all the
negative numbers followed by the positive numbers without changing
the order of the numbers.
Sample Input:
n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]
15 21 –32 –41 54 61 71 –19 –44 52
Sample Output: –32, –41, –19, –44, 15, 21, 54, 61, 71, 52
Prog. import [Link].*;
public class Numbers
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i;
int arr[ ] = new int[10];
[Link]("Enter 10 numbers:");
for (i = 0; i < 10; i++)
{
arr[i] = [Link]( );
}
for (i = 0; i < 10; i++)
{
if (arr[i] < 0)
[Link](arr[i] + ", ");
}
for (i = 0; i < 10; i++)
{
if (arr[i] >= 0)
[Link](arr[i] + ", ");
}
}
}

Arrays (Single Dimensional and Double Dimensional) 107


Q.4 Write a program in Java to store 20 numbers in a Single Dimensional
Array (SDA).
Display the numbers which are prime.
Sample Input:
n[0] n[1] n[2] n[3] n[4] n[5] ... n[16] n[17] n[18] n[19]
45 65 77 71 90 67 ... 82 19 31 52
Sample Output: 71, 67, …, 19, 31
Prog. import [Link].*;
public class Prime
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j, c;
int arr[ ] = new int[20];
[Link]("Enter 20 numbers:");
for (i = 0; i < 20; i++)
{
arr[i] = [Link]( );
}
[Link]("Prime Numbers:");
for (i = 0; i < 20; i++)
{
c = 0;
for (j = 1; j <= arr[i]; j++)
{
if (arr[i] % j == 0)
c++;
}
if (c == 2)
[Link](arr[i] + ", ");
}
}
}
Q.5 Write a program to accept name and total marks of N number of students
in two single subscript arrays name[ ] and totalmarks[ ].
Calculate and print:
(i) The average of the total marks obtained by N number of students.
[average = (sum of total marks of all the students)/N]
(ii) Deviation of each student's total marks with the average.
[deviation = total marks of a student – average]
Prog. import [Link].*;
public class Marks
{
public static void main(String args[ ])
{

108
Scanner in = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]( );
String name[ ] = new String[n];
int tmarks[ ] = new int[n];
int i, gtotal = 0;
double avg = 0;
for (i = 0; i < n; i++)
{
[Link]( );
[Link]("Enter name of student " + (i+1) + ": ");
name[i] = [Link]( );
[Link]("Enter total marks of student " + (i+1) + ": ");
tmarks[i] = [Link]( );
gtotal += tmarks[i];
}
avg = gtotal/(double)n;
[Link]("Average = " + avg);
for (i = 0; i < n; i++)
{
[Link]("Deviation for "+name[i]+" = " +(tmarks[i] – avg));
}
}
}
Q.6 Write a program in Java using arrays:
(a) To store the Roll No., Name and marks in six subjects for 100 students.
(b) Calculate the percentage of marks obtained by each candidate. The
maximum marks in each subject are 100.
(c) Calculate the Grade as per the given criteria:
Percentage Marks Grade
From 80 to 100 A
From 60 to 79 B
From 40 to 59 C
Less than 40 D
Prog. import [Link].*;
public class Grades
{
public static void main(String args[ ])
{
int ns = 100;
Scanner in = new Scanner([Link]);
int rollNo[ ] = new int[ns];
String name[ ] = new String[ns];
int s1[ ] = new int[ns];
int s2[ ] = new int[ns];
int s3[ ] = new int[ns];

Arrays (Single Dimensional and Double Dimensional) 109


int s4[ ] = new int[ns];
int s5[ ] = new int[ns];
int s6[ ] = new int[ns];
double p[ ] = new double[ns];
char g[ ] = new char[ns];
for (int i = 0; i < ns; i++)
{
[Link]("Enter student " + (i+1) + " details:");
[Link]("Roll No: ");
rollNo[i] = [Link]( );
[Link]( );
[Link]("Name: ");
name[i] = [Link]( );
[Link]("Marks in Subject 1: ");
s1[i] = [Link]( );
[Link]("Marks in Subject 2: ");
s2[i] = [Link]( );
[Link]("Marks in Subject 3: ");
s3[i] = [Link]( );
[Link]("Marks in Subject 4: ");
s4[i] = [Link]( );
[Link]("Marks in Subject 5: ");
s5[i] = [Link]( );
[Link]("Marks in Subject 6: ");
s6[i] = [Link]( );
p[i] = (((s1[i] + s2[i] + s3[i] + s4[i] + s5[i] + s6[i])/600.0)*100);
if (p[i] < 40)
g[i] = 'D';
else if (p[i] < 60)
g[i] = 'C';
else if (p[i] < 80)
g[i] = 'B';
else
g[i] = 'A';
}
[Link]( );
for (int i = 0; i < ns; i++)
{
[Link](rollNo[i]+"\t"+name[i]+"\t"+p[i]+"\t"+g[i]);
}
}
}
Q.7 Write a program to accept a list of 20 integers. Sort the first 10 numbers in
ascending order and the next 10 numbers in descending order by using
'Bubble Sort' technique. Finally, print the complete list of integers.

110
Prog. import [Link].*;
public class BubbleSort
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int arr[ ] = new int[20];
int i, j, t;
[Link]("Enter 20 numbers:");
for (i = 0; i < 20; i++)
{
arr[i] = [Link]( );
}
//to sort the first half in ascending order
for (i = 0; i < 20/2 – 1; i++)
{
for (j = 0; j < 20/2 – i – 1; j++)
{
if (arr[j] > arr[j + 1])
{
t = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = t;
}
}
}
//to sort the second half in descending order
for (i = 0; i < 20/2 – 1; i++)
{
for (j = 20/2; j < 20 – i – 1; j++)
{
if (arr[j] < arr[j + 1])
{
t = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = t;
}
}
}
//to display the sorted array
[Link]("\nSorted Array:");
for (i = 0; i < 20; i++)
{
[Link](arr[i] + " ");
}
}
}

Arrays (Single Dimensional and Double Dimensional) 111


Q.8 Write a program in Java to accept 20 numbers in a single dimensional
array arr[20]. Transfer and store all the even numbers in an array
even[ ] and all the odd numbers in another array odd[ ]. Finally, print
the elements of both the arrays.
Prog. import [Link].*;
public class EvenOdd
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i = 0, nc = 20;
int arr[ ] = new int[nc];
int even[ ] = new int[nc];
int odd[ ] = new int[nc];
[Link]("Enter 20 numbers:");
for (i = 0; i < nc; i++)
{
arr[i] = [Link]( );
}
int eIdx = 0, oIdx = 0;
for (i = 0; i < nc; i++)
{
if (arr[i] % 2 == 0)
even[eIdx++] = arr[i];
else
odd[oIdx++] = arr[i];
}
[Link]("Array containing even numbers:");
for (i = 0; i < eIdx; i++)
{
[Link](even[i] + " ");
}
[Link]("\nArray containing odd numbers:");
for (i = 0; i < oIdx; i++)
{
[Link](odd[i] + " ");
}
}
}
Q.9 Write a program to store 20 numbers in a Single Dimensional Array
(SDA). Now, display only those numbers that are perfect squares.

n[0] n[1] n[2] n[3] n[4] n[5] ... n[16] n[17] n[18] n[19]
12 45 49 78 64 77 ... 81 99 45 33
Sample Output: 49, 64, …, 81

112
Prog. import [Link].*;
public class Psquare
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int arr[ ] = new int[20];
int i;
[Link]("Enter 20 numbers:");
for (i = 0; i < 20; i++)
{
arr[i] = [Link]( );
}
[Link]("Perfect Squares are:");
for (i = 0; i < 20; i++)
{
double sr = [Link](arr[i]);
if ((sr – [Link](sr)) == 0)
[Link](arr[i] + ", ");
}
}
}
Q.10 To get promotion in a Science stream, a student must pass in English
and should pass in any of the two subjects (i.e.; Physics, Chemistry or
Maths). The passing marks in each subject is 35. Write a program in a
Single Dimension Array to accept the roll numbers and marks secured in
the subjects for all the students. The program should check and display
the roll numbers along with a message whether "Promotion is Granted"
or "Promotion is not Granted". Assume that there are 40 students in the
class.
Prog. import [Link].*;
public class Science
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int ns[] = new int[200]; //40 * 5 = 200
int i, idx;
[Link]("Enter student details");
for (i = 0, idx = 1; i < 200; i = i + 5, idx++)
{
[Link]("Enter Roll No.: ");
ns[i] = [Link]( );
[Link]("Student: " + idx + " Enter English marks: ");
ns[i+1] = [Link]( );
[Link]("Student: " + idx + " Enter Maths marks: ");
ns[i+2] = [Link]( );
[Link]("Student: " + idx + " Enter Physics marks: ");

Arrays (Single Dimensional and Double Dimensional) 113


ns[i+3] = [Link]( );
[Link]("Student: " + idx + " Enter Chemistry marks: ");
ns[i+4] = [Link]( );
}
for (i = 0; i < 200; i = i + 5)
{
[Link]("Roll No: " + ns[i]);
if (ns[i+1] > 34 &&
((ns[i+2] > 34 && ns[i+3] > 34) ||
(ns[i+2] > 34 && ns[i+4] > 34) ||
(ns[i+3] > 34 && ns[i+4] > 34)))
{
[Link]("Promotion granted");
}
else
{
[Link]("Promotion not granted");
}
}
}
}
Q.11 The annual examination result of 50 students in a class is tabulated in a
Single Dimensional Array (SDA) is as follows:

Roll No. Subject A Subject B Subject C


....... ....... ....... .......
....... ....... ....... .......
....... ....... ....... .......
Write a program to read the data, calculate and display the following:
(a) Average marks obtained by each student.
(b) Print the roll number and the average marks of the students whose
average is above. 80.
(c) Print the roll number and the average marks of the students whose
average is below 40.
Prog. import [Link].*;
public class Exam
{
public static void main(String args[ ])
{
int i, ns = 50;
Scanner in = new Scanner([Link]);
int rollNo[ ] = new int[ns];
int sub1[ ] = new int[ns];
int sub2[ ] = new int[ns];
int sub3[ ] = new int[ns];
double avg[ ] = new double[ns];
for (i = 0; i < ns; i++)

114
{
[Link]("Enter student " + (i+1) + " details:");
[Link]("Roll No: ");
rollNo[i] = [Link]( );
[Link]("Subject A Marks: ");
sub1[i] = [Link]( );
[Link]("Subject B Marks: ");
sub2[i] = [Link]( );
[Link]("Subject C Marks: ");
sub3[i] = [Link]( );
avg[i] = (sub1[i] + sub2[i] + sub3[i])/3.0;
}
[Link]("\nRoll No\tAverage Marks");
for (i = 0; i < ns; i++)
{
[Link](rollNo[i] + "\t" + avg[i]);
}
[Link]("\nStudents with average above 80:");
for (i = 0; i < ns; i++)
{
if (avg[i] > 80)
[Link](rollNo[i] + "\t" + avg[i]);
}
[Link]("\nStudents with average below 40:");
for (i = 0; i < ns; i++)
{
if (avg[i] < 40)
[Link](rollNo[i] + "\t" + avg[i]);
}
}
}
Q.12 Write a program to store 6 elements in an array P and 4 elements in an
array Q. Now, produce a third array R, containing all the elements of
arrays P and Q. Display the resultant array.
Input Input Output
P[ ] Q[ ] R[ ]
4 19 4
6 23 6
1 7 1
2 8 2
3 3
10 10
19
23
7
8

Arrays (Single Dimensional and Double Dimensional) 115


Prog. import [Link].*;
public class Arrays
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int P[ ] = new int[6];
int Q[ ] = new int[4];
int R[ ] = new int[10];
int i, j;
[Link]("Enter 6 elements of array P:");
for (i = 0; i < [Link]; i++)
{
P[i] = [Link]( );
}
[Link]("Enter 4 elements of array Q:");
for (i = 0; i < [Link]; i++)
{
Q[i] = [Link]( );
}
i = 0;
while(i < [Link])
{
R[i] = P[i];
i++;
}
j = 0;
while(j < [Link])
{
R[i++] = Q[j++];
}
[Link]("Elements of Array R:");
for (i = 0; i < [Link]; i++)
{
[Link](R[i] + " ");
}
}
}
Q.13 Write a program to accept the year of graduation from school as an
integer value from the user. Using the binary search technique on the
sorted array of integers given below, output the message "Record exists"
and the position, if the input value is located in the array. If not, output
the message "Record does not exist".
Sample Input:
n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]
1982 1987 1993 1996 1999 2003 2006 2007 2009 2010

116
Prog. import [Link].*;
public class Year
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int n[] = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};
[Link]("Enter graduation year to search: ");
int year = [Link]( );
int low = 0, high = [Link] – 1, idx = –1;
while (low<= high)
{
int m = (low + high)/2;
if (n[m] == year)
{
idx = m;
break;
}
else if (n[m] < year)
{
low = m + 1;
}
else
{
high = m – 1;
}
}
if (idx == –1)
[Link]("Record does not exist");
else
[Link]("Record exists at position:"+(idx + 1));
}
}
Q.14 Write a program to input and store roll numbers, names and marks in 3
subjects of n number of students in five single dimensional arrays and
display the remark based on average marks as given below:

Average Marks Remark


85–100 Excellent
75–84 Distinction
60–74 First Class
40–59 Pass
Less than 40 Poor
Prog. import [Link].*;
public class AvgMarks
{

Arrays (Single Dimensional and Double Dimensional) 117


public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int n, i;
[Link]("Enter number of students: ");
n = [Link]( );
int rollNo[ ] = new int[n];
String name[ ] = new String[n];
int s1[ ] = new int[n];
int s2[ ] = new int[n];
int s3[ ] = new int[n];
double avg[ ] = new double[n];
for (i = 0; i < n; i++)
{
[Link]("Enter student " + (i+1) + " details:");
[Link]("Roll No: ");
rollNo[i] = [Link]( );
[Link]( );
[Link]("Name: ");
name[i] = [Link]( );
[Link]("Subject 1 Marks: ");
s1[i] = [Link]( );
[Link]("Subject 2 Marks: ");
s2[i] = [Link]( );
[Link]("Subject 3 Marks: ");
s3[i] = [Link]( );
avg[i] = (s1[i] + s2[i] + s3[i])/3.0;
}
[Link]("Roll No\tName\tRemark");
for (i = 0; i < n; i++)
{
String rm;
if (avg[i] < 40)
rm = "Poor";
else if (avg[i] < 60)
rm = "Pass";
else if (avg[i] < 75)
rm = "First Class";
else if (avg[i] < 85)
rm = "Distinction";
else
rm = "Excellent";
[Link](rollNo[i] + "\t" + name[i] + "\t" + rm);
}
}
}

118
Q.15 A double dimensional array is defined as dd[4][4] to store numbers. Write
a program to find the sum of all even numbers and product of all odd
numbers of the elements stored in Double Dimensional Array (DDA).
Sample Input:

12 10 15 17
30 11 32 71
17 14 29 31
41 33 40 51
Sample Output:
Sum of all even numbers: 138
Product of all odd numbers: 210023455742595
Prog. import [Link].*;
public class DDAEvenOdd
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j;
int dd[ ][ ] = new int[4][4];
int evenSum = 0;
long oddProd = 1;
[Link]("Enter the elements of 4x4 DDA: ");
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
dd[i][j] = [Link]( );
if (dd[i][j] % 2 == 0)
evenSum += dd[i][j];
else
oddProd *= dd[i][j];
}
}
[Link]("Sum of all even numbers = " + evenSum);
[Link]("Product of all odd numbers = " + oddProd);
}
}
Q.16 A departmental shop has 5 stores and 6 departments. The monthly sale
of the department is kept in the Double Dimensional Array (DDA) as
m[5][6]. The manager of the shop wants to know the total monthly sale of
each store and each department at any time. Write a program to perform
the given task.
[Hint: Number of stores as rows and Number of departments as columns.]

Arrays (Single Dimensional and Double Dimensional) 119


Prog. import [Link].*;
public class Store
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
long m[ ][ ] = new long[5][6];
int i, j;
for (i = 0; i < 5; i++)
{
[Link]("Store " + (i + 1) + " Sales");
for (j = 0; j < 6; j++)
{
[Link]("Enter monthly sale of department " + (j + 1) + ": ");
m[i][j] = [Link]( );
}
}
[Link]("\nMonthly Sale by store: ");
for (i = 0; i < 5; i++)
{
long storeSale = 0;
for (j = 0; j < 6; j++)
{
storeSale += m[i][j];
}
[Link]("Store " + (i + 1) + " Sales: " + storeSale);
}
[Link]("\nMonthly Sale by Department: ");
for (i = 0; i < 6; i++)
{
long deptSale = 0;
for (j = 0; j < 5; j++)
{
deptSale += m[j][i];
}
[Link]("Department " + (i + 1) + " Sales: " + deptSale);
}
}
}
Q.17 A metropolitan hotel has 5 floors and 10 rooms in each floor. The names
of the visitors are entered in a Double Dimensional Array (DDA) as
M[5][10].The Hotel Manager wants to know from the "Enquiry" about
the position of a visitor (i.e., floor number and room number) as soon
as he enters the name of the visitor. Write a program in Java to perform
the above task.
Prog. import [Link].*;
public class Hotel
{

120
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String M[ ][ ] = new String[5][10];
int i = 0, j = 0;
for (i = 0; i < 5; i++)
{
[Link]("Enter floor " + (i + 1) + " guest details:");
for (j = 0; j < 10; j++)
{
[Link]("Guest in room " + (j + 1) + ": ");
M[i][j] = [Link]( );
}
}
boolean found = false;
[Link]("\nEnter guest name to search: ");
String guest = [Link]( );
for (i = 0; i < 5; i++)
{
for (j = 0; j < 10; j++) {
if (M[i][j].equals(guest))
{
found = true;
break;
}
}
if (found)
break;
}
if (found)
[Link](guest + " is in room number "+ (j + 1) + " on
floor number " + (i + 1));
else
[Link](guest + " is not staying in this hotel");
}
}
Q.18 A class teacher wants to keep the records of 40 students of her class
along with their names and marks obtained in English, Hindi, Maths,
Science and Computer Science in a Double Dimensional Array (DDA)
as M[40][5]. When the teacher enters the name of a student as an input,
the program must display the name, marks obtained in the 5 subjects
and the total. Write a program in Java to perform the task.
Prog. import [Link].*;
public class Record
{
public static void main(String args[ ])
{
int ns = 40;

Arrays (Single Dimensional and Double Dimensional) 121


int nsub = 5;
String sub_nm[ ] = {"English","Hindi","Maths","Science","Computer
Science"};
Scanner in = new Scanner([Link]);
String names[ ] = new String[ns];
int marks[ ][ ] = new int[ns][nsub];
int i = 0, j = 0;
for (i = 0; i < ns; i++)
{
[Link]("Student " + (i + 1) + " details:");
[Link]("Name: ");
names[i] = [Link]( );
for (j = 0; j < nsub; j++)
{
[Link]("Enter marks in " + sub_nm[j] + ": ");
marks[i][j] = [Link]( );
}
[Link]( );
}
[Link]("\nEnter name of the student to search: ");
String stu_nm = [Link]( );
for (i = 0; i < ns; i++)
{
if (names[i].equals(stu_nm))
break;
}
if (i == ns)
{
[Link]("Record for " + stu_nm + " not found");
}
else
{
[Link]("Name: " + names[i]);
int total = 0;
for (j = 0; j < nsub; j++)
{
[Link]("Marks in " + sub_nm[j] + ": " + marks[i][j]);
total += marks[i][j];
}
[Link]("Total Marks: " + total);
}
}
}
Q.19 If arrays M and M + N are as shown below, write a program in Java to
find the array N.
–1 0 2 –6 9 4
M= –3 –1 6 M+N= 4 5 0
4 3 –1 1 –2 –3

122
Prog. public class Find
{
public static void main(String args[ ])
{
int arrM[ ][ ] = {{–1, 0, 2},{–3, –1, 6},{4, 3, –1}};
int arrSum[ ][ ] = {{–6, 9, 4},{4, 5, 0},{1, –2, –3}};
int arrN[ ][ ] = new int[3][3];
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
arrN[i][j] = arrSum[i][j] – arrM[i][j];
}
}
[Link]("Array N:");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
[Link](arrN[i][j]);
[Link](' ');
}
[Link]( );
}
}
}
Q.20 Write a program in Java to store the numbers in a 4*4 matrix in a Double
Dimensional Array by using an input statement. Now, perform the
following tasks:
(a) Display the matrix elements.
(b) Find and display the largest and the smallest elements of the array.
(c) Difference between the largest and the smallest elements of the array.
Sample output:
The matrix elements are:
14 20 18 34
12 42 55 38
65 10 25 46
81 72 40 72
The smallest element in the array : 10
The largest element in the array : 81
Difference between the largest and the smallest elements : 71
Prog. import [Link].*;
public class ddMax_Min
{
public static void main(String args [ ])
{
Scanner in=new Scanner([Link]);

Arrays (Single Dimensional and Double Dimensional) 123


int i,j,min,max;
min=0;max=0;
int m[ ][ ]=new int[4][4];
[Link]("Enter the elements in the matrix");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
m[i][j]=[Link]( );
}
[Link]("Elements of the matrix are:");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
[Link](m[i][j]+" ");
}
[Link]( );
}
min=m[0][0];
max=m[0][0];
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(min>m[i][j])
min=m[i][j];
if(max<m[i][j])
max=m[i][j];
}
}
[Link]("Smallest element in the array is "+min);
[Link]("Largest element in the array is "+max);
[Link]("Difference between the smallest and largest is
"+(max–min));
}
}

124
Chapter 4

String Handling

VI. Differentiate between the following:


1. equals( ) and ==
equals( ) ==
It is a method. It is a relational operator.
It is used to check whether two It is used to check whether the
strings are same or not. values of two variables are equal
or not.

2. compareTo( ) and equals( )


compareTo( ) equals( )
It compares two strings It checks whether the contents of
lexicographically. two strings are same or not.
The result is a negative, positive The result is true if the contents are
or zero depending on the String same otherwise, it is false.
argument.

3. toLowerCase( ) and toUpperCase( )

toLowerCase( ) toUpperCase( )
Converts all the letters of the String Converts all the letters of the String
object to lowercase. object to uppercase.
ASCII values of lowercase letters ASCII values of uppercase letters
are higher than the uppercase are lower than the lowercase
letters. letters.

4. charAt( ) and substring( )


charAt( ) substring( )
It returns a character from the It extracts a part of the string as
string at the index specified as its specified by its arguments and
argument. returns the extracted part as a new
string.
Its return type is char. Its return type is String.

VII. Write short answers:


1. What is exception? Name two exception handling blocks.
Ans. An exception is an event which occurs during the execution of a program.
It disrupts the normal flow of the program's instructions. Two exception
handling blocks are try and catch.

125
2. State the purpose and return data type of the following String functions:
Ans. (a) indexOf( )
It returns the index within the string of the first occurrence of the
specified character and –1, if the character is not present. Its return
type is int.
(b) compareTo( )
It compares two strings lexicographically. Its return type is int.
3. Write a statement for each to perform the following task on a string:
(i) Extract the second last character of a word stored in the variable wd.
Ans. char ch = [Link]([Link]( ) – 2);
(ii) Check if the second character of a string str is in uppercase.
Ans. boolean res = [Link]([Link](1));
4. Write a statement each to perform the following task on a string:
(i) Find and display the position of the last space in a string s.
Ans. [Link]([Link](' '));
(ii) Convert a number stored in a string variable x to double data type.
Ans. double a = [Link](x);
5. How does endsWith( ) and startsWith( ) differ? Explain with an example.
Ans. The endsWith( ) checks whether the string object ends with the string
specified as its argument or not. Whereas, the startsWith( ) checks
whether the string object starts with the string specified as its argument
or not.
For example,
public class Example
{
public static void main(String args[ ])
{
String str = "ICSE Computer Applications";
[Link]([Link]("ICSE"));
[Link]([Link]("tions"));
}
}
Here, str starts with "ICSE" and ends with "tions". Thus, it will result in
true.
VIII. Describe the purpose of the following functions with their syntax:
1. toUpperCase( )
Ans. It converts a string into uppercase characters. If any character is already
in uppercase or is a special character then it will remain same.
Syntax: String <variable> = <string_variable>.toUpperCase( );
2. trim( )
Ans. It removes all the leading and trailing space from the string.
Syntax: String <variable> = <string_variable>.trim( );
3. toLowerCase( )
Ans. It converts a string into lowercase characters. If any character is already
in lowercase or is a special character then it will remain same.
Syntax: String <variable> = <string_variable>.toLowerCase( );

126
4. length( )
Ans. It returns the length of the string i.e. the number of characters present
in the string.
Syntax: int <variable> = <string_variable>.length( );
5. replace( )
Ans. It replaces a character with another character or a substring with another
substring at all of its occurrences in the given string.
Syntax: String <variable> = <string_variable>.replace(<character or
substring to replace>, <new character or substring>);
6. compareTo( )
Ans. It compares two strings lexicographically.
Syntax: int <variable> = <string_variable>.compareTo(<string_variable2>);
7. reverse( )
Ans. It is a method of StringBuffer class used to reverse the sequence of
characters.
Syntax: <StringBuffer variable>.reverse( );
8. indexOf( )
Ans. It returns the index within the string of the first occurrence of the specified
character and –1, if the character is not present.
Syntax: int <variable> = <string_variable>.indexOf(<character>);
9. startWith( )
Ans. It checks whether the string object starts with the string specified as its
argument or not.
Syntax: boolean <variable> = <string_variable>.startWith(<string>);
10. equalsIgnoreCase( )
Ans. It ignores the case of the characters and checks whether the contents of
two strings are same or not.
Syntax: boolean <variable> = <string_variable>.equalsIgnoreCase (<string>);
IX. Unsolved Java Programs on Strings:
Q.1 Write a program to input a sentence. Find and display the following:
(i) Number of words present in the sentence
(ii) Number of letters present in the sentence
Assume that the sentence neither includes any digit nor any special
character.
Prog. import [Link].*;
public class Count
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a sentence:");
String str = [Link]( );
int wc = 0, c = 0, p, i;
p = [Link]( );
for (i = 0; i < p; i++)

String Handling 127


{
char ch = [Link](i);
if (ch == ' ')
wc++;
else
c++;
}
wc++;
[Link]("No. of words = " + wc);
[Link]("No. of letters = " + c);
}
}
Q.2 Write a program in Java to accept a word/a string and display the new
string after removing all the vowels present in it.
Sample Input: COMPUTER APPLICATIONS
Sample Output: CMPTR PPLCTNS
Prog. import [Link].*;
public class RVowels
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String str, newStr = "";
int i, p;
[Link]("Enter a word or sentence:");
str = [Link]( );
p= [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link]([Link](i));
if (ch == 'A' ||ch == 'E' ||ch == 'I' ||ch == 'O' ||ch == 'U')
{
continue;
}
newStr = newStr + ch;
}
[Link]("String after removing vowels:");
[Link](newStr);
}
}
Q.3 Write a program in Java to enter a string/sentence and display the longest
word and the length of the longest word present in the string.
Sample Input: "TATA FOOTBALL ACADEMY WILL PLAY AGAINST
MOHAN BAGAN"
Sample Output: The longest word: FOOTBALL: The length of the word: 8

128
Prog. import [Link].*;
public class Longest
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, p;
String str, word = "", longwd = "";
[Link]("Enter a sentence:");
str = [Link]( );
str += " "; //Add space at the end of string
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (ch == ' ')
{
if ([Link]( ) > [Link]( ))
longwd = word;
word = "";
}
else
{
word += ch;
}
}
[Link]("The longest word: " + longwd);
[Link]("Length of the word: " + [Link]( ));
}
}
Q.4 Write a program in Java to accept a string in upper case and replace all
the vowels present in the string with Asterisk (*) sign.
Sample Input: "TATA STEEL IS IN JAMSHEDPUR"
Sample output: T*T* ST**L *S *N J*MSH*DP*R
Prog. import [Link].*;
public class ReplaceVowels
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, p;
String str, newStr = "";
[Link]("Enter a string in uppercase:");
str = [Link]( );
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link](i);

String Handling 129


if (ch == 'A' ||ch == 'E' ||ch == 'I' ||ch == 'O' ||ch == 'U')
newStr = newStr + '*';
else
newStr = newStr + ch;
}
[Link](newStr);
}
}
Q.5 Write a program in Java to enter a sentence. Frame a word by joining all
the first characters of each word of the sentence. Display the word.
Sample Input: Vital Information Resource Under Seize
Sample Output: VIRUS
Prog. import [Link].*;
public class FrameWord
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String str, word;
int i, p;
[Link]("Enter a sentence:");
str = [Link]( );
word = "" + [Link](0);
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (ch == ' ')
word += [Link](i+1);
}
[Link](word);
}
}
Q.6 Write a program in Java to enter a sentence. Display the words which
are only palindrome.
Sample Input: MOM AND DAD ARE NOT AT HOME
Sample Output: MOM
DAD
Prog. import [Link].*;
public class PalinWords
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j, p, wdln;
String str, word = "";
[Link]("Enter a sentence:");

130
str = [Link]( );
str = [Link]( ) + " ";
p = [Link]( );
[Link]("Palindrome Words:");
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (ch == ' ')
{
wdln = [Link]( );
boolean isPalin = true;
for (j = 0; j < wdln/2; j++)
{
if ([Link](j) != [Link](wdln – 1 – j))
{
isPalin = false;
break;
}
}
if (isPalin)
[Link](word);
word = "";
}
else
word += ch;
}
}
}
Q.7 Write a program to accept a sentence. Display the sentence in reversing
order of its words.
Sample Input: Computer is Fun
Sample Output: Fun is Computer
Prog. import [Link].*;
public class ReverseWords
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a sentence:");
int i, p;
String str, word = "";
str = [Link]( );
str = " " + str;
p = [Link]( );
for (i = p – 1; i >= 0; i– –)
{
char ch = [Link](i);
if (ch == ' ')

String Handling 131


{
[Link](word + " ");
word = "";
}
else
word = ch + word;
}
}
}
Q.8 Write a program to input a sentence and display the word of the sentence
that contains maximum number of vowels.
Sample Input: HAPPY NEW YEAR
Sample Output: The word with maximum number of vowels: YEAR
Prog. import [Link].*;
public class MaxVowel
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, p, c=0, maxc=0;
String str, word = "", mWord = "";
[Link]("Enter a sentence:");
str = [Link]( );
str = str + " ";
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link]([Link](i));
if (ch == 'A' ||ch == 'E' ||ch == 'I' ||ch == 'O' ||ch == 'U')
{
c++;
}
if (ch == ' ')
{
if (c > maxc)
{
maxc = c;
mWord = word;
}
word = "";
c = 0;
}
else
word += ch;
}
[Link]("Word with maximum number of vowels: " + mWord);
}
}

132
Q.9 Consider the sentence as given below:
Blue bottle is in Blue bag lying on Blue carpet
Write a program to assign the given sentence to a string variable. Replace
the word Blue with Red at all its occurrence without using built-in
function.
Display the new string as shown below:
Red bottle is in Red bag lying on Red carpet
Prog. public class Replace
{
public static void main(String args[ ])
{
String str, newStr = "", word = "", target = "Blue", nword = "Red";
str = "Blue bottle is in Blue bag lying on Blue carpet";
str += " ";
int i, p;
p = [Link]( );
[Link]("Given String:");
[Link](str);
[Link]( );
[Link]("New string after replacing 'Blue' with 'Red':");
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (ch == ' ')
{
if ([Link](word))
{
newStr = newStr + nword + " ";
}
else
{
newStr = newStr + word + " ";
}
word = "";
}
else
{
word += ch;
}
}
[Link](newStr);
}
}
Q.10 Write a program to accept a word and convert it into lowercase, if it is
in uppercase. Display the new word by replacing only the vowels with
the letter following it.
Sample Input: computer
Sample Output: cpmpvtfr

String Handling 133


Prog. import [Link].*;
public class VReplace
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, p;
String str, newStr = "";
[Link]("Enter a word: ");
str = [Link]( );
str = [Link]( );
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if ([Link](i) == 'a' ||[Link](i) == 'e' ||[Link](i) == 'i' ||
[Link](i) == 'o' ||[Link](i) == 'u')
{
char nextChar = (char)(ch + 1);
newStr = newStr + nextChar;
}
else
newStr = newStr + ch;
}
[Link](newStr);
}
}
Q.11 Write a program to input a sentence and convert it into uppercase and
count and display the total number of words starting with letter 'A'.
Sample Input: advancement and application of information technology
are ever changing
Sample Output: ADVANCEMENT AND APPLICATION OF
INFORMATION TECHNOLOGY ARE EVER CHANGING
Total number of words starting with letter 'A' = 4
Prog. import [Link].*;
public class Count
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, c=0, p;
String str, str1, str2;
[Link]("Enter a sentence:");
str = [Link]( );
str1 = [Link]( );
[Link]("String in uppercase:");
[Link](str1+"\n");
str2 = " " + str1;

134
p = [Link]( );
for (i = 0; i <p; i++)
{
if(([Link](i)==' ') && ([Link](i+1)=='A'))
c++;
}
[Link]("Total number of words starting with letter 'A': " +c);
}
}
Q.12 Write a program to input a sentence and convert it into uppercase and
display each word in a separate line.
Sample Input : India is my country
Sample Output : INDIA
IS
MY
COUNTRY
Prog. import [Link].*;
public class Display
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, p;
String str, str1, str2, str3="";
[Link]("Enter a sentence:");
str = [Link]( );
str1 = [Link]( );
[Link]("String in uppercase:");
[Link](str1+"\n");
str2 = str1+ " ";
p = [Link]( );
[Link]("Each word in a seperate line shown as:");
for (i = 0; i <p; i++)
{
if([Link](i)!=' ')
str3 = str3 + [Link](i);
else
{
[Link](str3);
str3 = "";
}
}
}
}

String Handling 135


Q.13 Write a program to accept two strings and convert them into uppercase.
Check whether both the strings are equal or not. If they are not equal,
print the string with the highest length or print the message "Both the
strings are of equal length".
For example,
Enter first string: Computer Science
Enter second string: Computer Applications
Strings with the highest length: COMPUTER APPLICATIONS
Prog. import [Link].*;
public class Display
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int p1, p2;
String str1, str2;
[Link]("Enter first string:");
str1 = [Link]( );
str1 = [Link]( );
[Link]("Enter second string:");
str2 = [Link]( );
str2 = [Link]( );
if ([Link](str2))
[Link]("Both the strings are equal length");
else
{
p1 = [Link]( );
p2 = [Link]( );
if (p1>p2)
[Link]("String with the highest length:"+str1);
else
[Link]("String with the highest length:"+str2);
}
}
}
Q.14 Write a program to accept two strings of same length. Form a new word
in such a way that the first character of the first word is followed by the
first character of the second word and so on.
For example,
Input string 1: BALL
Input string 2: WORD
Sample Output: BWAOLRLD
Prog. import [Link].*;
public class Display
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);

136
int p, i;
String str1, str2, nstr = "";
char ch1, ch2;
[Link]("Enter first string:");
str1 = [Link]( );
str1 = [Link]( );
[Link]("Enter second string:");
str2 = [Link]( );
str2 = [Link]( );
p = [Link]( );
for (i = 0; i< p; i++)
{
ch1 = [Link](i);
ch2 = [Link](i);
nstr = nstr+ch1+ch2;
}
[Link]("New String:"+nstr);
}
}
Q.15 Write a program to input a sentence. Count and display the frequency
of each letter of the sentence in alphabetical order.
Sample Input: COMPUTER APPLICATIONS
Sample Output:
Character Frequency Character Frequency
A 2 O 2
C 2 P 3
E 1 R 1
I 2 S 1
L 1 T 2
M 1 U 1
N 1
Prog. import [Link].*;
public class Letters
{
public static void main(String args[ ] )
{
int i,j,p,c=0;
String str;
char ch=0;
Scanner in = new Scanner([Link]);
[Link]("Enter a string in uppercase");
str=[Link]( );
str= [Link]( );
p=[Link]( );
[Link]("Frequency of the letters in order:");

String Handling 137


[Link]("Alphabet : Frequency");
for(i=65; i<=90; i++)
{
c=0;ch=0;
for(j=0;j<p;j++)
{
ch=[Link](j);
if(ch==(char)i)
c=c+1;
}
if(c!=0)
[Link]((char)i+"\t\t"+c);
}
}
}
Q.16 Write a program to accept a string. Convert the string into uppercase
letters. 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
Prog. import [Link].*;
public class Double_Letters
{
public static void main(String args[ ])
{
Scanner in=new Scanner([Link]);
String str;
int i, p, count=0;
char chr1, chr2;
[Link]("Enter a sentence:");
str=[Link]( );
str=[Link]( );
[Link]("Sentence in uppercase:"+str);
p=[Link]( );
for(i=0;i<p–1;i++)
{
chr1=[Link](i);
chr2=[Link](i+1);
if(chr1==chr2)
count++;
}
[Link]("Number of words with double letters : "+count);
}
}

138
Q.17 Special words are those words which start and end with the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to
right and vice-versa.
Example: MALYALAM, MADAM, LEVEL, ROTATOR, CIVIC
All palindromes are special words but all special words are not
palindromes.
Write a program to accept a word. Check and display whether the word
is palindrome or only a special word or none of them.
Prog. import [Link].*;
public class SplPalin
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String str;
int i, p;
[Link]("Enter a word: ");
str = [Link]( );
str = [Link]( );
p = [Link]( );
if ([Link](0) == [Link](p – 1))
{
boolean isPalin = true;
for (i = 1; i < p/2; i++)
{
if ([Link](i) != [Link](p – 1 – i))
{
isPalin = false;
break;
}
}
if (isPalin)
[Link]("Palindrome");
else
[Link]("Special Word");
}
else
[Link]("Neither Special nor Palindrome");
}
}
Q.18 Write a program to input a sentence. Convert the sentence into uppercase
letters. Display the words along with frequency of the words which have
at least a pair of consecutive letters.
Sample Input: MODEM IS AN ELECTRONIC DEVICE
Sample Output:
MODEM
DEVICE
Number of words containing consecutive letters: 2

String Handling 139


Prog. import [Link].*;
public class Words
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String str, word;
int i, j, p, c=0;
[Link]("Enter a string: ");
str = [Link]( );
str = [Link]( );
str += " ";
word = "";
p = [Link]( );
for (i = 0; i < p; i++)
{
if ([Link](i) == ' ')
{
int wdlen = [Link]( );
for (j = 0; j < wdlen – 1; j++)
{
if ([Link](j) + 1 == [Link](j + 1))
{
c++;
[Link](word);
break;
}
}
word = "";
}
else
word += [Link](i);
}
[Link]("Number of words having consecutive letters: " + c);
}
}
Q.19 Write a program to accept a word (say, BLUEJ) and display the pattern:
(a) B L U E J
BLUE
BLU
BL
B
Prog. import [Link].*;
public class Pattern
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);

140
String word;
int i, j, p;
char chr;
[Link]("Enter a word: ");
word = [Link]( );
p = [Link]( );
for (i = p – 1; i >= 0; i– –)
{
for (j = 0; j <= i; j++)
{
chr = [Link](j);
[Link](chr);
}
[Link]( );
}
}
}
(b) J
E E
U U U
L L L L
B B B B B
Prog. import [Link].*;
public class Pattern
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String word;
int i, j, p;
char chr;
[Link]("Enter a word: ");
word = [Link]( );
p = [Link]( );
for (i = p – 1; i >= 0; i– –)
{
for (j = p – 1; j >= i; j– –)
{
chr = [Link](i);
[Link](chr);
}
[Link]( );
}
}
}

String Handling 141


(c) B L U E J
L UE J
UE J
EJ
J
Prog. import [Link].*;
public class Pattern
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String word;
int i, j, p;
char chr;
[Link]("Enter a word: ");
word = [Link]( );
p = [Link]( );
for (i = 0; i < p; i++)
{
for (j = i; j < p; j++)
{
chr = [Link](j);
[Link](chr);
}
[Link]( );
}
}
}
Q.20 Write a program to generate a triangle or an inverted triangle based
upon the user's choice.
Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice: 1
Enter a word : BLUEJ
Sample Output:
B
L L
UUU
E E E E
J J J J J
Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice: 2
Enter a word : BLUEJ

142
Sample Output:
B L UE J
B L U E
B L U
BL
B
Prog. import [Link].*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
String word;
int i, j, p, ch;
[Link]("Enter a word: ");
word = [Link]( );
p = [Link]( );
[Link]("Type 1 for a triangle");
[Link]("Type 2 for an inverted triangle");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
for(i = 0; i < p; i++)
{
for(j = 0; j <= i; j++)
{
[Link]([Link](i));
}
[Link]( );
}
break;
case 2:
for(i = p – 1; i >= 0; i– –)
{
for(j = 0; j <= i; j++)
{
[Link]([Link](j));
}
[Link]( );
}
break;
default:
[Link]("Incorrect choice");
}
}
}

String Handling 143


Q.21 Using the switch statement, write a menu driven program for the
following:
(a) To print the Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
(b) To display the following pattern:
I
IC
ICS
ICSE
For an incorrect option, an appropriate error message should be
displayed.
Prog. import [Link].*;
public class Pattern
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j, ch, a;
[Link]("Type 1 for Floyd's triangle");
[Link]("Type 2 for an ICSE pattern");
[Link]("Enter your choice: ");
ch = [Link]( );
switch (ch)
{
case 1:
a = 1;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
[Link]((a++) + "\t");
}
[Link]( );
}
break;
case 2:
String st = "ICSE";
for (i = 0; i < [Link]( ); i++)
{
for (j = 0; j <= i; j++)
{
[Link]([Link](j) + " ");
}
[Link]( );

144
}
break;
default:
[Link]("Incorrect Choice");
}
}
}
Q.22 Define a class to declare a character array of size ten, accept the characters
into the array and perform the following:
• Count and print the number of uppercase letters in the array
• Count and print the number of vowels in the array
Prog. import [Link].*;
public class Count
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
char chr[ ] = new char[10];
int i,j, uc=0, v=0;
[Link]("Enter 10 characters in the array one by one:");
for(i=0; i<10; i++)
chr[i]=[Link]( ).charAt(0);
for(j=0; j<10; j++)
{
if(chr[j]>='A' && chr[j]<='Z')
{
uc++;
}
if ((chr[j]=='a'||chr[j]=='e'||chr[j]=='i'||chr[j]=='o'||chr[j]=='u'||
chr[j]=='A'||chr[j]=='E'||chr[j]=='I'||chr[j]=='O'||chr[j]=='U'))
v++;
}
[Link]("Number of uppercase letters: "+uc);
[Link]("Number of vowels: "+v);
}
}
Q.23 Define a class to accept ten characters in an array. The program searches
for the existence of a given character in the array using linear search.
If found then print the character along with the index (location in the
array), otherwise display an appropriate message "No such character is
available in the array".
Prog. import [Link].*;
public class Search
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);

String Handling 145


char chr[ ] = new char[10];
int i,f=0, indx=0;
char chr1;
[Link]("Enter 10 characters in the array one by one:");
for(i=0; i<10; i++)
chr[i]=[Link]( ).charAt(0);
[Link]("Enter a character to search in the array:");
chr1=[Link]( ).charAt(0);
for(i=0; i<10; i++)
{
if(chr1 == chr[i])
{
f=1;
indx = i;
}
}
if (f==1)
[Link]("The character "+chr1+" is present at location "+indx);
else
[Link]("No such character is available in the array");
}
}
Q.24 Write a program in Java to store ten different country names and their
capitals in two different Single Dimensional Arrays (SDA). Display the
country names (that starts with a vowel) along with their capitals in the
given format.
Country Names Capitals
xxxx xxxx
xxxx xxxx
Prog. import [Link].*;
public class CountryCapital
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i;
String countries[ ] = new String[10];
String capitals[ ] = new String[10];
[Link]("Enter 10 countries and their capitals one by
one:");
for (i = 0; i < 10; i++)
{
[Link]("Enter country name: ");
countries[i] = [Link]( );
[Link]("Enter its capital: ");
capitals[i] = [Link]( );
}

146
[Link]("Country Names\t\tCapitals");
for (i = 0; i < 10; i++)
{
char ch = [Link](countries[i].charAt(0));
if (ch == 'A' ||ch == 'E' ||ch == 'I' ||ch == 'O' ||ch == 'U')
[Link](countries[i] + "\t\t" + capitals[i]);
}
}
}
Q.25 Write a program in Java to store 20 different names and telephone
numbers of your friends in two different Single Dimensional Arrays
(SDA). Now, arrange all the names in alphabetical order and display the
names along with their respective telephone numbers using selection
sort technique.
Prog. import [Link].*;
public class TelephoneBook
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j, min;
String temp;
String names[ ] = new String[20];
long telNos[ ] = new long[20];
[Link]("Enter 20 names and telephone numbers one by
one:");
for (i = 0; i < 20; i++)
{
[Link]("Enter Name: ");
names[i] = [Link]( );
[Link]("Enter telephone number: ");
telNos[i] = [Link]( );
[Link]( );
}
//Selection Sort
for (i = 0; i < 20 – 1; i++)
{
min = i;
for (j = i + 1; j < 20; j++)
{
if (names[j].compareToIgnoreCase(names[min]) < 0)
{
min = j;
}
}
temp = names[min];
names[min] = names[i];
names[i] = temp;

String Handling 147


long t = telNos[min];
telNos[min] = telNos[i];
telNos[i] = t;
}
[Link]("Name\tTelephone Number");
for (i = 0; i < 20; i++)
[Link](names[i] + "\t" + telNos[i]);
}
}
Q.26 Write a program to accept 10 names in a Single Dimensional Array (SDA).
Display the names whose first letter matches with the letter entered by
the user.
Sample Input:
Aman Shahi
Akash Gupta
Suman Mishra
and so on.
Sample Output:
Enter a letter: A
Aman Shahi
Akash Gupta
………………
………………
Prog. import [Link].*;
public class Names
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i;
char chr;
String names[ ] = new String[10];
[Link]("Enter 10 names in the array one by one:");
for (i = 0; i < [Link]; i++)
{
names[i] = [Link]( );
}
[Link]("Enter a letter: ");
chr = [Link]( ).charAt(0);
chr = [Link](chr);
for (i = 0; i < [Link]; i++)
{
if ([Link](names[i].charAt(0)) == chr)
[Link](names[i]);
}
}
}

148
Q.27 Write a program in Java to store 10 words in a Single Dimensional Array.
Display only those words which are Palindrome.
Sample Input: MADAM, TEACHER, SCHOOL, ABBA, .........
Sample Output: MADAM
ABBA
..........
..........
Prog. import [Link].*;
public class Palin
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, j;
String str;
String words[ ] = new String[10];
[Link]("Enter 10 words in the array one by one:");
for (i = 0; i < [Link]; i++)
{
words[i] = [Link]( );
}
[Link]("\nPalindrome Words:");
for (i = 0; i < [Link]; i++)
{
str = words[i].toUpperCase( );
int strLen = [Link]( );
boolean isPalin = true;
for (j = 0; j < strLen/2; j++)
{
if ([Link](j) != [Link](strLen – 1 – j))
{
isPalin = false;
break;
}
}
if (isPalin)
[Link](words[i]);
}
}
}
Q.28 Write a program to accept the names of 10 cities in a single dimensional
string array and their STD (Subscribers Trunk Dialling) codes in another
single dimension integer array. Search for the name of a city input by
the user in the list. If found, display "Search Successful" and print the
name of the city along with its STD code, or else display the message
"No such city in the list!!".

String Handling 149


Prog. import [Link].*;
public class Search
{
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int i, idx;
String city;
String cities[ ] = new String[10];
String stdCodes[ ] = new String[10];
[Link]("Enter 10 cities and their STD codes one by one:");
for (i = 0; i < 10; i++)
{
[Link]("Enter City Name: ");
cities[i] = [Link]( );
[Link]("Enter its STD Code: ");
stdCodes[i] = [Link]( );
}
[Link]("Enter name of the city to search: ");
city = [Link]( );
for (idx = 0; idx < 10; idx++)
{
if ([Link](cities[idx]) == 0)
{
break;
}
}
if (idx < 10)
{
[Link]("Search Successful");
[Link]("City: " + cities[idx]);
[Link]("STD Code: " + stdCodes[idx]);
}
else
[Link]("No such city in the list!!");
}
}

150
Chapter 5

User Defined methods

VI. Answer the following:


1. Define a method. What is meant by method prototype?
Ans. A program module (a part or segment of the program) used at different
instances in a program to perform a specific task is known as a Method
or a Function. It can be called at any point in the program using its name
to perform the specific task.
The function prototype is nothing but the declaration of function that
specifies the return data type, function name, number and type of
arguments passed to the function.
2. What are the two ways of invoking functions?
Ans. Two ways of invoking functions are:
• Pass by value
• Pass by reference
3. When a function returns the value, the entire function call can be assigned
to a variable. Do you agree with the statement?
Ans. Yes, when a function returns a value, we can assign the entire function
call to a variable.
For example,
public class Example
{
public int sum(int a, int b)
{
int c = a + b;
return c;
}
public static void main(String args[ ])
{
Example ob = new Example( );
int x = 2, y = 3;
int z = [Link](x, y);
[Link](z);
}
}
4. When a function is invoked, how many values can be returned from the
function?
Ans. A function can return only a single value.
5. Debug the errors and rewrite the following function prototypes:
(a) int sum(x,y);
Ans. int sum(int x, int y)

151
(b) float product(a,int y);
Ans. float product(float a, int y)
(c) float operate(int x, float=3.4);
Ans. float operate(int x, float y)
(d) float sum(int x,y);
Ans. float sum(int x, float y)
6. Write down the main function which calls the following function:
int square(int a)
{
return(a*a);
}
Ans. public static void main(String args[ ])
{
int sq = square(4);
}
7. What happens when a function is passed by reference? Explain.
Ans. Pass by reference means that the arguments of the function are a reference
to the original objects and not a copy. So, any changes that the called
function makes to the objects are visible to the calling function.
For example,
public class PassByRef
{
void Prod(int b[ ])
{
for (int i = 0; i < 5; i++)
b[i] = b[i]*2;
[Link]("Parameters after change:");
for (int i = 0; i < 5; i++)
[Link](b[i] + " ");
[Link]( );
}
public static void main(String args[ ])
{
int a[ ] = { 10, 12, 14, 16, 18 };
PassByRef ob = new PassByRef( );
[Link](a);
[Link]("Function arguments after operation:");
for (int j = 0; j < 5; j++)
[Link](a[j] + " ");
}
}
Output:
Parameters after change:
20 24 28 32 36
Function arguments after operation:
20 24 28 32 36
Here, you can notice that the change brought in the elements of array
b[ ] has also been reflected in the array a[ ].
152
8. In what situation does a function return a value?
Ans. To return a value, it should have a return type other than void in its
function prototype. It returns a value of the corresponding data type
using the return statement in the function body.
9. Differentiate between pure and impure functions.
Ans. Pure functions Impure functions
It never changes the state of an It changes the state of an object.
object.
It takes place in call by value. It takes place in call by reference.
10. Write a function which is used to swap the values of two memory
locations.
(a) by using a third variable.
Ans. void swap(int a, int b)
{
int c = a;
a = b;
b = c;
[Link]("a = " + a + "\t" + "b = " + b);
}
(b) without using a third variable.
Ans. void swap(int a, int b)
{
a = a + b;
b = a – b;
a = a – b;
[Link]("a = " + a + "\t" + "b = " + b);
}
11. Differentiate between call by value and call by reference.
Ans. Call by value Call by reference
Any changes to formal parameters The changes made to formal
are not reflected onto the actual parameters are reflected onto the
parameters. actual parameters.
All primitive data types are passed All reference data types like arrays
using call by value. and objects of classes are passed
using call by reference.

12. What are the advantages of defining a method in a program?


Ans. Advantages of defining methods in a program are:
• It helps to manage the complexity of the program by dividing a
complex task into smaller tasks.
• It is useful in hiding the implementation details.
• It helps with code reusability.
13. What is meant by function overloading? In what way it is advantageous?
Ans. Function overloading is the process of defining functions/methods

User Defined methods 153


within a class that have the same name but differ in the number and/
or the data types of their arguments.
Advantages:
• It is one of the ways in which Java implements the object oriented
concept of Polymorphism.
• The programmers do not have to create and remember different names
for functions doing the same thing for different data types.
14. Define the following:
(a) Return data type
Ans. It specifies the type of value that the method should return. It is mentioned
before the method name in the method prototype. If no value is to return
then it should be defined with void.
(b) Access specifier
Ans. Access specifiers determine the type of access to the method. It can be
either public, private or protected.
(c) Parameter list
Ans. It is a comma-separated list of variables of a method along with their
respective data types. The list is enclosed within a pair of parentheses.
The parameter list can be empty, if the method doesn't accept any
parameters when it is called.
(d) Recursive function
Ans. A function that calls itself inside its body is called a recursive function.
(e) Method signature
Ans. Method signature comprises of the method name and the data types of
the parameters.
For example,
int sum(int a, int b)
{
int c = a + b;
return c;
}
So, the method signature is: sum(int, int)
15. Explain the function of a return statement in Java programming.
Ans. A function returns a value through the return statement. Once a return
statement is executed, the control moves back to the caller function
skipping the remaining statements of the current function (if any). A
function can have multiple return statements but only one of them will
be executed.
16. Differentiate between formal parameter and actual parameter.
Ans. Formal parameter Actual parameter
Formal parameters appear in Actual parameters appear in
function definition. function call statement.
They represent the values received They represent the values passed
by the called function. to the called function.

154
17. What is the role of the keyword 'void' in declaring functions?
Ans. The keyword 'void' signifies that the function doesn't return a value to
the calling function.
18. If a function contains several return statements, how many of them will
be executed?
Ans. A function can have multiple return statements but only one of them
will be executed.
19. Which OOP principle implements function overloading?
Ans. Polymorphism implements function overloading.
20. How are the following data passed to a function?
(i) Primitive types (ii) Reference types
Ans. (i) By value (ii) By reference
VI. Unsolved Java Programs based on Methods:
Q.1 Write a program in Java using a method Discount( ) to calculate a
single discount or a successive discount. Use overload methods
Discount(int p, int d) and Discount(int p,int d1,int d2) to calculate single
discount and successive discount respectively. Calculate and display
the amount to be paid by the customer after getting discounts on the
printed price of an article.
Sample Input:
Printed price: Z 12000
Successive discounts = 10%, 8%
= Z (12000 – 1200)
= Z (10800 – 864)
Amount to be paid = Z 9936
Prog. import [Link].*;
public class Discount
{
double discount(int price, int dis)
{
double dis_pr = price – price * dis/100.0;
return(dis_pr);
}
double discount(int price, int d1, int d2)
{
double dis_pr1 = price – price * d1/100.0;
double dis_pr2 = dis_pr1 – dis_pr1*d2/100.0;
return(dis_pr2);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int p, d1, d2;
double ans1, ans2;
[Link]("Enter price: ");
p = [Link]( );
[Link]("Enter first discount: ");

User Defined methods 155


d1 = [Link]( );
[Link]("Enter second discount: ");
d2 = [Link]( );
Discount ob = new Discount( );
ans1 = [Link](p, d1);
ans2 = [Link](p, d1, d2);
[Link]("Amount to pay after first discount: "+ans1);
[Link]("Amount to pay after two successive discounts:"+ans2);
}
}
Q.2 Write a program to input a number. Use a function int Armstrong(int n)
to accept the number. The function returns 1, if the number is Armstrong,
otherwise zero(0).
Sample Input: 153
Sample Output: 153 ⇒ 13 + 53 + 33 = 153
It is an Armstrong Number.
Prog. import [Link].*;
public class ArmstrongNum
{
public int armstrong(int n)
{
int num = n, cu_sum = 0, digit;
while (num > 0)
{
digit = num % 10;
cu_sum = cu_sum + (digit * digit * digit);
num /= 10;
}
if (cu_sum == n)
return 1;
else
return 0;
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int nm, res;
[Link]("Enter a number: ");
nm = [Link]( );
ArmstrongNum ob = new ArmstrongNum( );
res = [Link](nm);
if (res == 1)
[Link](nm + " is an Armstrong number");
else
[Link](nm + " is not an Armstrong number");
}
}

156
Q.3 Write a program to enter a two-digit number and find out its first factor
excluding 1 (one). The program then finds the second factor (when the
number is divided by the first factor) and finally displays both the factors.
[Hint: Use a non-return type function as void fact(int n) to accept the
number.]
Sample Input: 21
The first factor of 21 is 3
Sample Output: 3, 7
Sample Input: 30
The first factor of 30 is 2
Sample Output: 2, 15
Prog. import [Link].*;
public class Factors
{
public void fact(int n)
{
if (n < 10 || n > 99)
{
[Link]("Input Error!! Not a 2-digit number");
return;
}
int i;
for (i = 2; i <= n; i++)
{
if (n % i == 0)
break;
}
int sf = n/i;
[Link]("First and second factors are:");
[Link](i + ", " + sf);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int num;
[Link]("Enter a number: ");
num = [Link]( );
Factors ob = new Factors( );
[Link](num);
}
}
Q.4 Write a function fact(int n) to find the factorial of a number n. Include a
main class to find the value of S where:
S = n!/(m!(n - m)!)
where, n! = 1 x 2 x 3 x ........... x n
Prog. import [Link].*;
public class Factorial
{

User Defined methods 157


public long fact(int n)
{
long f = 1;
for (int i = 1; i <= n; i++)
{
f *= i;
}
return f;
}
public static void main(String args[ ])
{
Factorial ob = new Factorial( );
Scanner in = new Scanner([Link]);
int m, n;
[Link]("Enter the value of m: ");
m = [Link]( );
[Link]("Enter the value of n: ");
n = [Link]( );
double s = (double)([Link](n))/([Link](m)*[Link](n – m));
[Link]("Answer = " + s);
}
}
Q.5 Write a program using a function called area() to compute the area of
the following:
(a) Area of circle = (22/7) * r * r
(b) Area of square= side * side
(c) Area of rectangle = length * breadth
Display the menu to display the area as per the user's choice.
Prog. import [Link].*;
public class Menu_Ar
{
public void area( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter 'a' to calculate area of circle");
[Link]("Enter 'b' to calculate area of square");
[Link]("Enter 'c' to calculate area of rectangle");
[Link]("Enter your choice: ");
char choice = [Link]( ).charAt(0);
switch(choice)
{
case 'a':
[Link]("Enter radius of circle: ");
double r = [Link]( );
double ac = (22/7.0) * r * r;
[Link]("Area of circle = " + ac);
break;

158
case 'b':
[Link]("Enter side of square: ");
double side = [Link]( );
double asqr = side * side;
[Link]("Area of square = " + asqr);
break;
case 'c':
[Link]("Enter length of rectangle: ");
double l = [Link]( );
[Link]("Enter breadth of rectangle: ");
double b = [Link]( );
double ar = l * b;
[Link]("Area of rectangle = " + ar);
break;
default:
[Link]("Wrong choice!");
}
}
}
Q.6 Write a program using method name Glcm(int, int) to find the Lowest
Common Multiple (LCM) of two numbers by GCD (Greatest Common
Divisor) of the numbers. GCD of two integers is calculated by continued
division method. Divide the larger number by the smaller, the remainder
then divides the previous divisor. The process is repeated till the
remainder is zero. The divisor then results in the GCD.
LCM = product of two numbers/GCD
Prog. import [Link].*;
public class Glcm
{
public void Glcm(int a, int b)
{
int x = a, y = b;
while (y!= 0)
{
int t = y;
y = x % y;
x = t;
}
int lcm = (a * b)/x;
[Link]("LCM = " + lcm);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int m, n;
[Link]("Enter first number: ");
m = [Link]( );
[Link]("Enter second number: ");

User Defined methods 159


n = [Link]( );
Glcm ob = new Glcm( );
[Link](m, n);
}
}
Q.7 Write a program in Java to accept a word. Pass it to a function
magic(String str). The function checks the string for the presence of
consecutive letters. If two letters are consecutive at any position then
the function prints "It is a magic string", otherwise it prints "It is not a
magic string".
Sample Input: computer
Sample Output: It is not a magic string
Sample Input: DELHI
Sample Output: It is a magic string
Prog. import [Link].*;
public class MagicString
{
public void magic(String str)
{
int p, i;
boolean isMagicStr = false;
String st = [Link]( );
p = [Link]( );
for (i = 0; i < p – 1; i++)
{
if ([Link](i) + 1 == [Link](i + 1))
{
isMagicStr = true;
break;
}
}
if (isMagicStr)
[Link]("It is a magic string");
else
[Link]("It is not a magic string");
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a word: ");
String word = [Link]( );
MagicString ob = new MagicString( );
[Link](word);
}
}
Q.8 Write a program using a method Palin( ) to check whether a string is a
Palindrome or not. A Palindrome is a string that reads the same from
the left to right and vice versa.
Sample Input: MADAM, ARORA, ABBA, etc.

160
Prog. import [Link].*;
public class Palindrome
{
public void Palin( )
{
Scanner in = new Scanner([Link]);
int p, i;
String st, str;
[Link]("Enter a string: ");
st = [Link]( );
str = [Link]( );
p = [Link]( );
boolean isPalin = true;
for (i = 0; i < p/2; i++)
{
if ([Link](i) != [Link](p – 1 – i))
{
isPalin = false;
break;
}
}
if (isPalin)
[Link]("It is a palindrome string.");
else
[Link]("It is not a palindrome string.");
}
}
Q.9 Write a program in Java to accept a string from the user. Pass the string
to a function Display(String str) which displays the consonants present
in the string.
Sample Input: computer
Sample Output: c
m
p
t
r
Prog. import [Link].*;
public class Consonants
{
public void Display(String str)
{
int i, p;
String st = [Link]( );
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (ch != 'A' && ch != 'E' && ch != 'I' && ch != 'O' && ch != 'U')

User Defined methods 161


[Link]([Link](i));
}
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a string: ");
String s = [Link]( );
Consonants ob = new Consonants( );
[Link](s);
}
}
Q.10 Write a program in Java to accept a String from the user. Pass the String
to a function Change(String str) which displays the first character of
each word after changing the case (lower to upper and vice versa).
Sample Input: Delhi public school
Sample Output: d
P
S
Prog. import [Link].*;
public class Change_Case
{
public void Change(String str)
{
String st = " " + str;
int p, i;
p = [Link]( );
for (i = 0; i < p – 1; i++)
{
if ([Link](i) == ' ')
{
char ch = [Link](i+1);
if ([Link](ch))
ch = [Link](ch);
else if ([Link](ch))
ch = [Link](ch);
[Link](ch);
}
}
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a string: ");
String s = [Link]( );
Change_Case ob = new Change_Case( );
[Link](s);
}
}

162
Q.11 Write a program in Java to accept the name of an employee and his/
her annual income. Pass the name and the annual income to a function
Tax(String name, int income) which displays the name of the employee
and the income tax as per the given tariff:

Annual Income Income Tax


Up to Z 2,50,000 No tax
Z 2,50,001 to Z 5,00,000 10% of the income exceeding Z 2,50,000
Z 5,00,001 to Z 10,00,000 Z 30,000 + 20% of the amount exceeding
Z 5,00,000
Z 10,00,001 and above Z 50,000 + 30% of the amount exceeding
Z 10,00,000
Prog. import [Link].*;
public class IncomeTax
{
public void Tax(String name, int income)
{
double itax;
if (income <= 250000)
itax = 0;
else if (income <= 500000)
itax = (income – 250000) * 0.1;
else if (income <= 1000000)
itax = 30000 + ((income – 500000) * 0.2);
else
itax = 50000 + ((income – 1000000) * 0.3);
[Link]("Name: " + name);
[Link]("Income Tax: " + itax);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter name: ");
String nm = [Link]( );
[Link]("Enter annual income: ");
int sal = [Link]( );
IncomeTax ob = new IncomeTax( );
[Link](nm, sal);
}
}
Q.12 Write a program in Java to accept a String from the user. Pass the String
to a function First(String str) which displays the first character of each
word.
Sample Input: Understanding Computer Applications
Sample Output: U
C
A

User Defined methods 163


Prog. import [Link].*;
public class Character
{
public void First(String str)
{
int p, i;
String st = " " + str;
p = [Link]( );
for (i = 0; i < p – 1; i++)
{
if ([Link](i) == ' ')
{
char ch = [Link](i + 1);
[Link](ch);
}
}
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a string: ");
String s = [Link]( );
Character ob = new Character( );
[Link](s);
}
}
Q.13 Write a class with the name Area using function overloading that
computes the area of a parallelogram, a rhombus and a trapezium.
Formula:
Area of a parallelogram (pg) = base * ht
Area of a rhombus (rh) = (1/2) * d1 * d2 (where, d1 and d2 are
the diagonals)
Area of a trapezium (tr) = (1/2) * (a + b) * h (where, a and b are
the parallel sides, h is the perpendicular
distance between the parallel sides)
Prog. import [Link].*;
public class Area
{
public int area(int base, int height)
{
int ar1 = base * height;
return ar1;
}
public double area(double d1, double d2)
{
double ar2 = 1.0/2.0 * d1 * d2;
return ar2;
}

164
public double area(double a, double b, double h)
{
double ar3 = 1.0/2.0 * (a + b) * h;
return ar3;
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int base, ht;
double d1, d2, a, b, h;
Area ob = new Area( );
[Link]("Enter base of parallelogram: ");
base = [Link]( );
[Link]("Enter height of parallelogram: ");
ht = [Link]( );
[Link]("Enter first diagonal of rhombus: ");
d1 = [Link]( );
[Link]("Enter second diagonal of rhombus: ");
d2 = [Link]( );
[Link]("Enter first parallel side of trapezium: ");
a = [Link]( );
[Link]("Enter second parallel side of trapezium: ");
b = [Link]( );
[Link]("Enter height of trapezium: ");
h = [Link]( );
[Link]("Area of parallelogram = " + [Link](base, ht));
[Link]("Area of rhombus = " + [Link](d1, d2));
[Link]("Area of trapezium = " + [Link](a, b, h));
}
}
Q.14 Write a class with the name Perimeter using function overloading that
computes the perimeter of a square, a rectangle and a circle.
Formulae:
Perimeter of a square = 4 * s
Perimeter of a rectangle = 2 * (l + b)
Perimeter of a circle = 2 * (22/7) * r
Prog. import [Link].*;
public class Perimeter
{
public int peri(int s)
{
int p = 4 * s;
return p;
}
public int peri(int l, int b)
{
int p = 2 * (l + b);
return p;

User Defined methods 165


}
public double peri(double r)
{
double p = 2 * (22.0/7.0) * r;
return p;
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int side, l, b;
double r;
Perimeter ob = new Perimeter( );
[Link]("Enter side of square: ");
side = [Link]( );
[Link]("Enter length of rectangle: ");
l = [Link]( );
[Link]("Enter breadth of rectangle: ");
b = [Link]( );
[Link]("Enter radius of circle: ");
r = [Link]( );
[Link]("Perimeter of square = " + [Link](side));
[Link]("Perimeter of rectangle = " + [Link](l, b));
[Link]("Perimeter of circle = " + [Link](r));
}
}
Q.15 Design a class Overloading and a function display( ) as follows:
(i) void display(String str, int p) with one String argument and one
integer argument. It displays all the uppercase characters, if 'p' is 1
(one) otherwise, it displays all the lowercase characters.
(ii) void display(String str, char chr) with one String argument and one
character argument. It displays all the vowels if chr is 'v' otherwise,
it displays all the letters.
Prog. import [Link].*;
public class Overloading
{
void display(String str, int p)
{
int a, i;
a = [Link]( );
for (i = 0; i < a; i++)
{
char ch = [Link](i);
if (p == 1 && [Link](ch))
[Link](ch);
else if (p != 1 && [Link](ch))
[Link](ch);
}
}

166
void display(String str, char chr)
{
int a,i;
a = [Link]( );
for (i = 0; i < a; i++)
{
char ch = [Link](i);
ch = [Link](ch);
if (chr != 'v' && [Link]([Link](i)))
[Link]([Link](i));
else if (ch == 'A' ||ch == 'E' ||ch == 'I' ||ch == 'O' ||ch == 'U')
[Link]([Link](i));
}
}
}
Q.16 Design a class overloading a function calculate( ) as follows:
(i) void calculate(int m, char ch) with one integer argument and one
character argument. It checks whether the integer argument is
divisible by 7 or not, if ch is 's', otherwise, it checks whether the last
digit of the integer argument is 7 or not.
(ii) void calculate(int a, int b, char ch) with two integer arguments and
one character argument. It displays the greater of integer arguments
if ch is 'g' otherwise, it displays the smaller of integer arguments.
Prog. import [Link].*;
public class Calculate
{
public void calculate(int m, char ch)
{
if (ch == 's')
{
if (m % 7 == 0)
[Link]("It is divisible by 7");
else
[Link]("It is not divisible by 7");
}
else
{
if (m % 10 == 7)
[Link]("Last digit is 7");
else
[Link]("Last digit is not 7");
}
}
public void calculate(int a, int b, char ch)
{
if (ch == 'g')
[Link](a > b ? a : b);
else

User Defined methods 167


[Link](a < b ? a : b);
}
}
Q.17 Design a class to overload a function compare( ) as follows:
(i) void compare(int, int) : to compare two integers values and
print the greater of the two integers.
(ii) void compare(char, char) : to compare the numeric value of two
characters and print with the higher
numeric value.
(iii) void compare(String, String) : to compare the length of the two
strings and print the longer of the
two.
Prog. import [Link].*;
public class Compare
{
public void compare(int a, int b)
{
if (a > b)
[Link](a);
else
[Link](b);
}
public void compare(char a, char b)
{
int x = (int)a;
int y = (int)b;
if (x > y)
[Link](a);
else
[Link](b);
}
public void compare(String a, String b)
{
int p1 = [Link]( );
int p2 = [Link]( );
if (p1 > p2)
[Link](a);
else
[Link](b);
}
}
Q.18 Design a class to overload a function series( ) as follows:
(i) double series(double n) with one double argument and returns the
sum of the Series:
sum = (1/1) + (1/2) + (1/3) +............ + (1/n)
(ii) double series(double a, double n) with two double arguments and
returns the sum of the series:
sum = (1/a2) + (4/a5) + (7/a8) + (10/a11) +............ to n terms

168
Prog. public class Series
{
double series(double n)
{
double sum = 0;
for (int i = 1; i <= n; i++)
{
double term = 1.0 / i;
sum += term;
}
return sum;
}
double series(double a, double n)
{
double sum = 0;
int x = 1, y =2;
for (int i = 1; i <= n; i++)
{
double term = x / [Link](a, y);
sum += term;
x += 3;
y += 3;
}
return sum;
}
public static void main(String args[ ])
{
Series ob = new Series( );
[Link]("Sum of first series = " + [Link](5));
[Link]("Sum of second series = " + [Link](2, 5));
}
}
Q.19 Design a class to overload the function display(. .... ) as follows:
(i) void display(int num) : checks and prints whether the number is a
perfect square or not.
(ii) void display(String str, char ch) : checks and prints, if the word str
contains the letter ch or not.
(iii) void display(String str) : checks and prints the number of special
characters present in the word str.
Write a suitable main( ) function.
Prog. public class Display
{
public void display(int num)
{
double ans = [Link](num);
double diff = ans – [Link](ans);
if (diff == 0)

User Defined methods 169


[Link](num + " is a perfect square");
else
[Link](num + " is not a perfect square");
}
public void display(String str, char ch)
{
int idx = [Link](ch);
if (idx == –1)
[Link](ch + " not found in the given string");
else
[Link](ch + " found in the given string");
}
public void display(String str)
{
int i, p, c = 0;
p = [Link]( );
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (![Link](ch) && ![Link](ch))
{
c++;
}
}
[Link]("Number of special characters = " + c);
}
public static void main(String args[ ])
{
Display ob = new Display( );
[Link](64);
[Link]("ICSE Computer Applications", 'b');
[Link]("New Delhi - 110005");
}
}
Q.20 Design a class to overload the function display(. ) as follows:
(i) void display(String str, char ch) : checks whether the word str
contains the letter ch at the beginning as well as at the end or not.
If present, print 'Special Word' otherwise print 'No special word'.
(ii) void display(String str1, String str2) : checks and prints whether
both the words are equal or not.
(iii) void display(String str, int n) : prints the character present at nth
position in the word str.
Write a suitable main( ) function.
Prog. public class Check
{
public void display(String str, char ch)
{

170
String temp = [Link]( );
ch = [Link](ch);
int p = [Link]( );
if ([Link](ch) == 0 && [Link](ch) == (p – 1))
[Link]("Special Word");
else
[Link]("No Special Word");
}
public void display(String str1, String str2)
{
if ([Link](str2))
[Link](" Both the strings are equal");
else
[Link]("Strings are not equal");
}
public void display(String str, int n)
{
int p = [Link]( );
if (n < 0 || n > p)
{
[Link]("Invalid value for argument n");
return;
}
char ch = [Link](n – 1);
[Link](ch);
}
public static void main(String args[ ])
{
Check ob = new Check( );
[Link]("Tweet", 't');
[Link]("Facebook", "Notebook");
[Link]("Applications", 6);
}
}
Q.21 Design a class to overload a function volume( ) as follows:
(i) double volume(double r) : with radius (r) as an argument, returns
the volume of sphere using the formula:
V = (4/3) * (22/7) * r * r * r
(ii) double volume(double h, double r) : with height(h) and radius(r) as
the arguments, returns the volume of a cylinder using the formula:
V = (22/7) * r * r * h
(iii) double volume(double 1, double b, double h) : with length(l),
breadth(b) and height(h) as the arguments, returns the volume of a
cuboid using the formula:
V = l*b*h ⇒ (length * breadth * height)
Prog. public class Volume
{
double volume(double r)

User Defined methods 171


{
double vol = (4/3.0) * (22/7.0) * r * r * r;
return vol;
}
double volume(double h, double r)
{
double vol = (22/7.0) * r * r * h;
return vol;
}
double volume(double l, double b, double h)
{
double vol = l * b * h;
return vol;
}
public static void main(String args[ ])
{
Volume ob = new Volume( );
[Link]("Volume of sphere = " + [Link](14));
[Link]("Volume of cylinder = " + [Link](14, 8.5));
[Link]("Volume of cuboid = " + [Link](8.5, 4.5, 2.5));
}
}
22. Design a class to overload a function Series( ) as follows:
(a) To display the sum of the series given below:
x1 + x2 + x3 + ............+ xn terms
void Series(int x, int n)
(b) To display the following series:
0, 7, 26, 63, ..........to 'p' terms
void Series(int p)
(c) To display the sum of the series given below:
1 1 1 1
+ + + ………………………………. +
2 3 4 10
void Series( )
Write a main method to create an object and invoke the above methods.
Prog. import [Link].*;
public class Disp_Series
{
public void series( int x, int n)
{
int i;
double a, sum = 0;
for (i = 1; i <= n; i++)
{
a = [Link](x, i);
sum = sum + a;
}
[Link]("Sum of the series = " +sum);
}

172
public void series(int p)
{
int i;
[Link]("The series:");
for (i = 1; i <= p; i++)
{
[Link]((i * i * i) – 1 + " ");
}
public void series( )
{
int i;
double s = 0;
for (i =2; i <= 10; i++)
{
s = s + (double)1/i;
}
[Link]("Sum of the series " +s);
}
public static void main(String args[ ])
{
Disp_Series ob = new Disp_Series( );
[Link](2, 5);
[Link](5);
[Link]( );
}
}
23. Define a class to overload the function print( ) as follows:
(a) void print( ) : to print the following format:
11111
22222
33333
44444
55555
(b) print(int n) : to check whether the number is a lead number or not
A lead number is the one whose sum of even digits
is equal to sum of odd digits.
For example,
Sample Input: 3669
Sample Output: Sum of odd digits = 3 + 9 =12
Sum of even digits = 6 + 6 = 12
Hence, 3669 is a lead number.
Prog. public class Overload
{
void print( )
{
int i, j;
for (i = 1; i <= 5; i++)

User Defined methods 173


{
for (j = 1; j <=5; j++)
{
[Link](i + " ");
}
[Link]( );
}
}
void print(int n)
{
int sum_ev = 0, sum_odd = 0, d, temp;
temp = n;
while(temp!=0)
{
d = temp%10;
if (d%2 == 0)
sum_ev += d;
else
sum_odd += d;
temp = temp/10;
}
if(sum_ev == sum_odd)
[Link](n + " is a lead number");
else
[Link](n + " is not a lead number");
}
public static void main(String args[ ])
{
Overload ob = new Overload( );
[Link]( );
[Link](3669);
}
}

174
Chapter 6

Class as the Basis of all Computation


(Objects and Classes)

IV. Answer the following questions:


1. Why is a class known as composite data type?
Ans. A composite data type is one which is composed with various primitive
data types. A class can contain various primitive data types as its data
members. So, it is known as a composite data type.
2. Name the types of data used in a class.
Ans. The different data types used in a class are access specifiers, instance
variables, class variables, local variables, etc.
3. What is the purpose of the new operator?
Ans. The purpose of 'new' operator is to instantiate an object of the class by
allocating the memory dynamically for it.
4. Can a class be referred to as user defined data type?
Ans. Since a class is created by the user, so it is also known as user defined
data type. Moreover, the class created by the user will include all the
primitive data types, declared within it.
5. What is public access of a class?
Ans. When a class is declared with public access specifier it is said to publicly
accessible. It means that the class member is visible even outside the
visibility of the class.
6. How are private members of a class different from public members?
Ans. The private members of a class are accessible only within the class in
which they are declared. Whereas, the public members of the class are
accessible within and outside the class.
7. Mention any two attributes required for class declaration.
Ans. Two attributes required for class declaration are the keyword 'class' and
the name of the class.
8. Explain instance variables. Give an example.
Ans. The variables that are declared inside a class without using the keyword
'static' and outside of any member methods are termed instance variables.
For example,
class Cuboid
{
int length, breadth, height, volume =0;
public void input(int l, int b, int h)
{
length = l;
breadth = b;
height = h;

175
}
public void Cal_Volume( )
{
volume = length * breadth * height;
[Link]("Volume = " + volume);
}
}
Here: length, breadth, height and volume are instance variables.
9. Explain any two types of access specifiers.
Ans. The two types of access specifiers are:
• public: A data member or member method declared as public is
accessible inside as well as outside of the class in which it is declared.
• private: A data member or member method declared as private is only
accessible inside the class in which it is declared.
10. What is meant by private visibility of a method?
Ans. A member method of a class declared with private access specifier is said
to have private visibility. In this case, only the other member methods
of its class can call this method.
11. Is it possible to print the values of instance variable and local variable
having the same name but different values? Comment.
Ans. Yes, it is possible to print the value of an instance variable when local
variable and instance variable have the same name with different values.
In Java, the above task can be resolved by using this keyword.
For example,
Class Test
{
int n=12; // instance variable
void Show(int n) // local variable
{
[Link]("Value of local variable=" + n);
[Link]("Value of instance variable="+this.n);
}
public static void main(String args[ ])
{
Test ob = new Test( );
[Link](15);
}
}
12. Read the program and answer the given questions:
class Sample
{
int a;
int b;
Sample(int x, int y)
{
a = x;

176
b = y;
}
void calculate( )
{
int z;
z = a+b;
[Link](z);
}
}
(i) Name the global variables.
(ii) What are the method variables?
Ans. (i) a, b
(ii) x, y
V. Answer the questions given below (Long answer type):
1. 'Object is an instance of a class.' Explain this statement.
Ans. The data members declared within a class are also known as instance
variables.
When an object of a class is created, it includes instance variables
described within the class. This is the reason that object is called as an
instance of a class.
2. Differentiate between built-in data types and user defined data types.
Ans. Built-In Data Types User Defined Data Types
They are the fundamental data User defined data types are created
types defined by Java programming by the user.
language.
The size of built-in data types is The size of user defined data types
fixed. depends upon their constituent
members.

3. Which of the following declarations are illegal and why?


(a) class abc(...)
Ans. Legal
(b) public class NumberOfDaysWorked(...)
Ans. Legal
(c) private int x;
Ans. Legal
(d) private class abc(...)
Ans. Illegal : Only 'public' or no access specifier are allowed for class
declaration.
4. Why can't every class be termed as user defined data type?
Ans. The classes that contain main( ) method, i.e.,
"public static void main(String args[ ])" are not considered as a user
defined data type.
It is a Java application created by the system. So, it is not considered as
a user defined data type. Whereas, we can refer class to a user defined
data type that does not include a main( ) method. It must be noted that

Class as the Basis of all Computation (Objects and Classes) 177


a user defined data type is a data type that is created by a programmer.
5. Differentiate between static data members and non-static data members.
Ans. Static Data Members Non-Static Data Members
They are declared using the They are declared without using
keyword 'static'. the keyword 'static'.
All objects of a class share the same Each object of the class gets its own
copy of static data members. copy of non-static data members.

6. Differentiate between private and protected visibility modifiers.


Ans. The private members are only accessible inside the class in which they
are defined and they can not be inherited by the derived classes. The
protected members are also accessible only inside the class in which they
are defined but they can be inherited by the derived classes.
7. Differentiate between instance variable and class variable.
Ans. Instance Variable Class Variable
They are declared without using They are declared using the
the keyword 'static'. keyword 'static'.
They can be accessed only through They can be accessed using the
an object of the class. class name or object.

8. What is the significance of this keyword in Java? Explain.


Ans. The this keyword is the representation of the current object in a method
or a constructor. It is also called as a reference variable that refers to the
current object. In Java, using this keyword, we can print the value of an
instance variable when local variable and instance variable have the
same name.
VI. Unsolved Java Programs based on Class:
Q.1 Define a class Calculate to accept two numbers as instance variables.
Use the following functions for the given purposes:
Class Name : Calculate
Data members : int a, int b
Member methods : int a, int b
void inputdata( ) : to input both the values
void calculate( ) : to find the sum and the difference
void outputdata( ) : to print the sum and the difference of both the
numbers
Use a main method to call the functions.
Prog. import [Link].*;
public class Calculate
{
int a, b, sum, diff;
public void inputdata( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter first number: ");
a = [Link]( );

178
[Link]("Enter second number: ");
b = [Link]( );
}
public void calculate( )
{
sum = a + b;
diff = a – b;
}
public void outputdata( )
{
[Link]("Sum = " + sum);
[Link]("Difference = " + diff);
}
public static void main(String args[ ])
{
Calculate ob = new Calculate( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.2 Define a class Employee having the following description:
Class name : Employee
Data members/Instance variables
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
Member functions:
void input( ) : Store the pan number, name, taxable income
void cal( ) : Calculate tax on taxable income based on the given
table:

Total Annual Taxable Income Tax Rate


Up to Z 2,50,000 No tax
From Z 2,50,001 to Z 5,00,000 10% of the income exceeding
Z 2,50,000
From Z 5,00,001 to Z 10,00,000 Z 30,000 + 20% of the income
exceeding Z 5,00,000
Above Z 10,00,000 Z 50,000 + 30% of the income
exceeding Z 10,00,000
void display( ) : Output details of an employee
Calculate tax based on the given conditions and display the output as
per the given format:
Pan Number Name Tax-Income Tax
……………… ……………… ……………… ………………
……………… ……………… ……………… ………………

Class as the Basis of all Computation (Objects and Classes) 179


Prog. import [Link].*;
public class Employee
{
String pan, name;
double tincome, tax;
public void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter PAN number: ");
pan = [Link]( );
[Link]( );
[Link]("Enter name: ");
name = [Link]( );
[Link]("Enter taxable income: ");
tincome = [Link]( );
}
public void cal( )
{
if (tincome <= 250000)
tax = 0;
else if (tincome <= 500000)
tax = (tincome – 250000) * 0.1;
else if (tincome <= 1000000)
tax = 30000 + ((tincome – 500000) * 0.2);
else
tax = 50000 + ((tincome – 1000000) * 0.3);
}
public void display( )
{
[Link]("Pan Number\tName\t\tTax-Income\tTax");
[Link](pan + "\t" + name + "\t" +tincome + "\t" + tax);
}
public static void main(String args[ ])
{
Employee ob = new Employee( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.3 Define a class Discount having the following description:
Class name : Discount
Data members:
int cost : to store the price of an article
String name : to store the customer's name
double dc : to store the discount
double amt : to store the amount to be paid

180
Member methods:
void input( ) : Stores the cost of the article and name of the customer
void cal( ) : Calculates the discount and amount to be paid as per
the given table:
List Price Rate of discount
Up to Z 5,000 No discount
From Z 5,001 to Z 10,000 10% on the list price
From Z 10,001 to Z 15,000 15% on the list price
Above Z 15,000 20% on the list price
void display( ) : Displays the name of the customer, cost, discount and
amount to be paid
Write a program to compute the discount according to the given
conditions and display the output as per the given format.
Name of the customer Discount Amount to be paid
………………………… ………… ………………………
………………………… ………… ………………………
Prog. import [Link].*;
public class Discount
{
int cost;
String name;
double dc, amt;
public void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter customer name: ");
name = [Link]( );
[Link]("Enter cost: ");
cost = [Link]( );
}
public void cal( )
{
if (cost <= 5000)
dc = 0;
else if (cost <= 10000)
dc = cost * 0.1;
else if (cost <= 15000)
dc = cost * 0.15;
else
dc = cost * 0.2;
amt = cost – dc;
}
public void display( )
{
[Link]("Name \t\tDiscount\tAmount to be paid");
[Link](name + "\t" + dc + "\t\t" + amt);
}

Class as the Basis of all Computation (Objects and Classes) 181


public static void main(String args[ ])
{
Discount ob = new Discount( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.4 Define a class Telephone having the following description:
Class name : Telephone
Data members:
int prv, pre : to store the previous and present meter readings
int call : to store the calls made (i.e. pre – prv)
String name : to store name of the consumer
double amt : to store the amount
double total : to store the total amount to be paid
Member functions:
void input( ) : Stores the previous reading, present reading and
name of the consumer
void cal( ) : Calculates the amount and total amount to be paid
as per the given table:

Calls made Rate


Up to 100 calls No charge
For the next 100 calls 90 paise per call
For the next 200 calls 80 paise per call
More than 400 calls 70 paise per call
However, every consumer has to pay Z 180 per month as monthly rent
for availing the service.
void display( ) : Displays the name of the consumer, calls made,
amount and total amount to be paid
Write a program to compute the monthly bill to be paid according to the
given conditions and display the output as per the given format:
Name of the customer Calls made Amount to be paid
………………………… …………… ………………………
………………………… …………… ………………………
Prog. import [Link].*;
public class Telephone
{
int prv, pre, call;
String name;
double amt, total;
public void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter customer name: ");

182
name = [Link]( );
[Link]("Enter previous reading: ");
prv = [Link]( );
[Link]("Enter present reading: ");
pre = [Link]( );
}
public void cal( )
{
call = pre – prv;
if (call <= 100)
amt = 0;
else if (call <= 200)
amt = (call – 100) * 0.9;
else if (call <= 400)
amt = (100 * 0.9) + (call – 200) * 0.8;
else
amt = (100 * 0.9) + (200 * 0.8) + ((call – 400) * 0.7);
total = amt + 180;
}
public void display( )
{
[Link]("Name \t\tCalls made\tAmount to be paid");
[Link](name + "\t" + call + "\t\t" + total);
}
public static void main(String args[ ])
{
Telephone ob = new Telephone( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.5 Define a class with the following specifications:
Class name : Employee
Member variables:
eno : employee number
ename : name of the employee
age : age of the employee
basic : basic salary
[Declare the variables using appropriate data types]
Member methods:
void accept( ) : to accept the details using scanner class
void calculate( ) : to calculate the net salary as per the given
specifications:
net = basic + hra + da – pf
hra = 18.5% of basic
da = 17.45% of basic
pf= 8.10% of basic

Class as the Basis of all Computation (Objects and Classes) 183


If the age of the employee is above 50, he/she gets an additional
allowance of ` 5000.
void print( ) : to print the details as per the following format:
Emp_no Emp_Name Age Basic Net_Salary
xxxxx xxxxxxxxxx xxxx xxxxxx xxxxxxxx
Write a main method to create an object of the class and invoke the
methods.
Prog. import [Link].*;
public class Employee
{
String eno, ename;
int age, basic;
double net, hra, da, pf;
public void accept( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter employee number: ");
eno = [Link]( );
[Link]( );
[Link]("Enter employee name: ");
ename = [Link]( );
[Link]("Enter employee age: ");
age = [Link]( );
[Link]("Enter basic salary: ");
basic = [Link]( );
}
public void calculate( )
{
hra = basic * 18.5/100.0;
da = basic * 17.45/100.0;
pf = basic* 8.10/100.0;
net = basic + hra + da – pf;
if (age > 50)
net = net + 5000;
else
net = net + 0;
}
public void print( )
{
[Link]("Emp_No\tName\t\tAge\tBasic\tNet_Salary");
[Link](eno + "\t" + ename + "\t" +age+"\t" +basic + "\t" + net);
}
public static void main(String args[ ])
{
Employee ob = new Employee( );
[Link]( );
[Link]( );
[Link]( );
}
}

184
Q.6 Define a class Library having the following description:
Class name : Library
Data members:
String name : to store name of the book
int price : to store the printed price of the book
int day : to store the number of days for which fine is to be
paid
double fine : to store the fine to be paid
Member methods:
void input( ) : To accept the name of the book and printed price
of the book
void cal( ) : Calculates the fine to be paid as per the given table:
Days Fine
First seven days 25 paise per day
Eight to fifteen days 40 paise per day
Sixteen to thirty days 60 paise per day
More than thirty days 80 paise per day
void display( ) : Displays the name of the book and the fine to be paid
Write a program to compute the fine according to the given conditions
and display the fine to be paid.
Prog. import [Link].*;
public class Library
{
String name;
int price, day;
double fine;
public void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter name of the book: ");
name = [Link]( );
[Link]("Enter printed price of the book: ");
price = [Link]( );
[Link]("For how many days fine needs to be paid: ");
day = [Link]( );
}
public void cal( )
{
if (day <= 7)
fine = day * 0.25;
else if (day <= 15)
fine = (7 * 0.25) + ((day – 7) * 0.4);
else if (day <= 30)
fine = (7 * 0.25) + (8 * 0.4) + ((day – 15) * 0.6);
else
fine = (7 * 0.25) + (8 * 0.4) + (15 * 0.6) + ((day – 30) * 0.8);

Class as the Basis of all Computation (Objects and Classes) 185


}
public void display( )
{
[Link]("Name of the book: " + name);
[Link]("Fine to be paid: " + fine);
}
public static void main(String args[ ])
{
Library ob = new Library( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.7 Bank charges interest for the vehicle loan as given below:

Number of years Rate of interest


Up to 5 years 15%
More than 5 and up to 10 years 12%
Above 10 years 10%

Write a program to model a class with the specifications given below:


Class name : Loan
Data members/Instance variables:
int time : Time for which loan is sanctioned
double principal : Amount sanctioned
double rate : Rate of interest
double interest : To store the interest
double amt : Amount to pay after the given time
Member Methods:
void getdata( ) : to accept principal and time
void calculate( ) : to find interest and amount as per the table given
above
Interest = (Principal*Rate*Time)/100
Amount = Principal + Interest
void display( ) : to display interest and amount.
Prog. import [Link].*;
public class Loan
{
int time;
double pr, rate, interest, amt;
public void getdata( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter principal: ");
pr = [Link]( );
[Link]("Enter time: ");

186
time = [Link]( );
}
public void calculate( )
{
if (time <= 5)
rate = 15.0;
else if (time <= 10)
rate = 12.0;
else
rate = 10.0;
interest = (pr * rate * time)/100.0;
amt = pr + interest;
}
public void display( )
{
[Link]("Interest = " + interest);
[Link]("Amount Payable = " + amt);
}
public static void main(String args[ ])
{
Loan ob = new Loan( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.8 Hero Honda has increased the cost of its vehicles as per the type of the
engine using the following criteria:

Type of Engine Rate of increment


2 stroke 10% of the cost
4 stroke 12% of the cost
Write a program by using a class to find the new cost as per the given
specifications:
Class name : Honda
Data members/Instance variables:
int type : to accept type of engine 2 stroke or 4 stroke
int cost : to accept previous cost
Member Methods:
void gettype( ) : to accept the type of engine and previous cost
void find( ) : to find the new cost as per the criteria given above
void printcost( ) : to print the type and new cost of the vehicle
Prog. import [Link].*;
public class Honda
{
int ch, type, cost;

Class as the Basis of all Computation (Objects and Classes) 187


double newCost;
public void gettype( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter type of engine '2' or '4': ");
type = [Link]( );
[Link]("Enter cost: ");
cost = [Link]( );
[Link]("Enter 1 for '2 stroke engine' and 2 for '4 stroke
engine': ");
[Link]("Enter your choice: ");
ch = [Link]( );
}
public void find( )
{
switch (ch)
{
case 1:
newCost = cost + (cost * 0.1);
break;
case 2:
newCost = cost + (cost * 0.12);
break;
default:
[Link]("Incorrect choice!!");
[Link](0);
}
}
public void printcost( )
{
[Link]("Type of engine : " + type);
[Link]("New cost: " + newCost);
}
public static void main(String args[ ])
{
Honda ob = new Honda( );
[Link]( );
[Link]( );
[Link]( );
}
}

188
Q.9 Define a class called 'Mobike' with the following specifications:
Class name : Mobike
Instance variables/ Data members:
int bno : to store the bike number
int phno : to store the phone number of the customer
String name : to store the name of the customer
int days : to store the number of days the bike is taken on rent
int charge : to calculate and store the rental charge
Member methods:
void input( ) : to input and store the details of the customer
void compute( ) : to compute the rental charge
The rent for a mobike is charged on the following basis:
Days Charge
For first five days Z 500 per day
For next five days Z 400 per day
Rest of the days Z 200 per day
void display( ) : to display the details in the following format:
Bike No. Phone No. Name No. of days Charge
xxxxxxx xxxxxxxx xxxx xxx xxxxxx
Prog. import [Link].*;
public class Mobike
{
int days, charge;
long phno;
String name, bno;
public void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter customer name: ");
name = [Link]( );
[Link]("Enter customer phone number: ");
phno = [Link]( );
[Link]("Enter bike number: ");
bno = [Link]( );
[Link]("Enter number of days: ");
days = [Link]( );
}
public void compute( )
{
if (days <= 5)
charge = days * 500;
else if (days <= 10)
charge = (5 * 500) + ((days – 5) * 400);
else
charge = (5 * 500) + (5 * 400) + ((days – 10) * 200);
}

Class as the Basis of all Computation (Objects and Classes) 189


public void display( )
{
[Link]("Bike No.\tPhone No.\tName\tNo. of days\tCharge");
[Link](bno+"\t"+phno+"\t"+name+"\t"+days+"\t"+charge);
}
public static void main(String args[ ])
{
Mobike ob = new Mobike( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.10 Define a class with the following specifications:
Class name : Vowel
Data members : string st; int c (to count vowels)
Member functions:
void getstr( ) : to accept a string
void getvowel( ) : to count the number of vowels
void display( ) : to print the number of vowels
Prog. import [Link].*;
public class Vowel
{
String st;
int i, c, p;
public void getstr( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter a string: ");
st = [Link]( );
}
public void getvowel( )
{
String temp = [Link]( );
p = [Link]( );
c = 0;
for (i = 0; i < p; i++)
{
char ch = [Link](i);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O'|| ch == 'U')
c++;
}
}
public void display( )
{
[Link]("Number of Vowels = " + c);
}
public static void main(String args[ ])

190
{
Vowel ob = new Vowel( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.11 A bookseller maintains record of books belonging to the various
publishers. He uses a class with the specifications given below:
Class name : Stock
Data members/Instance variables
String title : Contains title of the book
String author : Contains author name
String pub : Contains publisher's name
int noc : Number of copies
Member Methods:
void getdata( ) : to accept title, author, publisher's name and the
number of copies.
void purchase(int t, String a, String p, int n) :
to check the existence of the book in the stock by
comparing total, author's and publisher's name.
Also check whether noc > n or not. If yes, maintain
the balance as noc–n, otherwise display book is not
available or stock is under flowing.
Write a program to perform the task given above.
Prog. import [Link].*;
public class Stock
{
String title, author, pub;
int noc;
public void getdata( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter title of the book: ");
title = [Link]( );
[Link]("Enter name of the author: ");
author = [Link]( );
[Link]("Enter name of the publisher: ");
pub = [Link]( );
[Link]("Enter number of copies: ");
noc = [Link]( );
}
public void purchase(String t, String a, String p, int n)
{
if ([Link](t) && [Link](a) && [Link](p))
{
if (noc > n)
{

Class as the Basis of all Computation (Objects and Classes) 191


noc –= n;
[Link]("Updated number of copies = " + noc);
}
else
{
[Link]("Stock is under flowing");
}
}
else
[Link]("Book is not available");
}
public static void main(String args[ ])
{
Stock ob = new Stock( );
[Link]( );
[Link]("Ignited Minds", "APJ Abdul Kalam","Penguin", 2);
}
}
Q.12 Define a class with the following specifications:
Class name : Characters
Data Members/Instance variable
String str : to store the string
Member Methods:
void input (String st) : to assign st to str
void check_print( ) : to check and print the following:
(i) number of letters
(ii) number of digits
(iii) number of uppercase characters
(iv) number of lowercase characters
(v) number of special characters
Prog. import [Link].*;
public class Characters
{
int i;
String str;
public void input(String st)
{
str = st;
}
public void check_print( )
{
int cLetters = 0, cDigits = 0, cUpper = 0, cLower = 0, cSpecial = 0;
for (i = 0; i < [Link]( ); i++)
{
char ch = [Link](i);
if (ch >= 'A' && ch <= 'Z')
{
cLetters++;

192
cUpper++;
}
else if (ch >= 'a' && ch <= 'z')
{
cLetters++;
cLower++;
}
else if (ch >= '0' && ch <= '9')
{
cDigits++;
}
else if ([Link](ch))
{
cSpecial++;
}
}
[Link]("Number of letters: " + cLetters);
[Link]("Number of digits: " + cDigits);
[Link]("Number of upppercase characters: " + cUpper);
[Link]("Number of lowercase characters: " + cLower);
[Link]("Number of special characters: " + cSpecial);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a string: ");
String st = [Link]( );
Characters ob= new Characters( );
[Link](st);
ob.check_print( );
}
}
Q.13 Define a class Student with the following specifications:
Class name : Student
Instance variables/Data Members:
String name : to store the name of the student
int eng : to store marks in English
int hn : to store marks in Hindi
int mts : to store marks in Maths
double total : to store total marks
double avg : to store average marks
Member methods:
void accept( ) : to input marks in English, Hindi and Maths
void compute( ) : to calculate total marks and average of 3 subjects
void display( ) : to show all the details viz. name, marks, total and
average
Write a program to create an object and invoke the above methods.

Class as the Basis of all Computation (Objects and Classes) 193


Prog. import [Link].*;
public class Student
{
String name;
int eng, hn, mts;
double total, avg;
public void accept( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter name the student: ");
name = [Link]( );
[Link]("Enter marks in English: ");
eng = [Link]( );
[Link]("Enter marks in Hindi: ");
hn = [Link]( );
[Link]("Enter marks in Maths: ");
mts = [Link]( );
}
public void compute( )
{
total = eng + hn + mts;
avg = total / 3.0;
}
public void display( )
{
[Link]("Name: " + name);
[Link]("Marks in English: " + eng);
[Link]("Marks in Hindi: " + hn);
[Link]("Marks in Maths: " + mts);
[Link]("Total Marks: " + total);
[Link]("Average Marks: " + avg);
}
public static void main(String args[ ])
{
Student ob = new Student( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.14 Define a class called ParkingLot with the following description:
Class name : ParkingLot
Instance variables/Data members:
int vno : to store the vehicle number
int hours : to store the number of hours the vehicle is parked in
the parking lot
double bill : to store the bill amount

194
Member methods:
void input( ) : to input the vno and hours
void calculate( ) : to compute the parking charges at the rate of Z 3 for
the first hour or the part thereof and Z 1.50 for each
additional hour or part thereof.
void display( ) : to display the detail
Write a main method to create an object of the class and call the above
methods.
Prog. import [Link].*;
public class ParkingLot
{
String vno;
int hours;
double bill;
public void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter vehicle number: ");
vno = [Link]( );
[Link]("Enter hours: ");
hours = [Link]( );
}
public void calculate( )
{
if (hours <= 1)
bill = 3;
else
bill = 3 + (hours – 1) * 1.5;
}
public void display( )
{
[Link]("Vehicle number: " + vno);
[Link]("Hours: " + hours);
[Link]("Bill: " + bill);
}
public static void main(String args[ ])
{
ParkingLot ob = new ParkingLot( );
[Link]( );
[Link]( );
[Link]( );
}
}

Class as the Basis of all Computation (Objects and Classes) 195


Q.15 Design a class RailwayTicket with following description:
Class name : RailwayTicket
Instance variables/Data members:
String name : to store the name of the customer
String coach : to store the type of coach customer wants to travel
long mobno : to store customer's mobile number
int amt : to store basic amount of ticket
int tamt : to store the amount to be paid after updating the
original amount
Member methods:
void accept( ) : to take input for name, coach, mobile number and
amount.
void update( ) : to update the amount as per the coach selected (extra
amount to be added in the amount as follows)

Type of Coaches Amount


First_AC Z 700
Second_AC Z 500
Third_AC Z 250
Sleeper None
void display( ) : to display all the details of a customer such as name,
coach, total amount and mobile number.
Write a main method to create an object of the class and call the above
member methods.
Prog. import [Link].*;
public class RailwayTicket
{
String name, coach;
long mobno;
int amt, tamt;
void accept( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]( );
[Link]("Enter coach : ");
coach = [Link]( );
[Link]("Enter mobile number: ");
mobno = [Link]( );
[Link]("Enter amount: ");
amt = [Link]( );
}
void update( )
{
if([Link]("First_AC"))
tamt = amt + 700;
else if([Link]("Second_AC"))

196
tamt = amt + 500;
else if([Link]("Third_AC"))
tamt = amt + 250;
else if([Link]("Sleeper"))
tamt = amt;
}
void display( )
{
[Link]("Name: " + name);
[Link]("Coach : " + coach);
[Link]("Total Amount: " + tamt);
[Link]("Mobile number: " + mobno);
}
public static void main(String args[ ])
{
RailwayTicket ob = new RailwayTicket( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.16 Define a class with the following specifications:
Class name : Student
Member variables:
name : name of the student
age : age of the student
mks : marks obtained
[Declare the variables using appropriate data types]
Member methods:
void accept( ) : to accept the name, age and marks using scanner
class
void allocate( ) : to allocate the stream as per the following
specifications
Marks (mks) Stream
>=300 Science and Computer
>=200 and <300 Commerce and Computer
>=75 and <200 Arts and Animation
<75 Try Again
void print( ) : to display student's name, age, mks and stream
allocated
Call all the above methods in main method using an object.

Class as the Basis of all Computation (Objects and Classes) 197


Prog. import [Link].*;
public class Student
{
String name, stream;
int age, marks;
public void accept( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]( );
[Link]("Enter age: ");
age = [Link]( );
[Link]("Enter marks: ");
marks = [Link]( );
}
public void allocate( )
{
if (marks >= 300)
stream = "Science and Computer";
else if (marks >= 200 && marks < 300)
stream = "Commerce and Computer";
else if (marks >= 75 && marks < 200)
stream = "Arts and Animation";
else
stream = "Try Again!";
}
public void print( )
{
[Link]("Name\t\tAge\tMarks\tStream Alloted");
[Link](name + "\t" +age+"\t" +marks + "\t" + stream);
}
public static void main(String args[ ])
{
Student ob = new Student( );
[Link]( );
[Link]( );
[Link]( );
}
}

198
Chapter 7

Constructors

V. Answer the following:


1. What is meant by a constructor?
Ans. A constructor is a member method that is written with the same name
as the class name and is used to initialise the data members or instance
variables. It is invoked at the time of creating any object of the class.
For example,
Car hybrid = new Car( );
In the above example, Car( ) is invoking a default constructor.
2. Name the different types of constructors used while defining a class.
Ans. The four types of constructors are:
(i) Default Constructor.
(ii) Non-Parameterised constructor
(iii) Parameterised constructor
(iv) Copy constructor
3. Why do we need a constructor as a class member?
Ans. A constructor is used to initialise the instance variables (data members)
belonging to an object.
4. Explain the following terms:
(a) Constructor with default argument
Ans. A constructor that is used to initialise the instance variables with default
initial values, is known as Default Constructor. When no constructor is
defined in a program, the compiler creates a constructor on its own. As
soon as, an object of a class is created, it uses this constructor to initialise
the instance variables with system approved initial values.
(b) Parameterised constructor
Ans. Parameterised constructor is a member function with the same name as
the class name that is used to initialise the object variables by passing
values while creation of an object.
(c) Copy constructor
Ans. A constructor that is used to initialise 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
Ans. The process of using a number of constructors with the same name
with different parameters is known as 'Constructor Overloading'. If
a class contains more than one constructor then the constructors are
automatically overloaded.

199
5. Why is an object not passed to a constructor by value? Explain.
Ans. An object is not passed to a constructor by value because objects are
non-primitive data types so they are passed by reference. If we pass the
objects by value to the constructor to copy actual parameters to formal
parameters then it will cause Java to invoke the constructor again and
this will lead to an endless circular loop.
6. State the difference between constructor and method.
Ans. Constructor Method
Constructor name is same as the Method name is different from
class name. the class name.
Constructor is used only to Method is used to perform
initialise the data members. arithmetical or logical operations
also.
Constructors are automatically Methods need to be overloaded.
overloaded.
7. Explain two features of a constructor.
Ans. (i) A constructor has the same name as the class name.
(ii) A constructor is used for initialising the data members.
8. Distinguish between parameterised constructor and non-parameterised
constructor.
Ans. A parameterised constructor is a constructor which is defined along with
formal parameters whereas, a non-parameterised constructor is defined
without any formal parameter.
For example,
(i) Parameterised Constructor:
class Sample
{
int a;
Sample(int n) // Parameterised constructor
{
a=n;
}
}
(ii) Non-Parameterised Constructor:
class Sample
{
int a;
Sample( ) // Non-Parameterised constructor
{
a=5;
}
}
9. Name two ways of creating objects in a constructor.
Ans. (i) Objects created by a complier
(ii) Objects created by a programmer

200
10. Differentiate between the following statements:
(i) abc p = new abc( ); (ii) abc p = new abc(5,7,9);
Ans. (i) abc p = new abc( );
The first statement is calling a non-parameterised constructor to
create and initialise an object p of class abc.
(ii) abc p = new abc(5,7,9);
The second statement is calling a parameterised constructor which
accepts three arguments to create and initialise an object p of class abc.
11. Fill in the blanks to design a class:
Ans. class Area
{
int l, b;
Area(int x, int y)
{
l = x;
b = y;
}
}
VI. Unsolved Programs in Java based on Constructors:
Q.1 An electronics shop has announced a special discount on the purchase
of Laptops as given below:
Category Discount on Laptop
Up to Z 25,000 5.0%
Z 25,001 – Z 50,000 7.5%
Z 50,001 – Z 1,00,000 10.0%
More than Z 1,00,000 15.0%
Define a class Laptop described as follows:
Data members/instance variables:
name, price, dis, amt
Member Methods:
(i) a parameterised constructor to initialise the data members
(ii) to accept the details (name of the customer and the price)
(iii) to compute the discount
(iv) 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.
Prog. import [Link].*;
public class Laptop
{
String name;
int price;
double dis, amt;
public Laptop(String st, int pr)
{
name = st;
price = pr;
}
Constructors 201
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( )
{
[Link]("Name: " + name);
[Link]("Discount: " + dis);
[Link]("Amount to be paid: " + amt);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter customer name: ");
String str = [Link]( );
[Link]("Enter price: ");
int p = [Link]( );
Laptop ob = new Laptop(str, p);
[Link]( );
[Link]( );
}
}
Q.2 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 initialise num with n, f and rev with 0 (zero)
int prime( ) : to return 1, if the number is prime
int reverse( ) : to return the reverse of the number
void display( ) : to check and print whether the number is a prime
palindrome or not
Prog. import [Link].*;
public class Calculate
{
int num, f, rev;
Calculate(int n)
{
num = n;
f = 0;

202
rev = 0;
}
int prime( )
{
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
c = c + 1;
}
if (c == 2)
return 1;
else
return 0;
}
int reverse( )
{
int s = 0;
int n = num;
while (n > 0)
{
int r = n % 10;
s = s * 10 + r;
n = n / 10;
}
return s;
}
void display( )
{
if (num == reverse( ) && prime( ) == 1)
[Link](num + " is prime palindrome.");
else
[Link]("The number is not prime palindrome.");
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a number");
int number = [Link]( );
Calculate ob = new Calculate(number);
[Link]( );
}
}
Q.3 Define a class Arrange described as below:
Data members/instance variables:
String str (a word), i, p (to store the length of the word), char ch
Member Methods:
(i) a parameterised constructor to initialise the data member
(ii) to accept the word

Constructors 203
(iii) to arrange all the letters of word in ascending order of their ASCII
values without using the sorting technique
(iv) to display the arranged letters
Write a main method to create an object of the class and call the above
member methods.
Prog. import [Link].*;
public class Arrange
{
String str, i;
int p;
char ch;
public Arrange(String s)
{
str = s;
i = " ";
p = [Link]( );
ch = 0;
}
public void rearrange( )
{
for (int a = 65; a <= 90; a++)
{
for (int j = 0; j < p; j++)
{
ch = [Link](j);
if (ch= =(char)a)
i += ch;
}
}
for (int a = 97; a <= 122;; a + +)
{
for (int j = 0; j < p; j++)
{
ch = [Link](j);
it(ch = = (char)a)
i += ch;
}
}
}
public void display( )
{
[Link]("Alphabet in ascending order:");
[Link](i);
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a word: ");

204
String word = [Link]( );
Arrange ob = new Arrange(word);
[Link]( );
[Link]( );
}
}
Q.4 Write a program by using a class in Java with the following specifications:
Class name : Stringop
Data members : String str
Member functions:
Stringop( ) : to initialise 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.
Example: A with C, B with D and so on.
void print( ) : to print each word of the String in a separate line
Prog. import [Link].*;
public class Stringop
{
String str;
public Stringop( )
{
str = null;
}
void accept( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a sentence");
str = [Link]( );
}
void encode( )
{
String value = str;
str = "";
for(int i = 0; i< [Link]( ); i++)
{
char ch = [Link](i);
if((ch !=' ')&&(ch >='a' && ch <= 'x'))
str = str + ((char)(ch + 2));
else if ((ch !=' ')&&(ch >='A' && ch <= 'X'))
str = str + ((char)(ch + 2));
else if ((ch !=' ')&&(ch =='y'))
str = str + "a";
else if ((ch !=' ')&&(ch =='Y'))
str = str + "A";
else if ((ch !=' ')&&(ch =='z'))
str = str + "b";
else if ((ch !=' ')&&(ch =='Z'))

Constructors 205
str = str + "B";
else
str = str + ch;
}
}
void print( )
{
String val = "";
str = str + " ";
for(int i=0;i<[Link]( );i++)
{
char ch = [Link](i);
if(ch != ' ')
val = val + ch;
else
{
[Link](val);
val = "";
}
}
}
public static void main(String args[ ])
{
Stringop ob = new Stringop( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.5 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 initialise p and r with a and b
respectively.
void print( ) : to calculate and print the population of each
year from 2001 to 2007.
Prog. import [Link].*;
public class Population
{
float p, r;
public Population(int a, float b)
{

206
p = a;
r = b;
}
void print( )
{
float np;
for(int i = 2001; i<=2007; i++)
{
np = p*(1+(r/100));
[Link]("Population at end of year "+i+": "+(int)np);
p=np;
}
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
[Link]("Enter the population at the starting of year 2000 : ");
int p = [Link]( );
[Link]("Enter the population growth rate : ");
float r = [Link]( );
Population ob = new Population(p, r);
[Link]( );
}
}
Q.6 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 and d is
the discriminant), r1 and r2 are the roots of the
equation.
Member Methods:
Quad(int x,int y,int z) : to initialise 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
Prog. import [Link].*;
public class Quad
{
float a, b, c, d, r1, r2;
Quad(int x, int y, int z)
{
a = x;
b=y;
c=z;
d=0;
}
void calculate( )

Constructors 207
{
d = (b*b)–(4*a*c);
if(d<0)
[Link]("Roots not possible");
else
{
r1 = (float) ((–b + [Link](d))/2*a);
r2 = (float) ((–b – [Link](d))/2*a);
[Link]("Roots of the equation are : "+r1+", "+r2);
}
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int a, b, c;
[Link]("Enter the coefficients a, b, c:");
a = [Link]( );
b = [Link]( );
c = [Link]( );
Quad ob = new Quad(a, b, c);
[Link]( );
}
}
Q.7 Define a class named FruitJuice with the following description:
Class name : FruitJuice
Instance variables/Data members:
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:
(i) FruitJuice( ) : constructor to initialise integer data members to
0 and string data members to " "
(ii) void input( ) : to input and store the product code, flavour, pack
type, pack size and product price
(iii) void discount( ) : to reduce the product price by 10
Prog. import [Link].*;
public class FruitJuice
{
int product_code;
String flavour, pack_type;
int pack_size, product_price;
public FruitJuice( )
{
product_code = 0;

208
flavour = "";
pack_type = "";
pack_size=0;
product_price=0;
}
void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter the product code");
product_code = [Link]( );
[Link]("Enter the flavour");
flavour = [Link]( );
[Link]("Enter the pack type");
pack_type = [Link]( );
[Link]("Enter the pack size");
pack_size = [Link]( );
[Link]("Enter the product price");
product_price = [Link]( );
}
void discount( )
{
product_price = product_price –10;
}
void display( )
{
[Link]("Product code : "+product_code);
[Link]("Product flavour : "+flavour);
[Link]("Product pack type : "+pack_type);
[Link]("Product pack size : "+pack_size);
[Link]("Product price : "+product_price);
}
public static void main(String args[ ])
{
FruitJuice ob = new FruitJuice( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.8 The basic salary of employees is undergoing a revision. Define a class
called Grade_Revision with the following specifications:
Instance variables/Data members:
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)

Constructors 209
Member Methods:
Grade_Revision( ) : constructor to initialise all data members
void accept( ) : to input name, basic and experience
void increment( ) : to calculate increment with the following
specifications:
Experience Increment
Up to 3 years Z 1,000 + 10% of basic
3 years or more and up to 5 years Z 3,000 + 12% of basic
5 years or more and up to 10 years Z 5,000 + 15% of basic
10 years or more Z 8,000 + 20% of basic
void display( ) : to display all the details of an employee
Write the main method to create an object of the class and call all the
member methods.
Prog. import [Link].*;
public class Grade_Revision
{
String name;
int bas, expn;
double inc, nbas;
public Grade_Revision( )
{
name = "";
bas = 0;
expn = 0;
inc = 0.0;
nbas = 0.0;
}
void accept( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter the name of the employee");
name = [Link]( );
[Link]("Enter basic salary of the employee");
bas = [Link]( );
[Link]("Enter experience of the employee");
expn = [Link]( );
}
void increment( )
{
if(expn<=3)
{
inc = 1000+((double) 10/100*bas);
nbas = bas+inc;
}
else if(expn>3 && expn<=5)
{

210
inc = 3000+((double) 12/100*bas);
nbas = bas+inc;
}
else if(expn>5&&expn<=10)
{
inc = 5000+((double) 15 /100*bas);
nbas = bas+inc;
}
else
{
inc = 8000+((double) 20 /100*bas);
nbas = bas+inc;
}
}
void display( )
{
[Link]("Name of the employee: "+ name);
[Link]("Basic salary of the employee: "+ bas);
[Link]("Experience of the employee: "+expn);
[Link]("Salary increment: "+inc);
[Link]("New basic salary of the employee: "+nbas);
}
public static void main(String args[ ])
{
Grade_Revision ob = new Grade_Revision( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.9 Define a class called Student to check whether a student is eligible for
taking admission in class XI with the following specifications:
Instance variables/Data members:
String name : to store name
int mm : to store marks secured in Maths
int scm : to store marks secured in Science
int comp : to store marks secured in Computer
Member Methods:
Student( ) : parameterised constructor to initialise the data members
by accepting the details of a student
check( ) : to check the eligibility for course with the following
conditions:
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 Science with Hindi
less than 90%

Constructors 211
Write the main method to create an object of the class and call all the
member methods.
Prog. import [Link].*;
public class Student
{
int mm, scm, comp;
public Student(int maths, int science, int computer)
{
mm = maths;
scm = science;
comp = computer;
}
void check( )
{
if(mm>=90 && scm>=90 && comp>=90)
[Link]("Science with computer");
if(((mm+scm+comp)/3)>=90)
[Link]("Bio-Science");
if((((mm+scm+comp)/3)>=80) && (((mm+scm+comp)/3)<90))
[Link]("Science with Hindi");
}
void display( )
{
check( );
}
public static void main(String args[ ])
{
Scanner in = new Scanner([Link]);
int maths, science, computer;
[Link]("Enter the marks in maths : ");
maths = [Link]( );
[Link]("Enter the marks in science : ");
science = [Link]( );
[Link]("Enter the marks in computer : ");
computer = [Link]( );
Student ob = new Student(maths, science, computer);
[Link]( );
}
}
Q.10 Define a class Bill that calculates the telephone bill of a consumer with
the following description:
Instance variables/Data members:
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

212
Member Methods
Bill( ) : constructor to initialise 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 following conditions

Units consumed Rate


First 100 calls Z 0.60 / call
Next 100 calls Z 0.80 / call
Next 100 calls Z 1.20 / call
Above 300 calls Z 1.50 / call
Fixed monthly rental applicable to all consumers: Z 125
Create an object in the main( ) method and invoke the above functions
to perform the desired task.
Prog. import [Link].*;
public class Bill
{
int bno, call;
String name;
double amt;
Bill( )
{
bno = 0;
name = "";
call = 0;
amt = 0.0;
}
Bill(int billNumber, String n, int c, double amount)
{
bno = billNumber;
name = n;
call = c;
amt = amount;
}
void calculate( )
{
if (call <= 100)
amt = call * 0.60;
else if (call > 100 && call <= 200)
amt = 100 * 0.60 + ((call – 100) * 0.80);
else if (call > 200 && call <= 300)
amt = 100 * 0.60 + (100 * 0.80) + ((call – 200) * 1.20);
else
amt = 100 * 0.60 + (100 * 0.80) + (100 * 1.20) + ((call – 300) * 1.50);
amt = amt + 125;

Constructors 213
}
void display( )
{
[Link]("Bill number: " + bno);
[Link]("Name: " + name);
[Link]("Number of calls: " + call);
[Link]("Bill amount: " + amt);
}
public static void main(String args[ ])
{
Bill ob = new Bill(123, "Abhishek", 250, 0.0);
[Link]( );
[Link]( );
}
}
Q.11 Define a class called BookFair with the following description:
Instance variables/Data members:
String Bname : stores the name of the book
double price : stores the price of the book
Member Methods:
(i) BookFair( ) : constructor to initialise data members
(ii) void input( ) : to input and store the name and price of the book
(iii) void calculate( ) : to calculate the price after discount. Discount is
calculated based on the following criteria:
Price Discount
Less than or equal to Z 1000 2% of price
More than Z 1000 and less than or equal to Z 3000 10% of price
More than Z 3000 15% of price
(iv) void display( ) : to display the name and price of the book after
discount
Write a main method to create an object of the class and call the above
member methods.
Prog. import [Link].*;
public class BookFair
{
String Bname;
double price;
BookFair( )
{
Bname = "";
price = 0.0;
}
void input( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter the name of the book:");
Bname = [Link]( );

214
[Link]("Enter the price of the book:");
price = [Link]( );
}
void calculate( )
{
if (price <= 1000)
price = price – ((double) 2 / 100 * price);
else if (price > 1000 && price <= 3000)
price = price – ((double) 10 / 100 * price);
else
price = price – ((double) 15 / 100 * price);
}
void display( )
{
[Link]("Name of the book: " + Bname);
[Link]("Price of the book: " + price);
}
public static void main(String args[ ])
{
BookFair ob = new BookFair( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.12 A private Cab service company provides service within the city at the
following rates:

Distance AC Car Non AC Car


Up to 5 km Z 150 Z 120
Beyond 5 km Z 12/- per km Z 10/- per km
Design a class CabService with the following description:
Member variables /data members:
String car_type : to store the type of car (AC or Non AC)
double km : to store the kilometres travelled
double bill : to calculate and store the bill amount
Member methods:
CabService( ) : Default constructor to initialise data members
String data members to '' '' and double data members
to 0.0
void accept ( ) : to accept car_type and km (using Scanner class only)
void calculate ( ) : to calculate the bill as per the rules given above.
void display( ) : to display the bill as per the following format
Car Type:
Kilometer Travelled:
Total Bill:
Create an object of the class in the main method and invoke the member
methods.

Constructors 215
Prog. import [Link].*;
public class CabService
{
String car_type;
double km, bill;
CabService( )
{
car_type = "";
km = 0.0;
bill = 0.0;
}
void accept( )
{
Scanner in = new Scanner([Link]);
[Link]("Enter car type 'AC Car' or 'Non AC Car' : ");
car_type = [Link]( );
[Link]("Enter kilometres : ");
km = [Link]( );
}
void calculate( )
{
if(car_type.equals("AC Car"))
{
if (km <= 5)
bill = 150;
else
bill = 150 + (km – 5)*12;
}
else if(car_type.equals("Non AC Car"))
{
if(km <= 5)
bill = 120;
else
bill = 120 + (km – 5)*10;
}
}
void display( )
{
[Link]("Car Type: " + car_type);
[Link]("Kilometer travelled: " + km);
[Link]("Total bill: " + bill);
}
public static void main(String args[ ])
{
CabService ob = new CabService( );
[Link]( );
[Link]( );
[Link]( );
}
}

216
Chapter 8

Encapsulation and Inheritance

V. Answer the following:


1. What is Encapsulation?
Ans. Encapsulation is an Object Oriented Programming (OOP)principle. In
OOP, the data and functions are grouped or merged together in such a
way that the data items are only accessible within the functions of the
same object. The function provides an interface between data items of the
objects and the calling program. Encapsulation focuses more on hiding
the complexity of the system by binding data and functions together
into a single unit.
2. In what way does a class enforce data hiding?
Ans. Data hiding promotes the use of data members of a class within the
same class. In no case, they can be used in another class or the main
class, although they are present in the same program. The class enforces
data hiding by the use of access specifiers. The different types of access
specifiers used for declaration of variables and functions are Public,
Private and Protected. The broad scope of the access specifiers are as
follows:
Access Specifiers Scope of usage
Private Private members are accessed only within the scope
of a class.
Public Public members can also be accessed outside the
class visibility.
Protected Protected members are used simply as private
members within the class in which they exist but can
be accessed to derived class (during inheritance).
Hence, if the data members are declared private, their accessibility
remains limited up to the class block and same cannot be accessed
outside the class block thereby enforcing data hiding to the outside
world.
3. What are the types of visibility modes used in Java?
Ans. Visibility Modes or Access specifiers are the terms used to specify the
extent of usage of the class members (instance variables or member
methods) in the program. They indicate that the program area under
which a class member (data member or member method) is visible or
accessible. Access specifiers or visibility modes can be categorised as:
(i) Public: The public class members (variables or methods) can even
be used inside or outside the visibility of a class.

217
Syntax of declaring public data member(s):
<access specifier> <data type> <variable(s)>;
For example,
public int a, b, c;
or,
int a, b, c;
Syntax of defining a public member method:
<access specifier> <return type> <method name>( );
For example,
public void getdata( );
or,
void getdata( );
In case, a class member is declared without an access specifier then
it means that the class member will be public (by default). Hence,
specifying instance variables or member methods public is optional.
(ii) Private: The private data members or member methods which are
specified as private are used only within the scope of a class. These
members cannot be accessed outside the visibility of a class.
Syntax of declaring private data member(s):
<access specifier> <data type> <variable(s)>;
For example,
private int a, b, c;
Syntax of defining a private member method:
<access specifier> <return type> <method name>( )
For example,
private void getdata( );
(iii) Protected:
The protected members are used in the class as private members
and can only be accessed within the class but they can be used in
another class during inheritance.
Syntax of declaring protected data member(s):
<access specifier> <data type> <variable(s)>;
For example,
protected int a, b, c;
Syntax of defining a protected member method:
<access specifier> <return type> <method name>( );
For example,
protected void getdata( );
4. What will happen, if data members are declared private?
Ans. The data members (instance variables) or member methods which are
specified as private are used only within the scope of a class. These
members cannot be accessed outside the visibility of a class.
Syntax of declaring private data member(s):
<access specifier> <data type> <variable(s)>;
For example,
private int a, b, c;

218
5. What do you understand by 'Inheritance '?
Ans. It is a term derived from biology which means the transfer of
characteristics.
Inheritance is an Object Oriented Programming principle. In Java, some
properties of a class are also transferred/ inherited to another class in
order to share data members or member methods. Hence, a process by
which some properties of a class are shared by another class or classes
is known as 'Inheritance '.
Inheritance uses the concept of base class and derived class. Base
class can be referred to as the parent class which possesses its own
unique characteristics or traits in the form of member methods or
member variables. In inheritance, the derived class inherits the features
and characteristics of the base class apart from its own features and
characteristics.
6. What is meant by base class?
Ans. Inheritance is an OOP principle in which new classes are created
or derived. The class by which a new class derives its features and
characteristics is known as the 'Base class'. A base class can be derived
from another class by using only the public, private and protected modes
of inheritance.
7. Differentiate between super class and target.
Ans. A class that is inherited by another class is said to be the base class
or super class whereas a class that inherits a base class is known as
the derived class or target. The derived or target class may consist of
additional features or characteristics in addition to the features and
characteristics possessed by its super or base class.
8. What is the significance of using protected declaration during inheritance?
Show with the help of an example.
Ans. A class member declared to be protected acts as a private member of the
class (i.e., cannot be used outside the class premises) but can be accessed
to its derived class during inheritance. Syntax of declaring protected data
member(s):
<access specifier> <data type> <variable(s)>;
For example,
protected int a,b,c;
Syntax of defining a protected member method:
<access specifier> <return type> <method name>( );
For example,
protected void getdata( );
class Abc
{
protected int a;
void get a( )
{
a=5;
}
}
class Xyz extends Abc

Encapsulation and Inheritance 219


{
private int x, z;
void getx( )
{
x=10;
}
void add( )
{
z=x+a;
}
void display( )
{
[Link](z);
}
}
In the above example, class Xyz inherits class Abc. The protected member
variable 'a' of class Abc is available in class Xyz and the final output of
variable 'z' is 15.
9. By default, the Main class is inherited by another class. Explain this
statement.
Ans. In Java, Object class is the base class for all other classes. All other classes,
either directly or indirectly are derived from the Object class. If a class
does not inherit other class then by default it becomes the child of the
Object class.
10. With the help of an example, explain how you can access a private
member of a base class.
Ans. The private members of the base class cannot be accessed directly in the
derived class. However, they can be accessed through a public method
of the base class.
For example,
class A
{
private int x;
public A( )
{
x = 10;
}
public int getX( )
{
return x;
}
}
class B extends A
{
public void showX( )
{
[Link]("Value of x = " + getX( ));
}
}

220
11. Why is the main method in Java so special?
Ans. The main method in Java is a static method and is the starting point for
all programs. The Java Virtual Machine by default calls the main method
at first when the execution of the program starts which in-turn initialises
and executes other program blocks.
12. What is meant by scope of variables? Show its application with the help
of an Example.
Ans. The scope of variables refers to the extent to which a variable can be used
in a program. A variable is used within the block in which it is declared.
Its application outside the block is restricted.
For example:
class Test
{
int b = 8;// instance variable
static int a = 5; //class variable
public void check( )
{
int p=1;
if(a < b)
{
int c = b – a; // c as the local variable
p=c*2;
}
[Link](p);
}
}
13. Based on the scope of usage, define the following:
(i) Instance variable
(ii) Class variable
(iii) Local variable
Ans. Based on the scope of usage, the variables can be categorised into three
types:
(i) Instance variables: The variables that are declared within a class
outside the member methods are said to be instance variables. They
are also called as data members. The life time of instance variables
is up to the end of the class.
(ii) Class variables: The class variable is a variable declared within
the class along with a keyword 'static'. It is also called static data
member. The basic difference between a non-static instance variable
and a static variable is that a non-static instance variable is a separate
copy whereas, a class or static variable happen to be a common copy
for all the objects of the class.
(iii) Local variables: The local variable is a variable that is declared within
a function or method. The local variables are used to hold the values
temporarily during any operation. Local variables are used only
within the scope of the function under which they are declared.

Encapsulation and Inheritance 221


14. In what way does the access specifier of the base class have access control
over the derived class? Show with the help of an example.
Ans. (i) Private members of the base class cannot be accessed in the derived
class.
(ii) Public members of the base class can be used in the derived class.
(iii) Protected members of the base class can be used in the derived class.
For example:
class Abc
{
protected int a;
private int b;
int c;
void geta( )
{
a=5;
b=7;
c=9;
}
}
class Xyz extends Abc
{
private int x,z;
void getx( )
{
x=8;
}
void add( )
{
z=x+a+b+c; //compilation error
}
void display( )
{
[Link](z);
}
}
Note: There is a compilation error because the variable b is declared as private
in the base class, so it is not accessible in the derived class. Once, you declare
the variable b either public or protected, it will produce the desired result.

15. Suppose, 'Happening' and 'Accident' are two classes. What will happen
when 'Happening' class derives from 'Accident' class by using private
visibility?
Ans. It will result in an error. It is because unlike C++, Java does not support
private or protected mode of inheritance for classes.
16. In what circumstances data members or methods should be declared
public or private in a class?
Ans. Data members and methods should be declared private when their
access need to be restricted within the class. This keeps class and its

222
members more secure. However, the data members and methods should
be declared public when they are supposed to be accessed outside the
class. This is comparatively less secure than private.
17. Describe the methods of accessing the data members and member
functions of a class in the following cases:
(a) in the member function of the same class.
(b) in the member function of another class.
(c) in the member function of base class.
Ans. (a) In the member function of the same class, all the data members and
member functions of a class are accessible.
(b) In the member function of another class, the public and protected
data members and member functions will be accessible, if the other
class is a sub-class of the main class.
(c) In the member function of base class, data members and member
functions of the derived class are not accessible.
18. Can a private member be accessed by
(a) a member of the same class?
Ans. Yes
(b) a member of other class?
Ans. No
(c) a function which is not a member function?
Ans. No
19. Show with the help of an example, how the following base class Elect
can be derived in class Bill to fulfill the given requirement:
class Elect
{
String n;
float units;
public void setvalue( )
{
n="SOURABH";
units=6879;
}
}
The class Bill uses data member charge and a member function to
calculate the bill at the rate of Z 3.25 per unit and displays the charge
using data member as private visibility.
Ans. The class Elect can be derived in class Bill as shown below:
class Elect
{
String n;
float units;
public void setvalue( )
{
n="SOURABH";
units=6879;
}

Encapsulation and Inheritance 223


}
class Bill extends Elect
{
private double charge;
public void calc( )
{
charge = 3.25 * units;
[Link]("Name = " + n);
[Link]("Charge = " + charge);
}
}
VI. Unsolved Java Programs on Encapsulation and Inheritance:
Q.1 Write a program by using a class with the following specifications:
Class name : Prime
Data members : private int n
Member functions:
void input( ) : to input a number
void checkprime( ) : to check and display whether the number is prime
or not
Use a main function to create an object and call member functions of the
class.
Prog. import [Link].*;
public class Prime
{
private int n;
void input( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number : ");
n = [Link]( );
}
void checkprime( )
{
int i, c = 0;
for (i = 1; i <= n; i++)
{
if (n % i == 0)
c = c + 1;
}
if (c == 2)
[Link](n + " is a prime number");
else
[Link](n + " is not a prime number");
}
public static void main(String args [])
{
Prime ob = new Prime( );

224
[Link]( );
[Link]( );
}
}
Q.2 Write a program by using a class with the following specifications:
Class name : Factorial
Data members : private int n
Member functions:
void input( ) : to input a number
void fact( ) : to find and print the factorial of the number
Use a main function to create an object and call member functions of the
class.
Prog. import [Link].*;
public class Factorial
{
private int n;
void input( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number : ");
n = [Link]( );
}
void fact( )
{
int f = 1;
for (int i = 1; i <= n; i++)
f = f * i;
[Link]("Factorial of " + n +" is "+ f);
}
public static void main(String args [])
{
Factorial ob = new Factorial( );
[Link]( );
[Link]( );
}
}
Q.3 Write a program by using a class with the following specifications:
Class name : Salary
Data members : private int basic
Member functions:
void input( ) : to input basic pay
void display( ) : to find and print the following:
da = 30% of basic,
hra = 10% of basic,
gross = basic + da + hra
Use a main function to create an object and call member functions of the
class.

Encapsulation and Inheritance 225


Prog. import [Link].*;
public class Salary
{
private int basic;
void input( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter basic salary : ");
basic = [Link]( );
}
void display( )
{
double da = ((double) 30/100) * basic;
double hra = ((double) 10/100) * basic;
double gross = basic + da + hra;
[Link]("Basic : " + basic);
[Link]("DA : " + da);
[Link]("HRA : " + hra);
[Link]("Gross : " + gross);
}
public static void main(String args[ ])
{
Salary ob = new Salary( );
[Link]( );
[Link]( );
}
}
Q.4 Write a class program with the following specifications:
Class name : Matrix
Data members : int array m[][] with 3 rows and 3 columns
Member functions:
void getdata( ) : to accept the numbers in the array
void rowsum( ) : to find and print the sum of the numbers of each
row
void colsum( ) : to find and print the sum of numbers of each
column
Use a main function to create an object and call member functions of the
class.
Prog. import [Link].*;
public class Matrix
{
int m[ ][ ] = new int[3][3];
void getData( )
{
Scanner sc = new Scanner([Link]);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)

226
{
[Link]("Enter matrix element :");
m[i][j] = [Link]( );
}
}
}
void rowsum( )
{
int i, j, sum;
for (i = 0; i < 3; i++)
{
sum = 0;
for (j = 0; j < 3; j++)
{
sum = sum + m[i][j];
}
[Link]("Sum for row number " + (i + 1) + " : " + sum);
}
}
void colsum( )
{
int i, j, sum;
for (i = 0; i < 3; i++)
{
sum = 0;
for (j = 0; j < 3; j++)
{
sum = sum + m[j][i];
}
[Link]("Sum for column number " + (i + 1) + " : " + sum);
}
}
public static void main(String args[ ])
{
Matrix ob = new Matrix( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.5 Write a program to use a class Account with the following specifications:
Class name : Account
Data members : long acno, double balance
Member Methods:
Account (long a, double b) : to initialise acno = a, balance = b
void withdraw(int w) : to maintain the balance with withdrawal
(balance – w)
void deposit(int d) : to maintain the balance with the deposit
(balance + d)

Encapsulation and Inheritance 227


Use another class Calculate which inherits class Account with the
following specifications:
Data members : int double, t; double si, amt;
Member Methods:
void accept(double x, double y) : to initialise r=x,t=y,amt=0
void compute( ) : to find simple interest and amount
si = (balance * r * t)/100;
a = a + si;
void display( ) : to print account number, balance,
interest and amount
The main( ) function need not to be used.
Prog. import [Link].*;
public class Account
{
protected long acno;
protected double balance;
public Account(long a, double b)
{
acno = a;
balance = b;
}
public void withdraw(int w)
{
balance –= w;
}
public void deposit(int d)
{
balance += d;
}
}
import [Link].*;
public class Calculate extends Account
{
double r, t;
double si, amt;
public Calculate(long a, double b)
{
super(a, b);
}
public void accept(double x, double y)
{
r = x;
t = y; Note: The keyword 'super' is
amt = 0; used to implement the value
} of parameterised constructor
public void compute( ) Account(long a, double b) in the
derived class.
{
si = (balance * r * t)/100.0;

228
amt = si + balance;
}
public void display( )
{
[Link]("Account Number: " + acno);
[Link]("Balance: " + balance);
[Link]("Interest: " + si);
[Link]("Amount: " + amt);
}
}
Q.6 Write a program by using class with the following specifications:
Class name : Sale
Data members/Instance variables:
String title, author, publication
double price
Member methods:
void input( ) : to accept title, author name and publication name
and price of a book
void display( ) : to display title, author name and publication name
and price of a book
Now, create another class 'Purchase' that inherits class 'Sale' having the
following specifications:
Class name: Purchase
Data members/Instance variables:
int noc
int amount;
Member methods:
void accept( ) : to enter the number of copies purchased
void calculate( ) : to find the amount by multiplying number of copies
ordered and price (i.e., noc * price)
void show( ) : to display the elements described in base class along
with the number of copies purchased and amount to
be paid to the shopkeeper
Prog. import [Link].*;
public class Sale
{
String title, author, publication;
double price;
void input( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter book title:");
title = [Link]( );
[Link]("Enter author's name:");
author = [Link]( );
[Link]("Enter publication's name:");
publication = [Link]( );
[Link]("Enter price of the book:");

Encapsulation and Inheritance 229


price = [Link]( );
}
void display( )
{
[Link]("Title of the book : " + title);
[Link]("Author's Name : " + author);
[Link]("Publication's Name : " + publication);
[Link]("Price of book : " + price);
}
}
import [Link].*;
public class Purchase extends Sale
{
int noc;
int amount;
void accept( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter number of copies of the book : ");
noc = [Link]( );
}
void calculate( )
{
amount = (int) (noc*price);
}
void show( )
{
display( );
[Link]("Number of copies of the book : " + noc);
[Link]("Amount to be paid : " + amount);
}
public static void main(String args[ ])
{
Purchase ob = new Purchase( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
}
Q.7 Write a program to define class with the following specifications:
Class name : Number
Data members/Instance variables:
int n : to hold an integer number
Member methods:
void input( ) : to accept an integer number in n
void display( ) : to display the integer number input in n

230
Now, inherit class Number to another class Check that is defined with
the following specifications:
Class name : Check
Data members/Instance variables:
int fact
int revnum
Member methods:
void find( ) : to find and print the factorial of each digit of the
number used in base class
void palindrome( ): to check and print whether the number used in base
class is a palindrome number or not
[A number is said to be palindrome, if it appears the same after reversing
its digits. For example, 414, 333, 515, etc.]
Prog. import [Link].*;
public class Number
{
int n;
void accept( )
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
n = [Link]( );
}
void display( )
{
[Link]("The number : " + n);
}
}
import [Link].*;
public class Check extends Number
{
int fact;
int d, nnum, revnum;
void find( )
{
nnum= n;
while(nnum>0)
{
d=nnum%10;
fact = 1;
for (int i = 1; i <= d; i++)
{
fact = fact * i;
}
[Link]("Factorial of digit "+d+": "+fact);
nnum=nnum/10;
}
}
void palindrome( )

Encapsulation and Inheritance 231


{
int number = n;
revnum =0;
while (number>0)
{
int d = number%10;
revnum = (revnum*10)+d;
number = number/10;
}
if (revnum==n)
[Link]("The number is palindrome");
else
[Link]("The number is not palindrome");
}
public static void main (String args[ ])
{
Check ob = new Check( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
}

232

Common questions

Powered by AI

String methods such as `compareTo`, `indexOf`, `startWith`, and `equalsIgnoreCase` allow for comprehensive string handling. They enable comparisons, searches, prefix checks, and case-insensitive content comparisons, facilitating complex manipulations and logical operations on strings .

A number is considered a Sunny number if the square root of the subsequent number (n+1) is an integer. The program verifies this by computing the square root and checking if its square equals the subsequent number, indicating it is a perfect square .

Java uses access specifiers like public and private to control the visibility of class members. Public members are accessible outside the class, while private ones are not. Visibility affects inheritance; private members can't be accessed by derived classes, while protected ones can .

The method iterates through the string, checking each character against a set of vowel characters. If a vowel is encountered, it is skipped, and non-vowel characters are concatenated to form the new string, allowing for efficient vowel removal .

The program replaces words by iterating through the sentence character by character, building words, and comparing them with the target word. When a match is found, it replaces the word with the specified new word manually, reconstructing the sentence without using built-in replace functions .

The program uses a switch statement to present menu options to the user. For each menu choice, a different series calculation is implemented. For example, in calculating a series alternating sums and subtractions of powers of x, it checks even or odd indices using modulus operations and adjusts the sum accordingly .

The program checks if a number is perfect by calculating the sum of its factors, excluding the number itself. It iterates from 1 to the number minus 1, adding up the factors. If the sum equals the original number, it is a perfect number .

The program identifies even digits within the input number, then calculates the successor for each even digit and computes the product of these successors. It involves parsing digits and performing multiplications iteratively based on conditions .

A Tech Number is identified by splitting a number with even digits into two equal halves, calculating the square of their sum, and checking if it equals the original number. This involves integer partitioning, squaring, and comparison operations .

The program determines if two numbers are co-prime by finding their highest common factor (HCF). It iterates through numbers from 1 to the product of the two numbers, checking if each divides both numbers. The largest common divisor found is stored as HCF. If HCF is 1, the numbers are co-prime .

You might also like