1550574902 0llcomputer Applications Icse10th Ans
1550574902 0llcomputer Applications Icse10th Ans
Computer Applications
Solution (ICSE)
X
Contents
Constructors.......................................................................................................... 170
Encapsulation......................................................................................................... 219
Arrays..................................................................................................................... 239
Mental Drill
5 Revision Tour I
7. Which among the following is a valid float literal?
a. 12.36f b. 12.36F
c. 12.36 d. Both a and b
Ans. d. Both a and b
8. Which among the following is a valid octal integer literal?
a. 0178 b. 675
c. 0675 d. 0X675
Ans. c. 0675
9. Which among the following is a valid method of initialising?
a. boolean f=true; b. boolean f=True;
c. boolean f=’true’; d. None of these
Ans. a. boolean f=true;
10. Which among the following is not a punctuator?
a. ; semicolon b. , comma
c. : colon d. . dot
Ans. d. . dot
11. Which among the following is not a primitive data type?
a. int b. float
c. String d. char
Ans. c. String
12. What is the largest possible value that can be stored in short data type?
a. 215-1 b. 231-1
c. 27-1 d. 263-1
Ans. a. 215-1
13. If a is of type int and b is of type float what would be the resultant data type of a+b?
a. int b. float
c. double d. short
Ans. b. float
B. State whether the following statements are True (T) or False (F).
1. Encapsulation refers to the art of hiding the complexities and giving a simple interface. F
2. Procedure Oriented Language follows top down approach. T
3. Java is an example of Object Oriented Language. T
Section A
Answer the following questions:
1. How are objects implemented in software?
Ans. In a software the characteristics of an object are represented through data members and
behaviour is represented through member functions.
2. What is abstraction? How is encapsulation related to it?
Ans. Abstraction is a principle of Object Oriented Programming (OOP) that hide certain details and
only show the essential features of the object.
3. Define Encapsulation.
Ans. Encapsulation is a principle of Object Oriented Programming (OOP) that binds together
characteristics and behaviour of an object into a single unit represented by a class.
7 Revision Tour I
4. What is Inheritance?
Ans. Inheritance is the concept that when a class of objects is defined, any subclass that is defined
can inherit the definitions of one or more general classes.
5. What is Object Oriented Programming?
Ans. Object Oriented Programming (or OOP) is a technique of implementing programs which are
organized as a co-interactive collection of objects, each of which represents an instance of a
class.
6. State three differences between Procedure Oriented Language and Object Oriented Languages.
Ans.
13. Give one example each of primitive data type and composite data type.
Ans. Primitive data type: int, short, boolean, char etc.
Composite data type: class, arrays, interface etc.
14. State two differences between a class and an object.
Ans.
Object Class
Class is a blueprint or template from which
Object is an instance of a class.
objects are created.
Object is a real world entity such as pen, laptop,
Class is a group of similar objects.
mobile, bed, keyboard, mouse, chair etc.
Object is a physical entity. Class is a logical entity.
Object is created through new keyword mainly Class is declared using class keyword e.g.
e.g. Student s1=new Student(); class Student{}
Object is created many times as per
Class is declared once.
requirement.
Class doesn’t allocated memory when it is
Object allocates memory when it is created.
created.
15. Give one point of difference between unary and binary operators.
Ans. Unary operator works on a single operand and Binary operator works on 2 operands.
16. What do you understand by type conversion?
Ans. Type conversion is the process of converting one Primitive data type to another primitive data
type. It may be done either implicitly or explicitly.
17. State the difference between a Boolean literal and a character literal.
Ans. A boolean literal consist of only two values i.e. true or false. A character literal on the other
hand is any character enclosed within single quotes.
18. Identify the literals as given below:
i. 0.5 ii. ‘A’ iii. false iv. “a”
Ans. i. double ii. char iii. boolean iv. String
9 Revision Tour I
19. Which two access specifier is used in a class declaration?
Ans. public and default
20. Why is a class called an object factory?
Ans. A class is called an object factory because objects are created from a class. An object is an
instance of a class.
21. Evaluate the value of n if the value of p=5 and q=19:
int n = (q-p)>(p-q)?(q-p):(p-q);
Ans. n=14
22. What is meant by precedence of operators?
Ans. When several operations occur in an expression, each part is evaluated and resolved in a
predetermined order called operator precedence.
23. What is Operator Associativity?
Ans. Operator associativity of an operator is a property that determines how operators of the same
precedence are grouped in the absence of parentheses; i.e. in what order each operator is
evaluated when two operators of same precedence appear in an expression.
24. State the difference between an accumulator and counter.
Ans. Accumulator is a variable that is used to add or accumulate a list of items. Counter on the other
hand is a variable, which is used to keep track of the number of times an operation is being
performed.
25. What does a class encapsulate?
Ans. A class encapsulates characteristics represented by data member and behaviour represented by
member methods.
26. State the Java concept that is implemented through:
i. A super class and a sub-class.
ii. The act of representing essential features without including background details.
Ans. i. Inheritance
ii. Abstraction
27. Write a statement in Java that will declare an object named si of the SimpleInterest class.
Ans. SimpleInterest si = new SimpleInterest();
28.Rewrite the following program after removing the errors, underlining each correction:
class My Class
{
int a, b;
void initialize( )
{
void show ( )
{
System.out.println (a+ ‘’ ‘’ + b);
}
SECTION B
Programming Questions
1. Write a program to find the sum and difference between 25 and 16 using variables in different
lines.
Ans. class q1
{
static void main()
{
int a=25,b=16,s,d;
s=a+b;
d=a-b;
System.out.println(“Sum=”+s);
System.out.println(“Difference=”+d);
}
}
2. Write a program to find the product of 5, 7 and 12 using variables.
Ans. class q2
{
static void main()
{
}
}
10. Write a program using variables to find the profit and profit percent of a certain transaction
where
S.P.= `10000 and C.P.= ` 7000.
Ans. class q10
{
static void main()
{
float sp=10000,cp=7000,p,pp;
p=sp-cp;
pp=p/cp*100;
System.out.println(“Profit=”+p);
System.out.println(“Profit Percent=”+pp);
}
}
11. Write a program to input the Principal, Rate and Time and calculate the Simple Interest.
}
}
13. Write a program to initialise two integer variables a and with 5 and 6 respectively and
interchange them. Thus after interchanging, a and b will be 6 and 5 respectively.
Ans. class q13
{
static void main()
{
int a=5,b=6,c;
System.out.println(“Before Interchange: a=”+a+“b=”+b);
c=a;
a=b;
b=c;
System.out.println(“After Interchange: a=”+a+“b=”+b);
}
}
14. Write a program to initialise three int variables a, b and c with 234, 456 and 712 and store the
sum of the last digits of the variables into d and display it.
Ans. class q14
{
static void main()
{
int a=234,b=456,c=712,d;
d=a%10+b%10+c%10;
System.out.println(“Sum=”+d);
Mental Drill
C. State whether the following statements are True (T) or False (F).
1. Scanner class is present in the java.lang package. F
2. Math.abs( ) is used to find the absolute value of a number. T
3. The return type of Math.sqrt( ) function is float. F
4. The fraction 1/2 will evaluate to 0.5. F
SECTION A
Answer the following questions.
1. Name the functions of the Scanner that is used to:
(i) Accept a number of long data type
(ii) Accept a group of alphabets.
Ans. (i) nextLong() (ii) nextLine()
2. What is a bug? What is debugging?
Ans. An error in a program is called a bug and the process of removing it is called debugging.
3. What are the different types of errors that may occur in a Java program?
Ans. Syntax Error, Logical Error and Run-time Error.
4. What are syntax errors? Give two examples.
Ans. A syntax error is an error in the syntax of a sequence of characters or tokens that is intended to
be written in a particular program.
Examples:
• Mismatched braces in classes and methods
• Wrongly accessing variable, whose visibility doesn’t exist
• Misspelled keywords and identifiers
5. What are run-time errors? Give two examples.
Ans. An error that occurs during the execution of a program is called run time error.
Example:
• Dividing an integer by zero.
• Accessing an element that is out of bounds of an array.
• Trying to store a value which is incompatible to a certain datatype.
15. Give the general syntax of a while-loop. How do you create infinite loops using a while-loop
structure?
Ans. The syntax of a while loop is,
while (condition or test-expression)
{
bodyoftheloop;
}
One of the method of creating an infinite loop is to write ‘true’ in the test-expression of the
loop.
while(true)
System.out.println(“Infinite”);
16. Give the general syntax of a do-while loop. How do you create infinite loops using do-while
loop structure?
Ans. The syntax of the dowhile loop is:
do
{
statement;
}while (condition);
Infinite loop using do-while loop:
do
{
System.out.println(“Infinite”);
}while(true);
17. Compare loops according to its usage.
Ans. Generally the for-loop is used when the number of iterations is known. The while loop is
generally used when the number of iterations is not known. The do-while loop is generally used
when it is necessary to execute the loop at least once.
Ans.
Output:
2.0
3.0
41. What is the final value of ctr after the iteration process given below, executes?
int ctr = 0;
for (int i = 1 ; i < = 5 ; i++)
for (int j = 1 ; j < = 5 ; j+=2)
++ctr;
Ans.
Final value of ctr is 15.
42. What are the final values stored in variables x and y below?
double a = - 6.35;
double b = 14.74;
double x = Math.abs(Math.ceil(a));
double y = Math.rint(Math.max(a,b));
Ans. x=6.0 and y=15.0
43. What are the values stored in variables r1 and r2:
(i) double r1 = Math.abs(Math.min(-2.83,-5.83));
(ii) double r2 = Math.sqrt(Math.floor(16.3));
Ans. r1=5.83 and r2=4.0
44. Rewrite the following program segment using if-else statements instead of the ternary
operator.
String grade=(mark>=90) ? “A” : (mark>=80) ? “B” : “C”;
Ans.
String grade;
If(marks>=90)
grade=“A”;
else
grade=“B”;
Ans. Output:
12
The loop executes 2 times.
50. Give the output of the following:
a) Math.floor (-4.7)
b) Math.ceil(3.4) + Math.pow(2, 3)
c) Math.floor(-126.349)
d) Math.max(45.6,17.3)
e) Math.min(-0.0,0.0)
f) Math.pow(4,3)
g) Math.sqrt(625)
h) Math.cbrt(125)
i) Math.max(11,11)
j) Math.ceil(-12.56)
k) Math.floor(15.36)
l) Math.round(146.5)
m) Math.max(-17, -19)
n) Math.ceil(7.8)
o) Math.ceil(4.2)
p) Math.abs(-4)
Ans.
a. Math.sqrt(a+b)
b. 1/3.0+Math.pow(a,3)+1/3.0*Math.pow(b,3)
c. s=u*t+1/2.0*a*Math.pow(t,2)
d. d=Math.sqrt(l*l+b*b);
SECTION B
Programming Questions
1. Write a program to input the area of a square and find its perimeter.
Ans. import java.util.*;
class Sol1
{
static void main()
{
Scanner sc=new Scanner(System.in);
double a,s,p;
System.out.println(“Enter the area of a square:”);
a=sc.nextDouble();
s=Math.sqrt(a);
p=4*s;
System.out.println(“Perimeter=”+p);
}
}
2. Write a program to input the length and breadth of a rectangle and find its diagonal.
5. Write a program to input 3 unique integers and print the smallest among them.
Ans. import java.util.*;
class Sol5
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println(“Enter 3 integers:”);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a<b && a<c)
System.out.println(“Smallest:”+a);
else if(b<a && b<c)
System.out.println(“Smallest:”+b);
else
System.out.println(“Smallest:”+c);
}
}
6. Write a program to input the three angles of a triangle and check whether it forms a triangle
or not, if it forms a triangle, check whether it is an equilateral, isosceles or a scalene triangle.
(Hint: To form a triangle, the sum of the angles should be 180 degrees.
To form an equilateral triangle every angle should be equal.
To form an isosceles triangle any two angles should be equal.
To form a scalene triangle all three angles should be different from each other.)
Ans. import java.util.*;
class Sol6
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println(“Enter 3 angles:”);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a+b+c==180)
b)
class Sol13
{
static void main()
{
int i;
for(i=99;i>=1;i-=2)
{
System.out.print(i+“ ”);
}
}
}
c)
class Sol13
{
static void main()
{
int i;
for(i=7;i<=70;i+=7)
{
System.out.print(i+“ ”);
}
}
}
d)
class Sol13
{
static void main()
{
int i;
for(i=80;i>=8;i-=8)
{
e)
class Sol13
{
static void main()
{
int i;
for(i=1;i<=10;i++)
{
System.out.print((i*i)+“ ”);
}
}
}
f)
class Sol13
{
static void main()
{
int i;
for(i=1;i<=10;i++)
{
System.out.print((i*i-1)+“ ”);
}
}
}
g)
import java.util.*;
class Sol13
{
static void main()
{
int i,n,s=1;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
System.out.print(s+“ ”);
h)
import java.util.*;
class Sol13
{
static void h()
{
int i,n,s=2,c=2;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
System.out.print(s+“ ”);
s=s+c;
c=c+2;
}
}
}
i)
import java.util.*;
class Sol13
{
static void main()
{
int i,n,s=1,c=1;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
System.out.print(s+“ ”);
s=s+c;
c=c+2;
}
}
}
j)
k)
import java.util.*;
class Sol13
{
static void main()
{
int i,n,f=1,s=0,t;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
t=f+2*s;
System.out.print(t+“ ”);
f=s;
s=t;
}
}
}
14. Write a program to find the sum of all 3-digit even natural numbers.
Ans.
class Sol14
{
static void main()
iii)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
}
iv)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
v)
class Sol27
{
static void main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
}
vi)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}
viii)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}
ix)
class Sol27
{
static void main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=i;j<=5;j++)
{
x)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(“*”);
}
System.out.println();
}
}
}
xi)
class Sol27
{
static void main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(“*”);
}
System.out.println();
}
}
}
xiii)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if((i+j)%2==0)
System.out.print(“1”);
else
System.out.print(“0”);
}
System.out.println();
}
}
}
xiv)
class Sol27
{
xv)
class Sol27
{
static void main()
{
int i,j,c=1;
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
if(c%2==0)
System.out.print(“0”);
else
System.out.print(“1”);
c++;
}
System.out.println();
}
}
}
xvi)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
xvii)
class Sol27
{
static void main()
{
int i,j,f,s,t;
for(i=1;i<=6;i++)
{
f=1;s=0;
for(j=1;j<=i;j++)
{
t=f+s;
System.out.print(t);
f=s;s=t;
}
System.out.println();
}
}
}
xviii)
class Sol27
{
static void main()
{
int i,j,f;
for(i=1;i<=6;i++)
{
f=0;
for(j=1;j<=2*i-1;j++)
{
if(j<=i)
++f;
xix)
class Sol27
{
static void main()
{
int i,j;
for(i=6;i>=1;i--)
{
for(j=i;j<=5;j++)
System.out.print(“ ”);
for(j=i;j>=1;j--)
System.out.print(j);
for(j=2;j<=i;j++)
System.out.print(j);
System.out.println();
}
}
}
xx)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if((i+j)%2==0)
System.out.print(“1”);
else
System.out.print(“0”);
}
System.out.println();
xxi)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
System.out.print(j);
for(j=1;j<=i-1;j++)
System.out.print(j);
System.out.println();
}
}
}
xxii)
class Sol27
{
static void main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=i;j>=1;j--)
System.out.print(j);
for(j=5;j>=i+1;j--)
System.out.print(j);
System.out.println();
}
}
}
xxiii)
class Sol27
{
static void main()
{
int i,j;
xxiv)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=6;i++)
{
for(j=1;j<=11;j++)
{
if(i+j>=7 && j-i<=5)
{
if((i+j)%2==0)
System.out.print(“ ”);
else
System.out.print(“*”);
}
else
System.out.print(“ ”);
}
System.out.println();
}
}
}
xxv)
class Sol27
{
static void main()
{
int i,j,f;
for(i=1;i<=6;i++)
{
xxvi)
class Sol27
{
static void main()
{
int i,j,f;
for(i=0;i<7;i++)
{
f=1;
for(j=0;j<=i;j++)
{
System.out.print(f+“ ”);
f=f*(i-j)/(j+1);
}
System.out.println();
}
}
}
xxvii)
class Sol27
{
static void main()
{
int i,j,f=1;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(f+“ ”);
f++;
}
Ans.
import java.util.*;
class Sol33
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,d,n,s=0,c=0;
System.out.println(“Enter a number:”);
n=sc.nextInt();
for(i=n;i>0;i/=10)
{
d=i%10;
if(d%2==1)
s=s+d*(int)Math.pow(10,c++);
}
System.out.println(“New Number:”+s);
}
Ans.
import java.util.*;
class Sol48
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,n,i,f=1;
float sum=0;
System.out.println(“Enter the value of a:”);
a=sc.nextInt();
System.out.println(“Enter the value of n:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
sum+=(float)(a+f)/(f+1);
f+=2;
Ans.
import java.util.*;
class Sol49
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a=1,n,i,p=1;
float sum=0;
System.out.println(“Enter the value of n:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
a=a+(i+1);
p=p*(i+1);
sum+=(float)a/p;
}
System.out.println(“Sum:”+sum);
}
}
50. Write a program to generate a triangle or an inverted triangle till n terms based upon the
user’s choice of triangle to be displayed.
Example 1 Example 2
Type 1 for a triangle and Type 1 for a triangle and
Type 2 for an inverted triangle 2 Type 2 for an inverted triangle 2
Input: 1 Input: 2
Enter the number of terms 5 Enter the number of terms 6
1 666666
22 55555
333 4444
4444 333
55555 22
1
Ans.
import java.util.*;
class Sol52
{
static void main()
{
}
}
54. Write a program to input a number and check whether it is a Smith number or not. Smith
number is such a number, the sum of whose digits equals the sum of the digits of its prime
factors.
Smith number is a composite number in which the sum of its digits is equal to the sum of the
digits of all its prime factors.
For Example 378 is a Smith Number as the sum of the digits of 378 are : 3+7+8 = 18. The prime
factors of 378 are: 2, 3, 3, 3, 7 ( sum = 2+3+3+3+7 = 18).
Similarly 22 is a Smith Number as the sum of the digits are : 2+2=4. The prime factors of 22 are:
2 and 11 (Sum = 2+(1+1) = 4
Other Examples include 27, 58, 85, 94, 121, 166, 202, 265, etc.
Ans.
import java.util.*;
class Sol54
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,f=2,m,t,s1=0,s2=0,d;
System.out.println(“Enter a number:”);
n=sc.nextInt();
m=n;
while(n>1)
{
if(n%f==0)
{
For option (ii) accept Monthly Instalment (P), rate of interest(r) and time period in months(n).
Calculate and output the maturity amount(A) receivable using the formula
SECTION A
A. Answer the following questions.
1. Mention any two attributes required for class declaration.
Ans. i) The keyword ‘class’
ii) The class-name
2. What is a class in Java?
Ans. A class is a mechanism to implement encapsulation. Thus class encloses characteristics
represented by data members or variables and behaviour represented by member methods or
functions into a single unit. It acts as a blueprint or template for an object.
3. Why is a class called an object factory?
Ans. A class is called an object factory because it acts as a factory for a design or abstraction which
produces objects. Each object that is generated from the class will have the same design or
abstraction as represented by its data members and member functions.
4. Define Instance Variable. Give an example of the same.
Ans. The data members declared within a class are called instance variables. For example:
class Myclass
{
int a,b;
void getval(int x, int y)
{
a=x;
Class Object
A class is a template from which objects An object is an instance of a class.
are created.
A class is a group of similar objects. Object is a real world entity such as pen,
laptop, mobile, chair etc.
A class is a logical entity. An object is a physical entity.
B. Consider the following code and answer the questions that follow:
class academic
{
int x,y;
void access()
{
int a,b;
academic student=new academic();
System.out.println(“Object Created”);
}
}
a. What is the object name of the class?
b. Name the instance variables used in the class.
c. Write the name of local variables used in the program.
d. Give the type of function being used and its name.
C. Consider the following code and answer the questions that follow:
class vxl
{
int x,y;
void init( )
{
x=5;
y=10;
}
protected void access( )
{
int a=50, b=100;
vxl vin=new vxl( );
vin.int( );
System.out.println(“Object created”);
System.out.println(“I am X=”+vin.x);
System.out.println(“I am Y=”+vin.y);
}
}
a. What is the object name of the class vxl?
b. Name the local variables of class.
c. What is the access specifier of method access( )?
d. Write the output of the above program.
Ans.
a. vin
b. a and b
c. protected
d. Output:
Object created
I am X=5
I am Y=10
void calc()
{
double pf,gp,np,hra,da;
da=25/100.0*basic;
hra=15/100.0*basic;
pf=8.33/100*basic;
np=basic+da+hra;
gp=np-pf;
System.out.println(“Gross Pay=”+gp);
}
}
2. Define a class ‘Salary’ described as below:
Data Members:
Name, Address, Phone, Subject Specialisation, Monthly Salary, Income Tax.
Member methods:
i. To accept the details of a teacher including the monthly salary.
ii. To display the details of the teacher.
iii. To compute the annual Income Tax as 5% of the annual salary above ` 1,75,000/-.
Write a main method to create object of the class and call the above member method.
class Employee
{
String pan, name;
double tax_income,tax;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter your PAN no.:”);
pan=sc.nextLine();
System.out.println(“Enter your name:”);
name=sc.nextLine();
System.out.println(“Enter taxable income:”);
void withdraw(int a)
{
if(bal-a<1000)
System.out.println(“Minimum balance should be 1000 rupees”);
else
bal-=a;
}
void datainput()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”);
name=sc.nextLine();
System.out.println(“Enter the consumer no.:”);
consumerno=sc.nextLong();
System.out.println(“Enter the unit consumed:”);
unitconsumed=sc.nextInt();
}
float compute()
{
float bill=0;
if(unitconsumed<=100)
bill=unitconsumed*1.2f;
else if(unitconsumed>100 && unitconsumed<=200)
bill=unitconsumed*2.2f;
else if(unitconsumed>200 && unitconsumed<=300)
bill=unitconsumed*3.2f;
else
bill=unitconsumed*4.0f;
return bill;
}
void Display()
{
System.out.println(“Consumer Name\t\tConsumer No\t\tUnit Consumed\t\tBill Amount”);
System.out.println(name+“\t\t”+consumerno+“\t\t”+unitconsumed+“\t\t”+compute());
}
}
void feedinfo()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the flight no:”);
fl_no=sc.nextInt();
System.out.println(“Enter the destination:”);
dest=sc.nextLine();
System.out.println(“Enter the distance:”);
dist=sc.nextFloat();
calfuel();
}
void showinfo()
{
System.out.println(“Flight no:”+fl_no);
System.out.println(“Destination:”+dest);
System.out.println(“Distance:”+dist);
System.out.println(“Fuel:”+fuel);
}
public static void main(String args[])
{
Flight ob=new Flight();
ob.feedinfo();
ob.showinfo();
}
}
14. Define a class hotel in with the following description
Instance variables/data members:
Rno : Room No of int type
Name : Customer name of String type
Tarrif : stores per day charges of float type
NOD : no of days integer
void Checkin()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the Room no:”);
Rno=sc.nextInt();
System.out.println(“Enter the Name:”);
Name=sc.nextLine();
System.out.println(“Enter the Tarrif:”);
Tarrif=sc.nextFloat();
System.out.println(“Enter the No. of Days:”);
NOD=sc.nextInt();
}
void Checkout()
{
System.out.println(“Room no:”+Rno);
System.out.println(“Name:”+Name);
System.out.println(“Tarrif:”+Tarrif);
System.out.println(“No. of days:”+NOD);
System.out.println(“Amount:”+CALC());
}
public static void main(String args[])
{
void display()
{
System.out.println(“Name\t\tCalls Made\t\tAmount\t\tTotal Amount”);
System.out.println(name+“\t\t”+call+“\t\t”+amt+“\t\t”+total);
}
public static void main(String args[])
{
Telephone ob=new Telephone();
ob.input();
ob.cal();
ob.display();
}
}
16. Define a class named movieMagic with the following description:
Instance variables/data members:
int year – to store the year of release of a movie
String title – to store the title of the movie.
float rating – to store the popularity rating of the movie.
(minimum rating = 0.0 and maximum rating = 5.0)
Member Methods:
(i) void accept() - To input and store year, title and rating.
(ii) void display() - To display the title of a movie and a message based on the rating as
per the table below.
if(units>300)
bill=rate+2.5/100*rate;
else
bill=rate;
}
void print()
{
System.out.println(“Name of the customer:”+n);
System.out.println(“Number of units consumed:”+units);
System.out.println(“Bill amount:”+bill);
}
public static void main(String args[])
{
ElectricBill ob=new ElectricBill();
ob.accept();
ob.calculate();
ob.print();
}
}
• void display() - To display all details of a customer such as name, coach, total amount
and mobile number.
Write a main method to create an object of the class and call the above member methods.
Ans.
import java.util.*;
class RailwayTicket
{
String name, coach;
long mobno;
int amt,totalamt;
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”);
name=sc.nextLine();
System.out.println(“Enter the type of coach:”);
coach=sc.nextLine();
System.out.println(“Enter the mobile number:”);
mobno=sc.nextLong();
System.out.println(“Enter the amount:”);
amt=sc.nextInt();
}
void update()
{
double rate=0;
if(coach.equals(“First_AC”))
totalamt=amt+700;
else if(coach.equals(“Second_AC”))
totalamt=amt+500;
}
void print()
{
System.out.println(“Name of the customer:”+name);
System.out.println(“Type of coach:”+coach);
System.out.println(“Total amount:”+totalamt);
System.out.println(“Mobile Number:”+mobno);
}
public static void main(String args[])
{
RailwayTicket ob=new RailwayTicket();
ob.accept();
ob.update();
ob.print();
}
}
Mental Drill
SECTION A
A. Answer the following questions.
1. What is a method?
Ans. A Java method is a collection of statements that are grouped together to perform an operation.
C. Answer as directed:
1. In the program given below:
class MyClass
{
static int x = 7;
int y = 2;
public static void main(String args[ ])
{
MyClass obj = new MyClass();
System.out.println(x);
obj.sampleMethod(5);
int a= 6;
System.out.println(a);
}
void sampleMethod(int n)
{
System.out.println(n);
System.out.println(y);
}
}
State the name and value of the:
(i) method argument or argument variable.
(ii) class variable.
(iii) local variable.
(iv) instance variable.
Ans.
(i) main() =String args[] value=none
sampleMethod=int n value=5
(ii) x value=7
(iii) a value=6
(iv) y value=2
7. Create a function which accepts an integer as parameter and return the largest digit. Create
another function to input 10 integers and find the sum of the largest digit of each number.
Ans.
import java.util.*;
class Sol7
{
static int largest(int n)
{
int i,max=0,d;
for(i=n;i>0;i=i/10)
{
d=i%10;
if(d>max)
max=d;
}
return max;
}
(ii) double series(double x,double n) with two double arguments and returns the sum of the
series
x2 x3 x4 xn
S= x+ + + + ...
2! 3! 4! n!
Ans.
class Sol35
{
static double series(double n)
Mental Drill
173Constructors
c. It can print the content of instance variables.
d. It begins with the static keyword.
Ans. c. It can print the content of instance variables.
SECTION A
1. What is a constructor? Why is it needed in a program?
Ans. A constructor in Java is a block of code similar to a method that is called when an instance of an
object is created. A constructor is needed to initialise data members with legal initial values.
2. State the characteristics of a constructor.
Ans. The characteristics of a constructor are:
a. It has the same name as the class-name.
b. It does not have any return type.
c. It follows the usual rules of accessibility as other members of a class and therefore access
modifiers can be applied to it.
d. It gets called automatically, whenever an object is created.
3. How are constructors invoked?
Ans. Constructor function gets called (invoked) automatically whenever an object is created.
4. Why do we need a constructor as a class member?
Ans. A constructor is a special member method which will be called by the JVM implicitly for placing
user/programmer defined values instead of placing default values. Constructors are meant for
initializing the object.
5. State the difference between function and constructor.
Ans. Following are the difference between constructor and method.
a. Constructor is used to initialize an object whereas method is used to exhibits functionality
of an object.
b. Constructors are invoked implicitly whereas methods are invoked explicitly.
c. Constructor does not return any value where the method may/may not return a value.
d. In case constructor is not present, a default constructor is provided by java compiler. In the
case of a method, no default method is provided.
e. Constructor should be of the same name as that of class. Method name should not be of
the same name as that of class.
6. How are private constructors called?
Ans. Private constructors allows an object to be created only within the methods of the class where
it is private.
7. What are the different types of constructors available in Java?
Ans. Parameterised constructor and Non-parameterised constructor.
175Constructors
{
public Perimeter() // I
{
System.out.println(“From default”);
}
public Perimeter(int x) // II
{
System.out.println(“Circle perimeter: “ + 2*Math.PI*x);
}
public Perimeter(int x, int y) // III
{
System.out.println(“Rectangle perimeter: “ +2*(x+y));
}
public static void main(String args[])
{
Perimeter p1 = new Perimeter(); // I
Perimeter p2 = new Perimeter(10); // II
Perimeter p3 = new Perimeter(10, 20); // III
}
}
12. What is a destructor? Is destructor function necessary in Java? If no, explain why?
Ans. A destructor is a special method called automatically during the destruction of an object. In java
a destructor is not necessary because Java is a garbage collected language you cannot predict
when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.
13. What is the implicit return type of a constructor function?
Ans. The implicit return type is the class itself.
14. Enter any two variables through constructor with parameters and write a program to swap
and print the values.
Ans. class Swap
{
int a,b;
Swap(int x,int y)
{
a=x;
b=y;
}
void interchange()
{
int t=a;
a=b;
b=t;
}
}
B. Consider the following code and answer the questions that follow:
class Myclass
{
int a,b;
void Myclass(int x, int y)
{
a=x;
b=y;
}
int Myclass(int x)
{
a=b=x;
}
void show( )
{
System.out.println(a+ “ “+y);
}
public static void main(String args[])
{
Myclass ob1=new Myclass();
Myclass ob2=new Myclass(12.3,14.6,15);
Myclass ob3=new Myclass(7);
ob1.ob2.ob3.show();
}
}
177Constructors
System.out.println(a+ “ ”+b);
}
public static void main(String args[])
{
Myclass ob2=new Myclass(12,15);
Myclass ob3=new Myclass(7);
ob2.show();
ob3.show();
}
}
C. Consider the following code and answer the questions that follow:
class academic
{
int x,y;
void access()
{
int a,b;
academic student=new academic();
System.out.println(Object Created”);
}
}
a. What is the object name of the class?
b. Name the instance variables used in the class.
c. Write the name of local variables used in the program.
d. Give the type of function being used and its name.
Ans.
a. student
b. x and y
c. a and b
d. procedural function Name: access
D. State the output of the following program segment:
class Today
{
static int a;
char b;
void input()
{
a=20;
b=’Z’;
}
void convert()
{
char c=(char)(a+b);
179Constructors
Ans.
i. main() method: String args[]
sampleMethod() method: int n
ii. x
iii. a
iv. y
SECTION B
Write programs for the following:
1. Define a class called Box, having members as:
Data Members: length, breadth and height of int type.
Member Functions:
i. Constructor to initialise the data members.
ii. To compute and display the volume.
Ans.
class Box
{
int length,breadth,height;
Box(int l,int b,int h)
{
length=l;
breadth=b;
height=h;
}
void compute()
{
int vol;
vol=length*breadth*height;
System.out.println(“Volume:”+vol);
}
}
181Constructors
}
void compute()
{
int area;
area=length*breadth;
System.out.println(“Area:”+area);
}
public static void main(String args[])
{
FourSide ob1=new FourSide(12);
FourSide ob2=new FourSide(17,6);
ob1.compute();
ob2.compute();
}
}
4. The sum of n natural numbers is defined by the following formula:
n * (n + 1)
1
Create a class named Natural, which will contain the following members:
Data members: n and s of int data type.
Member functions:
i. Parametrised constructor to initialise n.
ii. void compute( ) to calculate the sum of first n natural numbers using the above formula
and store it in s.
iii. void display( ) to show the sum.
Ans.
class Natural
{
int n,s;
Natural(int t)
{
n=t;
}
void compute()
{
int i;
s=0;
for(i=1;i<=n;i++)
s+=i;
}
void display()
{
183Constructors
area=new Conversion().multiply(length,breadth);
System.out.println(“Area:”+area);
}
}
6. A class Palin has been defined to check whether a positive number is a Palindrome number or
not.
The number ‘N’ is palindrome if the original number and its reverse are same. Some of the
members of the class are given below:
Classname :
Palin Data members/instance variables:
• num : integer to store the number
• revnum : integer to store the reverse of the number
Methods/Member functions:
• Palin( ) : constructor to initialize data members with legal initial values.
• void accept( ) : to accept the number.
• int reverse(int y) : reverses the parameterized argument ‘y’ and stores it in ‘revnum’.
• void check( ) : checks whether the number is a Palindrome by invoking the function
reverse( ) and display the result with an appropriate message.
Specify the class Palin giving the details of the constructor( ), void accept( ),int reverse(int) and
void check( ). Define the main( ) function to create an object and call the functions accordingly
to enable the task.
Ans.
import java.util.*;
class Palin
{
int num,revnum;
Palin()
{
num=0;
revnum=0;
}
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a number:”);
num=sc.nextInt();
}
int reverse(int y)
{
for(int i=num;i>0;i/=10)
{
int d=i%10;
185Constructors
}
9. You are to print the telephone bill of a subscriber. Create a class having the following data
members:
Phone Number of long data type (for storing the phone number).
Name of String type (for storing the name of a the subscriber).
Hire Charge a symbolic constant of int type (to store monthly hire charge say `. 200).
Units Consumed of int type (to store the monthly units consumed by the subscriber).
Bill Amount of float type (to store the bill amount that is payable).
Create member functions for the following:
i. Constructor to initialise all data members except Hire Charge and Bill Amount.
ii. C
alculate the bill amount payable which is Hire Charge+(`. 1 per unit for the first 100 units,
`. 1.50 per unit for the next 100 units and `. 2.00 per unit there after.
iii. To display the Bill for the subscriber.
Ans.
import java.util.*;
class Telephone
{
long pno;
String name;
int hire;
int units;
float bill;
Telephone(long p,String n,int u)
{
pno=p;
name=n;
units=u;
}
void calculate()
{
hire=200;
bill=0;
if(units<=100)
187Constructors
bill=hire+units*1;
else if(units>100 && units<=200)
bill=hire+100*1+(units-100)*1.50f;
else
bill=hire+100*1+100*1.50f+(units-200)*2;
}
void show()
{
System.out.println(“BILL”);
System.out.println(“Phone No.:”+pno);
System.out.println(“Name:”+name);
System.out.println(“Hire Charge:”+hire);
System.out.println(“Units consumed:”+units);
System.out.println(“Bill:”+bill);
}
}
10. Define a class Taximeter having the following description:
Data members/instance variables:
int taxino - to store taxi number
String name - to store passenger’s name
int km - to store number of kilometers travelled
Member functions:
Taximeter() - constructor to initialise taxino to 0, name to “” and km to 0.
input() - to store taxino,name,km
calculate() - to calculate bill for a customer according to given conditions
Kilometers travelled(km) Rate/km
1 km ` 25
1 < km ≤ 6 ` 10
6 < km ≤ 12 ` 15
12 < km ≤ 18 ` 20
>18 km ` 25
display()- To display the details in the following format
Taxino Name Kilometres travelled Bill amount
Ans.
import java.util.*;
class Taximeter
{
int taxino;
String name;
int km;
Taximeter()
{
taxino=0;
189Constructors
Ans.
import java.util.*;
class Numbers
{
int a,b;
Numbers(int x,int y)
{
a=x;
b=y;
}
int sum()
{
return a+b;
}
void display()
{
System.out.println(“a=”+a+“b=”+b);
}
static void compare(Numbers ob1,Numbers ob2)
{
if(ob1.sum()>ob2.sum())
ob1.display();
else
ob2.display();
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x,y;
System.out.println(“Enter 2 numbers:”);
x=sc.nextInt();
y=sc.nextInt();
Numbers ob1=new Numbers(x,y);
System.out.println(“Enter 2 numbers:”);
x=sc.nextInt();
y=sc.nextInt();
Numbers ob2=new Numbers(x,y);
compare(ob1,ob2);
}
}
12. Define a class called FruitJuice with the following description:
Instance variables/data members:
int product_code - stores the product code number
String flavour - stores the flavour of the juice.(orange, apple, etc.)
191Constructors
System.out.println(“Flavour:”+flavour);
System.out.println(“Pack type:”+pack_type);
System.out.println(“Pack size:”+pack_size);
System.out.println(“Product price:”+product_price);
}
public static void main(String args[])
{
FruitJuice ob=new FruitJuice();
ob.input();
ob.discount();
ob.display();
}
}
13. Create a class SalaryCalculation that is described as below:
Class Name : SalaryCalculation
Data members : name (String type data)
basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary AnnualSal (All double type data)
Member methods :
i. SalaryCalculation( ) - A constructor to assign name of employee (name), basic
salary (basicPay) of your choice and conveyance allowance
(conveyanceAlw) As ` 1000.00
ii. void SalaryCal( ) - to calculate other allowances and salaries as given:
specialAlw = 25% of basic salary.
gross = basicPay + specialAlw + conveyanceAlw.
netSalary = gross - pf.
AnnualSal = 12 months netSalary.
iii. void display( ) - to print the name and other calculations with suitable headings.
Write a program in Java to calculate all the details mentioned above and print them all.
Ans.
import java.util.*;
class SalaryCalculation
{
String name;
double basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary, AnnualSal;
SalaryCalculation()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”);
name=sc.nextLine();
System.out.println(“Enter the basic pay:”);
basicPay=sc.nextDouble();
conveyanceAlw=1000.00;
}
void SalaryCal()
193Constructors
double pamt, rate;
int time;
Compound()
{
pamt=rate=0.0;
time=0;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the principal:”);
pamt=sc.nextDouble();
System.out.println(“Enter the rate:”);
rate=sc.nextDouble();
System.out.println(“Enter the time:”);
time=sc.nextInt();
}
double findInterest()
{
double ci;
ci=pamt*Math.pow(1+rate/100.0,time)-pamt;
return ci;
}
void printData()
{
System.out.println(“Principal:”+pamt);
System.out.println(“Rate:”+rate);
System.out.println(“Time:”+time);
}
public static void main(String args[])
{
Compound ob=new Compound();
ob.input();
ob.printData();
System.out.println(“Compound Interest:”+ob.findInterest());
}
}
15. Define a class PhoneBill with the following descriptions.
Data members:
customerName of type character array
phoneNumber of type long
no_of_units of type int
rent of type int
amount of type float.
195Constructors
System.out.println(“Enter the phone number:”);
phoneNumber=sc.nextLong();
System.out.println(“Enter the no. of units:”);
no_of_units=sc.nextInt();
System.out.println(“Enter the rent:”);
rent=sc.nextInt();
}
void Display()
{
System.out.println(“Customer name:”+customerName);
System.out.println(“Phone number:”+phoneNumber);
System.out.println(“No. of units:”+no_of_units);
System.out.println(“Rent:”+rent);
System.out.println(“Amount:”+amount);
}
public static void main(String args[])
{
PhoneBill ob=new PhoneBill();
ob.accept();
ob.calculate();
ob.Display();
}
}
16. Define a class Sports with the following descriptions:
Data members:
s_code of type long
s_name of type (String)
fees of type integer
duration of type integer
Member Functions:
i Constructor to assign initial values of s_code as 1001, s_name as “Cricket”, fees as 500,
duration as 70.
ii. A function newSports() which allows user to enter s_code, s_name and duration. Also
assign the values to fees as per the following conditions:
s_name Fees
Table Tennis 2000
Swimming 4000
Football 3000
iii. A function displaySports() to display all the details.
Ans.
import java.util.*;
class Sports
{
197Constructors
Ans.
import java.util.*;
class GeneratePrime
{
int n;
GeneratePrime(int a)
{
n=a;
}
boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
void display()
{
int i=0,p=2;
while(i<n)
{
if(isPrime(p)==true)
{
System.out.println(p);
i++;
}
p++;
}
}
}
18. Create a class called PrimeDigits to find the sum of the prime digits in an integer. The class
should have the following members.
Data Members:
n of int data type.
Member Functions:
i. Parameterised constructor to initialise the value of n.
void sumOfPrimeDigits(int n)
{
int i=n,d,s=0;
while(i>0)
{
d=i%10;
if(isPrime(d)==true)
s=s+d;
i/=10;
}
System.out.println(“Sum of prime digits:”+s);
}
}
19. Create a class called Series which will contain the following members:
Data Members:
x of double type
n of int type
199Constructors
Member Functions:
i. Parameterised constructor to initialise the data members.
ii. To calculate and print the sum of the following series:
x+x/2!+x/3!+x/4!+...+x/n!
To calculate and print the sum of the following series:
x/2!+x2/3!+x3/4!+x4/5!+…+xn/(n+1)!
To calculate and print the sum of the following series:
x/2! - x2/3!+x3/4! - x4/5!+…±xn/(n+1)!
where the symbol ! stands for factorial eg. 5!=5*4*3*2*1, 3!=3*2*1
Ans.
import java.util.*;
class Series
{
double x;
int n;
Series(double x,int n)
{
this.x=x;
this.n=n;
}
void sumSeries1()
{
double s=0;
long i,p,j;
for(i=1;i<=n;i++)
{
p=1;
for(j=1;j<=i;j++)
{
p=p*j;
}
s=s+x/p;
}
System.out.println(“Sum=”+s);
}
void sumSeries2()
{
double s=0;
long i,p,j;
for(i=1;i<=n;i++)
201Constructors
Rounding()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a real number in n:”);
n=sc.nextDouble();
}
void roundOff()
{
r=Math.round(n*100)/100.0;
}
void display()
{
System.out.println(“n=”+n+“r=”+r);
}
}
Mental Drill
SECTION A
A. Answer the following questions.
1. What is composite data type?
Ans. In computer science, a composite data type or compound data type is any data type which can
be constructed in a program using the programming language’s primitive data types and other
composite types.
2. State the difference between primitive and composite data type.
Ans.
Primitive data type Composite data type
Primitives are the fundamental data types Composite data types are user defined types
that are represented by keywords namely and may have any name defined by the user.
byte, short, int, long, char and boolean.
Variables of primitive data type stores values Variables of composite data type stores
of corresponding data type. reference to an object.
It can store only one type of value. It can store data of multiple data type.
6. Show with an example, how wrapper class object can be created and initialised?
Ans. Example:
Byte b=new Byte(byte) 10):
7. Explain autoboxing and unboxing in java.
Ans. Converting a primitive value into an object of the corresponding wrapper class is called
autoboxing. Converting an object of a wrapper type to its corresponding primitive value is
called unboxing.
Mental Drill
221 Encapsulation
7. Which among the following best describes encapsulation?
a. It is a way of combining various data members into a single unit
b. It is a way of combining various member functions into a single unit
c. It is a way of combining various data members and member functions into a single unit which
can operate on any data
d. It is a way of combining various data members and member functions that operate on those
data members into a single unit
Ans. d. It is a way of combining various data members and member functions that operate on
those data members into a single unit
8. If data members are private, what can we do to access them from the class object?
a. Create public member functions to access those data members
b. Create private member functions to access those data members
c. Create protected member functions to access those data members
d. Private data members can never be accessed from outside the class
Ans. a. Create public member functions to access those data members
9. Which feature can be implemented using encapsulation?
a. Inheritance b. Abstraction
c. Polymorphism d. Overloading
Ans. b. Abstraction
10. How can Encapsulation be achieved?
a. Using Access Specifiers b. Using only private members
c. Using inheritance d. Using Abstraction
Ans. a. Using Access Specifiers
Section A
Answer the following questions.
1. What is encapsulation?
Ans. Wrapping up of data and methods into a single unit is called encapsulation.
2. What are access specifiers used for? Name the access specifiers used in Java.
Ans. Access modifiers (or access specifiers) are keywords in object-oriented languages that set the
accessibility of classes, methods, and other members. Access modifiers are a specific part of
programming language syntax used to facilitate the encapsulation of components.
Access specifiers used in Java are:
223 Encapsulation
}
}
public class MainClass
{
public static void main(String args[ ])
{
/*Access obj=new Access(5,6);Error constructor has private
access specifier.*/
Access.createObject();
Access obj=new Access(7); /*Correct as the default access
version of the constructor is being called.*/
}
}
6. What is Inheritance? Which keyword is used to implement inheritance?
Ans. Inheritance is a mechanism wherein a new class is derived from an existing class. The ‘extends’
keyword is used to implement inheritance.
7. What is a package? What is its significance?
Ans. A package is a namespace that organises a set of related pre-compiled classes and interfaces
into folders.
Packages are used for:
• Preventing naming conflicts.
• Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
• Providing controlled access: protected and default have package level access control.
• Packages can be considered as data encapsulation (or data-hiding).
8. How are packages created in BlueJ?
Ans. To create a package:
Step 1: Select the Edit menu and select the New Package… option.
Step 2: E nter the name of the package in the ‘Create New Package’ dialog and hit the ‘OK’
button.
9. What do you understand by “Scope of a Variable”?
Ans. The scope of a variable is defined as the extent of the program code within which the variable
can be accessed or declared or worked with.
10. What is the scope of argument variables?
Ans. Argument variables have their scope limited only within the method or constructor block where
it is declared.
225 Encapsulation
2. Define a class Candidate with the following descriptions:
Private Members:
• A data member RNo(Registration Number) of type long
• A data member Name of type String
• A data member Score of type float
• A data member Remarks of type String
• A member function AssignRem() to assign the remarks as per the score obtained by a
candidate. Score range and the respective remarks are shown as follows:
Score Remarks
>=50 Selected
Less than 50 Not Selected
Public Members:
• A function ENTER() to allow user to enter values for Rno, Name, Score and call function
AssignRem() to assign grade.
• A function DISPLAY() to allow user to view the content of all data members.
Also create a main() method to create an object and show its implementation by calling the
above methods.
Ans.
import java.util.*;
class Candidate
{
private long Rno;
private String Name;
private float Score;
private String Remarks;
private void AssignRem()
{
if(Score>=50)
Remarks=“Selected”;
else
Remarks=“Not Selected”;
}
public void ENTER()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the reg. no.:”);
Rno=sc.nextLong();
System.out.println(“Enter the name:”);
Name=sc.nextLine();
System.out.println(“Enter the score:”);
Score=sc.nextFloat();
AssignRem();
}
Public Members:
• A function GetFood() to allow user to enter values for FoodCode, Food, FType and call
function GetSticker() to assign Sticker.
• A function ShowFood() to allow user to view the content of all the data members.
Also create a main() method to create an object and show its implementation by calling the
above methods.
Ans.
import java.util.*;
class RESTRA
{
private int FoodCode;
private String Food,FType,Sticker;
private void GetSticker()
{
227 Encapsulation
if(FType.equalsIgnoreCase(“Sticker”))
Sticker=“GREEN”;
else if(FType.equalsIgnoreCase(“Contains Egg”))
Sticker=“YELLOW”;
else if(FType.equalsIgnoreCase(“Non-Vegetarian”))
Sticker=“YELLOW”;
}
public void GetFood()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the FoodCode:”);
FoodCode=sc.nextInt();
System.out.println(“Enter the Food:”);
Food=sc.nextLine();
System.out.println(“Enter the Food Type:”);
FType=sc.nextLine();
GetSticker();
}
public void ShowFood()
{
System.out.println(“FoodCode:”+FoodCode);
System.out.println(“Food:”+Food);
System.out.println(“Food Type:”+FType);
System.out.println(“Sticker:”+Sticker);
}
229 Encapsulation
ob.Register();
ob.ViewSeminar();
}
}
5. Define a class Graments with the following description:
Private members:
• GCode of type String
• GType of type String
• GSize of type integer
• GFabric of type String
• GPrice of type String
• A function Assign() which calculates and assigns the value of GPrice as follows:
For the GFabric as “COTTON”
GType GPrice
TROUSER 1300
SHIRT 1100
For GFabric other than “COTTON” the above mentioned GPrice gets reduced by 10%.
Public Members:
• A constructor to assign initial values of GCode, GType and GFabric with the words “NOT
ALLOTED” and GSize and GPrice with 0.
• A function input() to input the values of the data members of GCode, GType, GFabric, GSize
and invoke the Assign function.
• A function Display() which displays the content of all the data members for a Garment.
Also create a main() method to create an object and show its implementation by calling the
above methods.
Ans.
import java.util.*;
class Garments
{
private String GCode,GType,GFabric;
private int GSize;
private float GPrice;
private void Assign()
{
if(GType.equalsIgnoreCase(“TROUSER”))
GPrice=1300;
else if(GType.equalsIgnoreCase(“SHIRT”))
GPrice=1100;
if(!(GFabric.equalsIgnoreCase(“COTTON”)))
GPrice=GPrice-10/100f*GPrice;
}
public Garments()
231 Encapsulation
Type Fare
‘O’ 15*Distance
‘E’ 20*Distance
‘L’ 24*Distance
Public Members:
• A constructor function to initialise Type as ‘O’ and Fare as 500.
• A function Allocate() to allow user to enter values for BusNo, From, To, Type and Distance.
Also this function should call CalcFare() to calculate Fare.
• A function Show() to display the content of all the data members on the screen.
Also create a main() method to create an object and show its implementation by calling the
above methods.
Ans.
import java.util.*;
class Bus
{
private String From,To;
private char Type;
private int BusNo;
private float Distance,Fare;
private void CalcFare()
{
if(Type==’O’)
Fare=15*Distance;
else if(Type==’E’)
Fare=20*Distance;
else if(Type==’L’)
Fare=24*Distance;
}
public Bus()
{
Type=’O’;
Fare=500;
}
public void Allocate()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the bus no.:”);
BusNo=sc.nextInt();
System.out.println(“Enter the origin:”);
From=sc.nextLine();
System.out.println(“Enter the destination:”);
To=sc.nextLine();
System.out.println(“Enter the Type of bus:”);
233 Encapsulation
Ans.
import java.util.*;
class CABS
{
private char Type;
private int CNo;
private float PKM,Dist;
public CABS()
{
Type=’A’;
CNo=1111;
}
private void Charges()
{
if(Type==’A’)
PKM=25;
else if(Type==’B’)
PKM=20;
else if(Type==’L’)
PKM=15;
}
235 Encapsulation
}
}
(ii)
import Number.Armstrong;
import java.util.Scanner;
class Check
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println(“Enter a number:”);
n=sc.nextInt();
Armstrong ob=new Armstrong(n);
if (ob.isArmstrong())
System.out.println(“Armstrong No.”);
else
System.out.println(“Not an Armstrong No.”);
}
}
237 Encapsulation
10. Define a class Salary described as below that calculates the tax depending upon the salary of
a teacher:
private data Members : Name, Address, Phone, Subject Specialization, Monthly Salary, Income
Tax.
public Member methods :
(i) To accept the details of a teacher including the monthly salary.
(ii) To display the details of the teacher.
(iii) To compute the annual Income Tax as 5% of the annual salary above ` 1,75,000/-.
Also create a main() function and create 2 objects to calculate tax for 2 teachers.
Ans.
import java.util.*;
class Salary
{
String Name, Address,subSpe;
double mSal,it;
long phone;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter your name:”);
Name=sc.nextLine();
System.out.println(“Enter your address:”);
Address=sc.nextLine();
System.out.println(“Enter Subject Specialization:”);
subSpe=sc.nextLine();
System.out.println(“Enter Phone No.:”);
phone=sc.nextLong();
System.out.println(“Enter monthly salary:”);
mSal=sc.nextDouble();
}
void display()
{
System.out.println(“Name:”+Name);
System.out.println(“Address:”+Address);
System.out.println(“Subject Specialization:”+subSpe);
System.out.println(“Phone No.:”+ phone);
System.out.println(“Monthly salary:”+mSal);
}
void calc()
{
double aSal;
aSal=12*mSal;
if(aSal>175000)
it=5/100.0*(aSal-175000);
239 Encapsulation
return f;
}
static void isSpecial()
{
int i,d,s=0;
for(i=n;i>0;i/=10)
{
d=i%10;
s+=factorial(d);
}
if(s==n)
System.out.println(“Special Number”);
else
System.out.println(“Not a Special Number”);
}
}
241Arrays
<array-name>.length
The length is the property of an array that provides the number of elements in an array.
7. With the help of an example show how arrays are passed to a function as Call by Reference.
Ans. The following illustrates how are arrays passed as call by reference:
class ArrayDemo
{
//Method to double the value of each element in the array.
static void doubleIt(int a[])
{
for(int i=0; i<a.length; i++)
{
a[i]=2*a[i];
}
}
public static void main (String args[])
{
int a []={4,5,12,7,8,3};
System.out.println(“Original Array...”);
for (inti=0;i<a. length;i++)
System.out.print(a[i]+“/t”);
doubleIt(a); // this is how you pass an array as
//parameter.
System.out.println (“InUpdated Array...”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+“\t”);
}
}
Output when main( ) is executed will be,
Original Array....
4 5 12 7 8 3
Updated Array...
8 10 24 14 16 6
8. Explain:
i. Linear Search
ii. Binary Search
Ans.
i. Linear search or sequential search is a method for finding a particular value in a list, that
consists of checking everyone of its elements, one at a time and in sequence, until the
desired one is found.
ii. Binary search in Java using divide and conquer technique. A binary search or half-interval
search algorithm finds the position of a specified value(the input“key”) within a sorted
array.
243Arrays
B. Answer as directed:
1. What is the difference between these two statements:
i. int sum[]=new int[10] ii. sum[1]=10;
Ans. The first statement declares an integer array of size 10 having the name ‘sum’. The second
statement initialises the second element of the array ‘sum’ with 10.
2. Write the correct form of the following arrays:
i. A1(2) ii. Name[2,5]
iii. Roll[2;] iv. Matrix(5)(5)
Ans. i. A1[2]
ii. Name[2][5]
iii. Roll[2]
iv. Matrix[5][5]
3. Write the value of individual array element.
i. int c[]={78,23,45,12,16};
ii. int p[][]={{1,1},{3,3},{5,5},{7,7}};
Ans.
i. c[0]=78, c[1]=23, c[2]=45, c[3]=12, c[4]=16
ii. p[0][0]=1, p[0][1]=1, p[1][0]=3, p[1][1]=3, p[2][0]=5, p[2][1]=5, p[3][0]=7, p[3][1]=7
4. Give the proper array declaration for the following:
i. Declare an integer array, which can hold 25 values.
ii. Declare a two dimensional array called mat 3×4 of integer.
iii. Declare and initialise a two dimensional array of size 5×5 to 0.
Ans. i. int a[]=new int[25];
ii. int mat[][]=new int[3][4];
iii. int a[][]={{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}};
5. What will be the output of the following program:
class Output
{
public static void main(String args[])
{
int a[]={6,5,4,3,2,1};
int x;
for(x=5;x>=0;x--)
{
System.out.println(a[x]);
}
}
}
Ans.
Output:
245Arrays
Ans. Output:
kolkata
gangtok
banglore
Kolkata
Gangtok
Banglore
8. What will be the output of the following program:
class Output
{
public static void main(String args[])
{
int a,b=0;
int c[]={1,2,3,4,5,6,7,8,9,10};
for(a=0;a<10;a++)
{
if(a%2==0)
b+=c[a];
}
System.out.print(b);
}
}
In what statement, state what the above program is doing?
Ans. Output:
25
9. Find the syntax error(s), if any in the following program.
Class First
{
public static void main(String args[])
{
int sum[2,4];
for(i=0;i<2;i++)
{
for(j=0;j<=3;j++)
{
System.print(sum);
}
}
}
}
247Arrays
SECTION B
1. Write a program to input 10 numbers into an integer array and find the sum of all numbers in
it.
Ans.
import java.util.*;
class Sol1
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,s=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
s+=a[i];
System.out.println(“Sum=”+s);
}
}
2. Write a program to input 10 numbers into an integer array and find the sum of even and odd
numbers separately.
Ans.
import java.util.*;
class Sol2
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,se=0,so=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
se+=a[i];
else
so+=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]%2==0)
s+=a[i];
}
av=(float)s/10;
System.out.println(“Numbers less than average:”);
for(i=0;i<10;i++)
{
if(a[i]<av)
System.out.print(a[i]+“ ”);
}
}
}
4. Write a program to input 10 numbers into an integer array and find the sum of prime numbers
only.
Ans.
import java.util.*;
class Sol4
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,s=0,j,c;
249Arrays
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
s+=a[i];
}
if(s>0)
System.out.println(“Sum of prime numbers:”+s);
else
System.out.println(“No prime numbers found”);
}
}
5. Write a program to input 10 numbers into an integer array and check whether all numbers are
3-digit numbers or not.
Ans. import java.util.*;
class Sol5
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i;
boolean f=true;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(!(a[i]>=100 && a[i]<=999))
f=false;
}
if(f)
System.out.println(“All are 3 digit numbers”);
6. Write a program to input 10 numbers into an integer array and check whether all numbers in
it are same or not.
Ans.
import java.util.*;
class Sol6
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i;
boolean f=true;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]!=a[0])
f=false;
}
if(f)
System.out.println(“All are same”);
else
System.out.println(“All are not same”);
}
}
7. Write a program to input 10 numbers into an integer array and check whether they are in
ascending order or not.
Ans.
import java.util.*;
class Sol7
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i;
boolean f=true;
251Arrays
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<9;i++)
{
if(a[i]>a[i+1])
f=false;
}
if(f)
System.out.println(“All are in ascending order”);
else
System.out.println(“All are not in ascending order”);
}
}
8. Write a program to input 10 numbers into an integer array and find the position of the largest
and the smallest number.
Ans.
import java.util.*;
class Sol8
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,l=0,s=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
l=s=a[0];
for(i=1;i<10;i++)
{
if(a[i]>l)
l=a[i];
if(a[i]<s)
s=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]==l)
System.out.println(“Position of largest number:”+i);
9. Write a program to input 10 numbers into an integer array and interchange the largest number
with the smallest number within the array and print the modified array. Assume that there is
only one largest and smallest number.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 67 34 15 16 89 15
After interchange it should have the elements arranged as:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 89 7 67 34 15 16 3 15
Ans.
import java.util.*;
class Sol9
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,l=0,s=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
l=s=a[0];
for(i=1;i<10;i++)
{
if(a[i]>l)
l=a[i];
if(a[i]<s)
s=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]==l)
a[i]=s;
else if(a[i]==s)
a[i]=l;
}
253Arrays
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
10. Write a program to input 10 numbers into an integer array and replace all prime numbers in it
(if any) by 0 and print the modified array.
For example, if the array contains the following elements:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 67 34 15 16 89 13
After replacing the prime numbers with 0 the modified array should have the elements as:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 0 0 67 34 15 16 89 0
Ans.
import java.util.*;
class Sol10
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,c;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
a[i]=0;
}
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
for(i=0;i<10;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
{
if(s==0)
s=a[i];
if(a[i]<s)
s=a[i];
}
}
if(s>0)
System.out.println(“Smallest prime number:”+s);
else
System.out.println(“No prime number found”);
}
}
255Arrays
12. Write a program to input 10 numbers into an integer array and print the position of the second
largest number in it.
import java.util.*;
class Sol12
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,l=0,sl=0,p=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
l=a[0];
for(i=1;i<10;i++)
{
if(a[i]>l)
l=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]!=l)
{
if(sl==0)
{
sl=a[i];
p=i;
}
if(a[i]>sl)
{
sl=a[i];
p=i;
}
}
}
System.out.println(“Position of second largest:”+p);
}
}
13. Write a program to input 10 numbers into an integer array and arrange the numbers in
descending order using Linear Sorting technique.
import java.util.*;
class Sol13
{
static void main()
14. Write a program to input 10 numbers into a float type array and arrange the numbers in
descending order using Bubble Sorting technique.
import java.util.*;
class Sol14
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]<a[j+1])
257Arrays
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
15. Write a program to input 10 numbers into an integer array and reverse the array and print the
modified array.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
After reversal it should have the elements arranged as:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
25 67 16 15 34 89 7 3 12 9
Ans.
import java.util.*;
class Sol15
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<5;i++)
{
t=a[i];
a[i]=a[9-i];
a[9-i]=t;
}
259Arrays
17. Write a program to input 10 numbers into an integer array and find the frequency of the
largest number.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 89 3 7 89 34 15 16 67 89
Output should be:
Frequency of largest number = 3
Ans.
import java.util.*;
class Sol17
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,l=0,c=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<9;i++)
{
if(a[i]>l)
l=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]==l)
c++;
}
System.out.print(“Frequency of the largest:”+c);
}
}
18. Write a program to input 10 numbers into an integer array and input a position. Now delete the
element at that position by shifting the rest of the numbers to the left and insert a 0 at the end.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
And element at position 4 is to be deleted, the resultant array should be:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 34 15 16 67 25 0
for(i=p;i<9;i++)
{
a[i]=a[i+1];
}
a[9]=0;
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
19. Write a program to input 10 numbers into an integer array and input a number and a position.
Now insert the number at that position by shifting the rest of the numbers to the right. The
last element is therefore removed from the array.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
And if 36 is to be inserted at position 4, the resultant array should be:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 36 89 34 15 16 67
Notice that the last element i.e. 25 got removed after the shifting process.
Ans.
import java.util.*;
class Sol19
{
static void main()
{
261Arrays
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,p,n;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=9;i>p;i--)
{
a[i]=a[i-11];
}
a[p]=n;
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
20. Write a program to input 10 positive or negative numbers (no zero) into an integer array and
shift all positive numbers to the beginning of the array and negative numbers to the end of
the array; without changing the order of the numbers.
For example, if the array contains the following elements:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
-9 12 -3 -7 89 -34 15 16 -67 25
After shifting the array should contain the elements arranged in the following manner:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
12 89 15 16 25 -9 -3 -7 -34 -67
Positive numbers Negative numbers
Ans.
import java.util.*;
class Sol20
{
static void main()
{
Scanner sc=new Scanner(System.in);
21. Write a program to input 10 numbers into an integer array and shift all even numbers to the
beginning of the array and odd numbers to the end of the array; without changing the order
of the numbers.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 24
After shifting the resultant array should be:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
12 34 16 24 9 3 7 89 15 67
Ans.
import java.util.*;
class Sol21
{
static void main()
{
Scanner sc=new Scanner(System.in);
263Arrays
int a[]=new int[10],i,j,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]%2!=0 && a[j+1]%2==0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
22. Write a program to input 10 numbers into an integer array and print those single-digit positive
numbers which are not present in the array.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 9 16 8 24
Output should be:
1, 2, 4, 5, 6
Ans.
import java.util.*;
class Sol22
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j;
boolean f;
System.out.println(“Enter 10 numbers:”);
265Arrays
if(a[j]==i)
f++;
}
if(f>0)
System.out.println(“Frequency of “+i+” is=”+f);
}
}
}
24. Write a program to input 10 numbers into an integer array and find the frequency of each
number present in it.
Ans. import java.util.*;
class Sol24
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,f,c;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
c=f=0;
for(j=0;j<10;j++)
{
if(a[i]==a[j])
{
c++;
if(j<i)
f=1;
}
}
if(f==0)
System.out.println(“Frequency of “+a[i]+” is=”+c);
}
}
}
25. Write a program to input 10 numbers into an integer array and print the number having
maximum frequency assume that there is only one number having maximum frequency.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
99 12 34 7 99 34 12 16 12 24
267Arrays
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,b[]=new int[10],c=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
b[c++]=a[i];
}
System.out.println(“Resultant Array:”);
for(i=0;i<c;i++)
{
System.out.print(b[i]+ “ ”);
}
}
}
27. Write a program to input 10 numbers into an integer array and store only the unique numbers
into another array and display it.
For example, if the given array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
99 12 34 7 99 36 12 16 14 123
The resultant array should be:
b[0] b[1] b[2] b[3] b[4] b[5]
34 7 36 16 14 123
Ans.
import java.util.*;
class Sol27
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,b[]=new int[10],c=0,j,p=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
p=0;
269Arrays
b[c++]=a[i];
}
System.out.println(“Resultant Array:”);
for(i=0;i<c;i++)
{
System.out.print(b[i]+“ ”);
}
}
}
29. Write a program to input 10 numbers into an integer array and store all even numbers into
one array and all odd numbers into another array. Display all the three arrays.
For example, if the given array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
99 12 34 7 87 36 94 16 14 45
The resultant arrays should be:
b[0] b[1] b[2] b[3] b[4] b[5]
12 34 36 94 16 14
c[0] c[1] c[2] c[3]
99 7 87 45
Ans.
import java.util.*;
class Sol29
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,b[]=new int[10],c[]=new int[10];
int ib=0,ic=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
b[ib++]=a[i];
else
c[ic++]=a[i];
}
System.out.println(“Resultant Array Even No.s:”);
271Arrays
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,l=0,s=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==0 && j==0)
l=s=a[i][j];
else
{
if(a[i][j]>l)
l=a[i][j];
if(a[i][j]<s)
s=a[i][j];
}
}
}
System.out.print(“Largest=”+l);
System.out.print(“Smallest=”+s);
}
}
32. Write a program to input numbers into a 5×5 integer matrix and interchange the largest
number with the smallest number and display the modified matrix.
For example. if the given matrix is:
5 12 13 45 22
17 67 48 19 2
100 17 10 128 79
11 28 156 59 63
72 29 37 59 71
273Arrays
else if(a[i][j]==s)
a[i][j]=l;
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}
}
33. Write a program to input numbers into a 5×5 integer matrix and find the sum of each row
separately.
For example, if the given matrix is:
1 2 3 5 2
7 6 8 9 2
1 7 11 3 4
3 2 5 9 8
5 5 3 2 1
Output:
Sum of row 1 = 13
Sum of row 2 = 32
Sum of row 3 = 26
Sum of row 4 = 27
Sum of row 5 = 16
Ans.
import java.util.*;
class Sol33
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,s=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
275Arrays
}
}
for(i=0;i<5;i++)
{
s=0;
for(j=0;j<5;j++)
{
s+=a[j][i];
}
System.out.println(“Sum of column” +(i+1)+ “= “+s);
}
}
}
35. Write a program to input numbers into a 5×5 integer matrix and check whether all numbers in
it are even numbers or not.
Example 1:
If the given matrix is:
6 12 14 46 22
18 66 48 18 2
100 16 10 128 80
8 28 156 60 64
72 30 38 58 72
Output:
All are even numbers.
Example 2:
If the given matrix is:
6 12 14 45 22
18 68 48 22 146
100 27 10 128 78
49 81 35 60 63
72 30 40 70 78
Output:
All are not even numbers.
Ans.
import java.util.*;
class Sol35
{
static void main()
{
Scanner sc=new Scanner(System.in);
277Arrays
if(a[i][i]>l)
l=a[i][i];
if(a[i][i]<s)
s=a[i][i];
if(a[i][4-i]>l)
l=a[i][4-i];
if(a[i][4-i]<s)
s=a[i][4-i];
}
System.out.println(“Largest=”+l);
System.out.println(“Smallest=”+s);
}
}
37. Write a program to input numbers into a 5×5 integer matrix and sort the major diagonal
elements in descending order.
Ans.
import java.util.*;
class Sol37
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i][i]<a[j][j])
{
t=a[i][i];
a[i][i]=a[j][j];
a[j][j]=t;
}
}
}
System.out.println(“Sorted Array:”);
279Arrays
{
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}
}
39. Write a program to input numbers into a 5×5 integer matrix and sort elements of each row in
ascending order.
Ans.
import java.util.*;
class Sol39
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t,r;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(r=0;r<5;r++)
{
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[r][i]>a[r][j])
{
t=a[r][i];
a[r][i]=a[r][j];
a[r][j]=t;
}
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
281Arrays
{
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}
}
41. Write a program to input numbers into a 5×5 integer matrix and print the number having
maximum frequency.
Ans.
import java.util.*;
class Sol41
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t,r,c,p,max=0,n=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(r=0;r<5;r++)
{
for(c=0;c<5;c++)
{
p=0;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[r][c]==a[i][j])
p++;
}
}
if(p>max)
{
max=p;
n=a[r][c];
}
}
}
42. Write a program to input numbers into a 5×5 integer matrix and print the frequency of each
number.
Ans.
import java.util.*;
class Sol42
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,l=0,s=0,x,c;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==0 && j==0)
l=s=a[i][j];
else
{
if(a[i][j]>l)
l=a[i][j];
if(a[i][j]<s)
s=a[i][j];
}
}
}
for(x=s;x<=l;x++)
{
c=0;
for(i=0;i<5;i++)
283Arrays
{
for(j=0;j<5;j++)
{
if(x==a[i][j])
c++;
}
}
if(c>0)
System.out.println(“Frequency of”+x+“is=”+c);
}
}
}
43. Write a program to read in a 5×5 matrix and then ask for an input of a number and search
its position in the matrix. If found, print the indices where it is found, otherwise print “Not
Found”.
Ans.
import java.util.*;
class Sol43
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0,n;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println(“Enter the number to search:”);
n=sc.nextInt();
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]==n)
{
System.out.println(“Position present at i=”+i+ “j=”+j);
f=1;
}
}
}
285Arrays
45. Write a program to input numbers into a 5×5 integer matrix and check whether it is a diagonal
matrix or not. Diagonal matrix is such a matrix whose major diagonal elements are non-zeroes
and rest of the elements are zeroes.
Ans. import java.util.*;
class Sol45
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
{
if(a[i][j]==0)
f=1;
}
else
{
if(a[i][j]!=0)
f=1;
}
}
}
if(f==0)
System.out.println(“Diagonal Matrix”);
else
System.out.println(“Not a Diagonal Matrix”);
}
}
46. Write a program to input numbers into a 5×5 integer matrix and find it’s transpose. The
transpose of a matrix is a new matrix whose rows are the columns of the original. (This makes
the columns of the new matrix the rows of the original). Here is a matrix and its transpose:
The superscript “T” means transpose.
287Arrays
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]!=a[j][i])
f=1;
}
}
if(f==0)
System.out.println(“Symmetric Matrix”);
else
System.out.println(“Not a Symmetric Matrix”);
}
}
48. Write a program to input numbers into a 5×5 integer matrix and check whether it is a Lower
Triangular Matrix or not. Lower Triangular Matrix is such a matrix whose elements above the
major diagonal are zeroes and below the major diagonal are non-zeroes.
Ans.
import java.util.*;
class Sol48
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
289Arrays
{
b[i][j]=sc.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(c[i][j]+“\t”);
}
System.out.println();
}
}
}
50. Write a program to input numbers into a 5×5 integer matrix and check whether it is zero or
null matrix or not. A null matrix is a matrix, whose all elements are zero.
Ans.
import java.util.*;
class Sol50
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
if(a[i][i]!=a[0][0])
f=1;
}
if(f==0)
System.out.println(“Scalar Matrix”);
else
System.out.println(“Not a Scalar Matrix”);
}
}
52. Create a class named Student containing the following instance variables:
Instance Variables:
roll[ ] of int type array reference.
291Arrays
name[ ] of String type array reference.
Member functions:
i. Parameterized constructor to initialize the data members.
ii. T o accept a roll as parameter and search for it in roll[]. If found, the corresponding name
should be displayed otherwise a relevant message should be displayed.
Ans.
import java.util.*;
class Student
{
int roll[];
String name[];
Student(int r[],String n[])
{
roll=r;
name=n;
}
void search(int r)
{
int i,f=0;
for(i=0;i<roll.length;i++)
{
if (roll[i]==r)
{
System.out.println(“Name:”+name[i]);
f=1;
}
}
if(f==0)
System.out.println(“Not found”);
}
}
53. Create a method which accepts an integer as parameter and return true if it is a prime number,
otherwise return false. Now use it in another method which accepts a two-dimensional
integer array as parameter and check whether all the elements of the minor diagonal are
prime numbers or not.
Ans.
import java.util.*;
class Sol53
{
static boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
293Arrays
s=a[i];p=i;
for(j=i+1;j<10;j++)
{
if(a[j]<s)
{
s=a[j];
p=j;
}
}
a[p]=a[i];
a[i]=s;
}
System.out.println(“Sorted Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
56. Write a program to store 6 element in an array P, and 4 elements in an array Q and produce a
third array R, containing all elements of array P and Q. Display the resultant array.
Ans.
class Sol56
{
static void main()
{
int P[]={4,12,23,34,45,56};
int Q[]={17,15,12,23};
int R[]=new int[10],i,c=0;
for(i=0;i<6;i++)
{
R[c++]=P[i];
}
for(i=0;i<4;i++)
{
R[c++]=Q[i];
}
295Arrays
System.out.println(“Resultant Array:”);
for(i=0;i<10;i++)
{
System.out.print(R[i]+“\t”);
}
}
}
57. Write a program to accept the year of graduation from school as an integer value from the
user. Using the Binary Search technique on the sorted array of integers given below, output
the message ‘Record exists’ if the value input is located in the array. If not, output the message
Record does not exist”.
(1982, 1987, 1993. 1996, 1999, 2003, 2006, 2007, 2009, 2010)
Ans.
import java.util.*;
class Sol57
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]={1982,1987,1993,1996, 1999, 2003, 2006, 2007, 2009, 2010},l,u,n,m,f=0;
System.out.println(“Enter the year of graduation:”);
n=sc.nextInt();
l=0;u=a.length-1;
while(l<=u)
{
m=(l+u)/2;
if(a[m]==n)
{
f=1;
break;
}
else if(a[m]>n)
u=m-1;
else
l=m+1;
}
if(f==1)
System.out.println(“Record exists”);
else
System.out.println(“Record does not exist”);
}
}
297Arrays
Chapter 9
String Manipulation
Answer as directed
1. Give the output of the following program fragment:
String s=new String(“He went to the market”);
String r;
r=s.replace(“went”,“is going”);
System.out.println(r);
Ans.
Output:
He is going to the market
2. Give the output of the following program fragment:
String s=“String”;
int a=12,b=45;
System.out.println(s+a+b);
System.out.println(a+s+b);
System.out.println(a+b+s);
Ans.
Output:
String1245
12String45
57String
3. Give the output of the following program fragment:
String s=“india”,s1=“IndIA”,s2=s;
System.out.println(s.equals(s1));
System.out.println(s.equalsIgnoreCase(s1));
System.out.println(s2==s);
System.out.println(s.toUpperCase()==s1.toUpperCase());
System.out.println(s.startsWith(“IN”.toLowerCase()));
System.out.println(s1.endsWith(“iA”.toUpperCase()));
Ans.
Output:
false
true
true
false
true
true
SECTION B
Write programs for the following:
1. Write a program to count the number of non-blank characters in a given sentence.
Ans.
import java.util.*;
class Sol1
{
static void main()
3. Write a program to input a sentence and count the number of vowels in it.
Ans. import java.util.*;
class Sol3
{
static void main()
{
16. In a set of 50 names, it is intended to find the total number of names which contains at least
one pair of consecutive letters, e.g., SURABHI. In this ‘A’ and ‘B’ are consecutive letters and ‘H’
and ‘I’ are consecutive letters. Write a program for the above program.
Ans.
import java.util.*;
class Sol16
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s[]=new String[50];
int i,c=0,j;
System.out.println(“Enter 50 names:”);
for(i=0;i<50;i++)
s[i]=sc.nextLine();
for(i=0;i<50;i++)
{
for(j=0;j<s[i].length()-1;j++)
{
if((char)(s[i].charAt(j)+1)==s[i].charAt(j))
{
c++;
break;
}
}
}
System.out.println(“No. of words :”+c);
}
}
for(i=0;i<s.length()-1;i++)
{
if((char)(s.charAt(i)+1)== s.charAt(i+1))
c++;
}
System.out.println(“Pairs of consecutive letter :”+c);
}
}
19. Pig Latin is a language game of alterations played in English. To form the Pig Latin form of an
English word the initial consonant sound is transposed to the end of the word and an ay is
affixed (for example, trash yields ash-tray and plunder yields under-play). Write a program to
input a word and change it to Pig Latin.
Ans.
import java.util.*;
class Sol19
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,n;
int i;
System.out.println(“Enter a word:”);
s=sc.nextLine().toUpperCase();
for(i=0;i<s.length();i++)
{
char x=s.charAt(i);
if(x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
34. Write a program to input a sentence and print the sentence in reverse order without reversing
each word.
For example, If input is
He went to the market
Output should be
market the to went He
Ans.
import java.util.*;
class Sol34
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,w=“ ”,r=“ ”;
char x;
int i;
System.out.println(“Enter a sentence:”);
s=sc.nextLine();
s=s.trim()+“ ”;
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!= ‘ ’)
w=w+x;
else
{
r=w+“ ”+r;
w=“ ”;
}
}
System.out.println(“New Sentence:”+r);
}
}
Question 1
(a) Differentiate between class variable and instance variable.
(b) Mention two difference between Binary search and Linear search.
(c) Define wrapper class.
(d) What do you mean by rvalue and lvalue?
(e) Why Java do not require a destructor?
Ans.
(a) Class variables only have one copy that is shared by all the different objects of a class,
whereas every object has it’s own personal copy of an instance.
(b) The major difference between linear search and binary search is that binary search takes
less time to search an element from the sorted list of elements. So it is inferred that
efficiency of binary search method is greater than linear search.
Another difference between the two is that there is a prerequisite for the binary search,
i.e., the elements must be sorted while in linear search there is no such prerequisite.
(c) A Wrapper class is a class whose object wraps or contains a primitive data types. In other
words, we can wrap a primitive value into a wrapper class object.
(d) “lvalue” either means “expression which can be placed on the left-hand side of the
assignment operator”, or means “expression which has a memory address”. “rvalue” is
defined as “all other expressions”.
(e) Java has its own garbage collection implementation so it does not require any destructor
like C++ . Still we can have destructor along with garbage collector where developer can
free resources and which can save garbage collector’s work.
Question 2
(a) State the difference between Constructor and Method.
(b) Define fall through.
(c) What is the difference between ordinary compilation and Java compilation?
(d) What is the difference between String and Array?
(e) What is meant by private visibility of a method?
Ans. (a)
Java Constructor Java Method
Constructor is used to initialize the state of an Method is used to expose behaviour of an
object. object.
(b) A “fall through” is what we call it when a case in a switch statement doesn’t end in a break,
return, throw, or any other control-breaking statement. In these cases, program execution
continues to the next case block (regardless of the value in the switch), and so control “falls
through” to the case below it.
(c) In ordinary compilation the source code is directly converted into machine or object code
using an interpreter or a compiler .In Java compilation into an the source code is first
converted into an intermediate code called the byte code.
(d) An array is used to hold multiple values of the same type. An array may hold
• multiple primitive values of same type, or
• multiple object references of same type.
String is a nothing but a sequence of characters within double quotes.
(e) Private access modifier simply means that the method on which it is used will be accessible
only in the enclosing class.
Question 3
(a) Name the keyword that
(i) Transfers the control to the beginning of the loop and skips the rest of the loop body.
(ii) The variables whose single copy is made for all the objects of a class.
(iii) The keyword that is used to distinguish between instance variable and local variables.
(b) Give the output of the following:
int x=10;
int y=20;
if((x<y)||(x=5)>10)
System.out.print(y);
else
System.out.print(x);
(c) What will be the output of the following program segment?
String name[]={“Board”,”Examinations”};
System.out.println(name[0].length());
System.out.println(name.length());
(d) Find the output
class Aa
{
void display()
Question 5
Write a program to accept any string: Count and print the number of pairs of consecutive letters
present in words in the forward direction only. Assume that all the letters in the string are in
the same case, consecutive letters in two different words are not counted and ‘za’ or ‘ZA’ in any
word is not a consecutive pair.
For example:
INPUT:
Enter String: ABSTRACT STRING IS BEING COUNTED EDUCATIONALLY.
OUTPUT:
Pairs of consecutive letter: 3
Ans.
import java.util.*;
class Q5
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,c=0;
char x,y;
String s;
System.out.println(“Enter the sentence:”);
s=sc.nextLine();
for(i=0;i<s.length()-1;i++)
{
x=s.charAt(i);
y=s.charAt(i+1);
if((char)(x+1)==y)
c++;
}
System.out.println(“No. of pairs:”+c);
}
}
Question 7
Write a menu driven program using function overloading (the function name is display) to
perform the
following:
(a) To find the sum of the series up to the limit given by user i.e 2+3+5+7+11+……………..
(b) To print the following pattern:
000
001
010
011
100
Question 9
(a) WAP to calculate the sum of the following series.
S = 1/2! – 2/5! – 4/10! + 8/17! – 16/26! – 32/37! + 64/50! ……..n terms
(b) WAP to display the chain of 5 consecutive composite numbers within 1 to 100.
e.g 24, 25, 26, 27, 28
62, 63, 64, 65, 66
*******************************
(b)
import java.util.*;
class Q9b
{
static void main()
{
int n,i,j,c,f=0,m=0,p=0;
for(i=1;i<=100;i++)
{
c=0;
for(j=1;j<=i;j++)
}
}
Question 1
(a) What do you know about instance variable?
(b) Explain the concept of try-catch-finally with a suitable example. What is the use of ‘finally’
keyword?
(c) State and explain the multiple branch selection statement provided by Java.
(d) Given numbers 23, 45, -33, 533, 100. Illustrate a binary search to locate the number 500.
(e) What is control variable?
Ans.
(a) Instance variable in java is used by Objects to store their states. Variables which are defined
without the STATIC keyword and are Outside any method declaration are Object specific
and are known as instance variables. They are called so because their values are instance
specific and are not shared among instances.
(b) The try block encases any statements that might cause an exception to occur. The catch
block(s) provide a place to handle the exception thrown by the statements within a try
block.
The statements in the finally block are always executed. This is useful to clean up resources
in the event of the try block executing without an exception and in the cases when there is
an exception.
For example,
class x
{
static void divide(int a,int b)
{
int c;
try
{
c=a/b;
System.out.println(“Quotient:”+c);
}
catch(ArithmeticException e)
{
System.out.println(“Division error”);
}
finally
{
(c) The switch statement is a multi-way branch statement. The switch statement of Java is
another selection statement that defines multiple paths of execution of a program. It
provides a better alternative than a large series of if-else-if statements.
(d) Set of numbers: 23, 45, -33, 533, 100
Ascending Order: -33, 23, 45, 100, 533
Lower limit Upper limit Mid Check
0 4 2 45<500
3 4 3 100<500
4 4 4 533>500
4 3 --- Not found
(e) A control variable in computer programming is a program variable that is used to regulate
the flow of control of the program. In definite iteration, control variables are variables
which are successively assigned (or bound to) values from a predetermined sequence of
values.
Question 2
(a) Why is a class known as composite data type?
(b) What is Recursive method?
(c) What is Function Signature?
(d) Differentiate a constructor from a destructor.
(e) Which unit of a class gets called when the object of the class is created?
Ans.
(a) A composite data type is one which is composed with various primitive data type. A
class defined with various primitive data types such as int, double etc; so it is known as a
composite data type; and it is used to create objects which hold similar types of values and
behaviours (functions).
(b) Recursion is a basic programming technique you can use in Java, in which a method calls
itself to solve some problem. A method that uses this technique is recursive method.
(c) A function signature (or type signature, or method signature) defines input and output of
functions or methods. A signature can include: parameters and their types. a return value
and type. exceptions that might be thrown or passed back.
(d) Constructor is used to initialize the instance of a class. Destructor destroys the objects
when they are no longer needed. Constructor is Called when new instance of a class is
created. Destructor is called when instance of a class is deleted or released.
(e) Constructor
Question 4
(a) Read the following overloaded method prototypes and answer the question that follow:
void calculate ( int x, double y );
void calculate ( double x, double y, double z);
(i) Write the java statement to invoke the method “calculate” using actual parameters a = 20, b
= 45.52.
(ii) Write the java prototype to overload the method calculate to return a double result and
accepts two double parameters.
Question 5
Binomial co-efficient can be calculated by using the following formula:
n!
nCm = ---------------- [where! sign represents the factorial of a number]
m! (n – m)!
WAP in java to calculate and print the binomial co-efficient of the given expression, taking the
value n and m as input. Make use of the function int fact(int k), which returns the factorial of a
number k.
void display()
{
System.out.println(“EMPLOYEE No.\t\tNAME\t\tGROSS SALARY\t\tPF”);
}
else
System.out.println(“Nearest Prime:”+n);
}
}
Question 8
Write a menu driven program in java to perform the following ( using switch case ):
(i) to print the value of S where
S = 1/1! + ( 1 + 2 )/( 1! + 2! ) + ( 1 + 2 + 3 ) / ( 1! + 2! + 3! ) + …….… upto n terms.
(ii) to print the value of S where
S = 1n + 2(n-1) + ...…………………………….……….. + (n-1)2 + n1
Ans.
import java.util.*;
class Q8
{
static long fact(long k)
{
long i,f=1;
for(i=1;i<=k;i++)
k=k*i;
return k;
}
Question 9
WAP in java to accept the NAME and TOTAL MARKS obtained in an exam of a class having N
number of students and display the NAME and TOTAL MARKS of the students according to the
rank 1st, 2nd and 3rd.
Ans.
import java.util.*;
class Q9
Question 1
(a) What is the difference between an object and a class?
(b) What does the token ‘keyword’ refer to, in the context of Java? Give an example for keyword.
(c) What is the difference between entry controlled and exit controlled loop?
(d) What are the two ways of invoking functions?
(e) What is the difference between / and % operators?
Ans.
(a) A class is a blueprint or template that defines the characteristics and behaviour of an entity.
Object on the other hand is an instance of a class.
(b) A keyword refers to the reserve words that has a special meaning to the Java compiler. Eg,
for, if, else, while etc.
(c) Loop, where test condition is checked before entering the loop body, known as Entry
Controlled Loop. Loop, where test condition is checked after executing the loop body,
known as Exit Controlled Loop.
(d) Call by Value and Call by Reference.
(e) / is used to find the quotient and % is used to find the remainder when 2 numbers are
divided.
Question 2
(a) State the total size in bytes, of the arrays a[4] of char data type and p[4] of float data type.
(b) (i) Name the package that contains Scanner class.
(ii) Which unit of the class gets called, when the object of the class is created.
(c) Give the output of the following:
String n=“Computer Kowledge”;
String m=“Computer Applications”;
System.out.println(n.substring(0,8).concat(m.substring(9)));
System.out.println(n.endsWith(“e”));
(d) Write the output of the following:
(i) System.out.println(Character.isUpperCase(‘R’));
(ii) System.out.println(Character.toUpperCase(‘j’));
(e) What is the role of keyword void in declaring functions?
Question 3
(a) Analyse the following program segment and determine how many times the loop will be
executed and what will be the output of the program segment?
int p=200;
while(true)
{
if(p<100)
break;
p=p-20;
}
System.out.println(p);
(b) What will be the output of the following code?
(i) int k=5, j=9;
k+ = k++ - ++j + k;
System.out.println(“k=”+k);
System.out.println(“j=”+j);
(ii) double b=-15.6;
double a=Math.rint(Math.abs(b));
System.out.println(“a=”+a);
(c) Explain the concept of constructor overloading with an example.
(d) Give the prototype of a function search which receives a sentence sentnc and a word wrd and
returns 1 or 0.
(e) Write an expression in Java for
(f) 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.
(ii) Convert a number stored in a String variable x to double data type.
(g) Name the keyword that
(i) informs that an error has occurred in an input/output operation.
Question 4
Define a class called mobike with the following description:
Instance variables/ data members:
int bno - to store the bike’s 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 detail of the customer
void compute() - to compute the rental charge.
The rent for a mobike is charged on the following rental basis:
First five days ` 500 per day.
Next five days ` 400 per day
Rest of the days ` 200 per day.
void display() to display the details in the following format:
Bike No. Phone No. Name No. of days Charge
_______ ________ _________ ________ _______
Ans.
import java.util.*;
class mobike
{
int bno,phno,days,charge;
String name;
Question 5
Write a program to input and store the weight of ten people. Sort and display them in descending
order using the selection sort technique.
Ans.
import java.util.*;
class Q5
{
Question 6
Write a program to input a number and print whether the number is a special number or not.
(A number is said to be special number, if the sum of the factorial of the digits of the number is
same as the original number).
Example: 145 is a special number, because 1!+4!+5!=1+24+120=145
(Where ! stands for factorial of the number and the factorial value of a number is the product of
all integers from 1 to that number, example 5!=1*2*3*4*5=120).
Ans.
import java.util.*;
class Q6
{
static int fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
Question 7
Write a program to accept a word and convert it into lowercase if it is in uppercase, and display
the new word by replacing only the vowels with the character following it.
Example:
Sample Input: ComPuter
Sample output: cpmpvtfr
Ans.
import java.util.*;
class Q7
{
static void main()
{
int i;
String w,n=“ ”;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a word:”);
w=sc.nextLine();
w=w.toLowerCase();
for(i=0;i<w.length();i++)
Question 8
Design a class to overload a function compare( ) as follows:
(a) void compare(int, int) - to compare two integer values and print the greater of the
two integers.
(b) void compare(char, char) - to compare the numeric value of two characters and print the
character with higher numeric value.
(c) void compare(String, String) - to compare the length of the two strings and print the longer
of the two.
Ans.
class Overload
{
void compare(int a, int b)
{
if(a>b)
System.out.println(a);
else
System.out.println(b);
}
void compare(char a, char b)
{
if(a>b)
System.out.println(a);
else
System.out.println(b);
}
void compare(String a, String b)
{
if(a.length()>b.length())
Question 9
Write a menu driven program to perform the following: (Use switch-case statement)
(i) To print the series 0,3,8,15,24… n terms(value of ‘n’ is to be an input by the user.)
(ii) To find the sum of the series given below:
S=1/2+3/4+5/6+7/8+--------19/20
Ans.
import java.util.*;
class Q9
{
Question 1
(a) Define Abstraction in Java.
(b) What are actual parameters and formal parameters?
(c) Differentiate between for loop and do-while loop.
(d) Define Wrapper class with an example.
(e) How much bytes does the following data types occupy:
(i) Short
(ii) long
(iii) double
(iv) char
Ans.
(a) Abstraction is a process of hiding the implementation details from the user. Оnly the
functionality will be provided to the user. In Java, abstraction is achieved using abstract
classes and interfaces.
(b) Java tutorial: actual parameter vs formal parameter. Formal parameters are the parameters
as they are known in the function/method definition. Actual parameters are also known as
arguments and are passed by the caller on method invocation (calling the method).
(c) Difference:
for loop do while loop
It is an entry controlled loop. It is an exit controlled loop.
The loop do not execute if the condition The loop executes at least once even if the
is false. condition is false.
(d) A Wrapper class is a class whose object wraps or contains a primitive data types. When
we create an object to a wrapper class, it contains a field and in this field, we can store a
primitive data types. In other words, we can wrap a primitive value into a wrapper class
object. Example- Integer, Character Float, Short etc.
(e) (i) 2 bytes
(ii) 8 bytes
(iii) 8 bytes
(iv) 2 bytes
Question 5
Write a Java program to print the first 15 numbers of the Pell series.
In mathematics, the Pell numbers are an infinite sequence of integers. The Sequence of Pell
numbers starts with 0 and 1, and then each Pell number is the sum of twice the previous Pell
number and the Pell number before that.: thus, 70 is the companion to 29, and 70 = 2 x 29 + 12
= 58 + 12. The first few terms of the sequences are: 0, 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378,
5741, 13860…
Question 6
Maharashtra State Electricity board charges their consumers according to the units consumed
(per month) as per the given tariff: UNITS CONSUMED CHARGES Up to 100 units 80 paise / unit
More than 100 upto 200 units `. 1 / unit More than 200 units ` 1.25 / unit
In addition to the above mentioned charges, every consumer has to pay ` 50 as Service Charge
per month and calculate the Electricity Bill. Write a program to create the object of the class and
call the member methods.
Ans.
import java.util.*;
class Q6
{
void calc()
{
Scanner sc=new Scanner(System.in);
int units;
double charge;
System.out.println(“Enter the no. of units:”);
units=sc.nextInt();
if(units<=100)
charge=units*0.80;
else if(units<=200)
charge=100*0.80+(units-100)*1.00;
else
charge=100*0.80+100*1.00+(units-200)*1.25;
charge=50+charge;
Question 8
Design a class to overload a function prStr() are as follows: void prStr(String s1, String s2) – Print
the string that has more number of vowels from amongst s1 and s2.
void prStr(String s, char ch) – Replace all blank spaces from String s with ch and print the String
s. void prStr(String s) – Print the first and last position of letter ‘G’ in String s.
Ans.
class Overload
{
void prStr(String s1, String s2)
{
int i,c1=0,c2=0;
s1=s1.toUpperCase();
s2=s2.toUpperCase();
for(i=0;i<s1.length();i++)
{
char x=s1.charAt(i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
c1++;
}
for(i=0;i<s2.length();i++)
{
char x=s2.charAt(i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
c2++;
}
if(c1>c2)
System.out.println(s1);
else
System.out.println(s2);
}
void prStr(String s, char ch)
{
s=s.replace(‘ ’, ch);
Question 9
Write a program using switch-case statements: 1. input an string array of size 10 and sort them
in descending order using bubble sort technique. 2. initialize an array of size 9 Indian currency
notes and initialize another array with their respective currency serial numbers. Search for a
currency note input by the user, in the list.
If found, display “Search Successful” and print the currency along with the serial number,
otherwise display “Search unsuccessful Name not enlisted.” Write an appropriate message for
incorrect option.
Ans.
import java.util.*;
class Q9
{
Question 1
(a) Name any two library packages.
(b) State two main features of an Object Oriented Programming language.
(c) What is meant by a user defined data type?
(d) Show the use of logical operator && with an example.
(e) Explain the term - “pass by reference”.
Ans.
(a) java.util and java.lang
(b) Encapsulation and Polymorphism
(c) A user-defined data type (UDT) is a data type that derived from an existing data type. You
can use UDTs to extend the built-in types already available and create your own customized
data types.
(d) A && logical operator returns a Boolean result that’s based on the Boolean result of one
or two other expressions. Returns true if both of the operands evaluate to true. Both
operands are evaluated before the And operator is applied.
(e) When composite data types are passed to a method it is termed as pass by reference. Thus
any changes made to the formal parameters are reflected back to the actual parameters.
Question 2
(a) Give an example of Syntax error.
(b) How is I/O Exception helpful in handling I/O errors?
(c) Differentiate between indexOf() and valueOf() methods.
(d) What is the scope of the keyword protected in accessing methods?
(e) Find the output of z:
int y = 14;
int z = ++y * (y– + –y);
Ans.
(a) C=a+b
(b) It is helpful when the expected data from the I/O device is not received for whatever
reasons.
(c) The java string indexOf() method returns index of given character value or substring. The
valueOf method returns the relevant Number Object holding the value of the argument
passed.
int week = 4;
String day;
switch (week) {
case 1:
day = “Sunday”;
break;
case 2:
day = “Monday”;
break;
case 3:
day = “Tuesday”;
break;
case 4:
day = “Wednesday”;
break;
case 5:
day = “Thursday”;
break;
case 6:
day = “Friday”;
break;
case 7:
day = “Saturday”;
break;
default:
day = “Invalid day”;
break;
}
System.out.println(day);
}
}
When you run the program, the output will be:
Wednesday
(b) E=Math.pow(a+b,2);
(c)
class PickCode
{ private char ch;
(d) A stream can be defined as a sequence of data. The InputStream is used to read data from
a source and the OutputStream is used for writing data to a destination.
(e) Strings are immutable in Java it means once created you cannot modify content of String. If
you modify it by using toLowerCase(), toUpperCase() or any other method, It always result
in new String. Since String is final there is no way anyone can extend String or override any
of String functionality.
(f) anytine
Java is Funamytime
(g) if(n%2==0 && n>35 && n<67)
a=a+4;
if(n%2==0 && n>35 && n<67)
n=n/a;
if(n%2==0 && n>35 && n<67)
rem=n%10;
(h) Pack ob=new Pack();
(i) Constructor with parameters is called parameterised constructor, that is generally used to
accept values for initialisation of its data members.
(j) It is used to ensure that multiple instances of the main() method is not created with each
instances of an object.
Question 4
Define a class Book Store having the following specifications:
Data Member: Name of the book, author, publication and cost.
Member Methods:
(i) To accept the book details
(ii) To calculate the discount of 13.5% given on all books.
(iii) To display the book details.
Using a main method and an object. call the above methods
Ans.
import java.util.*;
class BookStore
{
String name,author,pub;
double cost;
void accept()
Question 6
Write a program to accept numbers in a 4×4 matrix, then print the all prime numbers present in
the matrix with array Index value.
SAMPLE DATA:
INPUT:
16 15 1 2
6 4 10 14
9 8 12 5
3 7 11 13
OUTPUT:
PRIME ROW INDEX COLUMN INDEX
203
330
523
731
11 3 2
13 3 3
Ans.
import java.util.*;
class Q6
{
static boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
Question 8
Write a menu driven class to accept a number and check whether it is
(a) Palprime number – [a number is a palindrome and a prime number Eg. 101]
(b) Armstrong number – [Sum of the cubes of the digits = number Eg. 153]
Ans.
import java.util.*;
class Q8
{
Question 9
Write a program to input a word in uppercase and rearrange the characters of the word in
alphabetical order.
Ans.
import java.util.*;
class Q9
{
static void main()
{