Class 10 Computer App With BlueJ Notes
Class 10 Computer App With BlueJ Notes
Understanding ICSE
Computer Applications with Blue J
Contents
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.
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
6
Chapter 1 Revision of Class IX Syllabus
Part III
Values and Data Types
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
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.
10
Chapter 1 Revision of Class IX Syllabus
Part IV
Operators in Java
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
(--) (/)
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)
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
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.
Introduction to Java 19
Chapter 1 Revision of Class IX Syllabus
Part V(b)
Input in Java
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.
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
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);
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: ");
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);
}
}
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.
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.
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.");
}
}
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]);
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);
}
}
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;
}
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!");
}
}
}
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);
}
}
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;
50
Chapter 1 Revision of Class IX Syllabus
Part VIII
Iterative Constructs in Java
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.
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]( );
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);
}
}
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[])
{
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]( );
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);
}
}
}
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;
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;
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;
}
}
}
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: ");
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;
}
}
}
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
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]();
102
[Link]( );
}
break;
default:
[Link]("Incorrect Choice!!");
}
}
}
Arrays
(Single Dimensional and Double Dimensional)
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.
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] + ", ");
}
}
}
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];
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] + " ");
}
}
}
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: ");
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
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:
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.]
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;
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]);
124
Chapter 4
String Handling
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.
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++)
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);
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 == ' ')
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
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 = "";
}
}
}
}
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:");
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
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]( );
}
}
}
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");
}
}
}
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]);
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;
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!!".
150
Chapter 5
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.
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: ");
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
{
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: ");
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')
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:
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;
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
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)
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)
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++)
174
Chapter 6
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.
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:
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);
}
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
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);
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:
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);
}
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)
{
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.
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]( );
}
}
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.
198
Chapter 7
Constructors
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
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:
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
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
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.
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;
}
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.
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)
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:");
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( )
232
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 .