Computer Applications: Solution (ICSE)
Computer Applications: Solution (ICSE)
Solution (ICSE)
X
A. Tick () the correct option.
1. Name the programming technique that implements programs as an organised collection of
interactive objects.
a. Procedure Oriented Programming b. Modular Programming
c. Object Oriented Programming d. None of these
Ans.
2. Name the characteristics of Object Oriented Programming that hides the complexity and
provides a simple interface.
a. Encapsulation b.
Polymorphism
c. Abstraction d. Inheritance
Ans.
3. Which among the following operator is used to access individual members of an object?
a. . (dot) b. + (plus)
c. – (minus) d. / (divide)
Ans.
4. Which among the following modifier is used in a ‘class’?
a. public b. default
c. Both a and b d. None of
these
Ans.
5. Which among the following is a valid class name?
a. Simple Interest b. SimpleInterest
c. 1SimpleInterest d. Simple@Interest
Ans.
6. Which among the following is a valid object name?
a. obj1 b. 1obj
c. Obj 1 d. Obj#1
Ans.
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.
8. Which among the following is a valid octal integer literal?
a. 0178 b. 675
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.
2. Procedure Oriented Language follows top down approach.
3. Java is an example of Object Oriented Language.
4. Hiding the complexity and giving a simple interface is called Inheritance.
5. Abstraction is same as encapsulation.
6. An object is called a class factory.
7. A class is an instance of an object.
8. A class is a mechanism to implement encapsulation.
9. Data members in a class is used to represent the characteristic of an object.
3 Revision Tour I
10. The new operator is used to create an object.
11. It’s a rule to have a class-name beginning in capital letter.
Section A
Answer the following questions:
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.
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.
12. Write one difference between primitive data type and composite data type.
Ans.
Fundamental data type Composite data type
These are inbuilt data type provided by the These are data types created by the user using
Java Language. fundamental or user defined data type or both.
The size of it is fixed. The size of different user-defined data type
depends upon the size of the individual
components of it.
These data types are available in all parts These data types are available only as specified
of a program within a class. by the access specifiers.
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.
5 Revision Tour I
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, mobile, bed, keyboard, mouse, chair Class is a group of similar objects.
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.
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.
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?
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( )
{
a=5;
b=6;
}
void show ( )
{
[Link] (a+ ‘’ ‘’ + b);
}
static void main( )
{
7 Revision Tour I
My Class ob = new My Class ( );
ob. initialize ( ); show ( ). ob;
}
}
Ans. class MyClass
{
int a, b; void
initialize( )
{ a=5;
b=6;
}
void show ( )
{
[Link] (a+ ‘’ ‘’ + b);
}
Ans. a. 5
15
b. 19
9 Revision Tour I
-37
c. 6
4
d. 14 14 27 16 15 35
e. true true
10 14
f. true true
8
g. false true
h. 10 17 17
true
32. What will be the output when the following code segment is executed?
[Link](“The king said \”Begin at the beginning!\ “to me”);
Ans. The king said “Begin at the beginning!” to me
34. What is the value of y after evaluating the expression given below? y+=++y + y-- + --y;
when int y=8
Ans. y=33
35. Give the output of the following expression:
a+=a++ + ++a + --a + a--; when a=7. Ans. a=39
37. What are the values of x and y when the following statements are executed? int a = 63, b =
36; boolean x = (a < b ) ? true : false; int y= (a > b ) ? a : b;
Ans. x=false y=63
38. What will be the result stored in x after evaluating the following expression? int x=4;
40. What is the result stored in x, after evaluating the following expression?
int x = 5; x = x++ * 2 + 3 * –x;
Ans. x=-8
43. State the number of bytes occupied by char and int data types.
Ans. char = 2 bytes int = 4
bytes
11 Revision Tour I
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;
[Link](“Sum=”+s);
[Link](“Difference=”+d);
}
}
2. Write a program to find the product of 5, 7 and 12 using variables.
Ans. class q2
{
static void main()
{
int a=5,b=7,c=12,d;
d=a*b*c;
[Link](“Product=”+d);
}
}
3. Write a program to find the product of the sum and difference between 17 and 2 using
variables.
Ans. class q3
{
static void main()
{
int a=17,b=2,s,d;
s=a+b;
d=a-b;
[Link](“Sum=”+s);
[Link](“Difference=”+d);
}
}
13 Revision Tour I
p=a*b;
[Link](“Sum=”+s);
[Link](“Difference=”+d);
[Link](“Product=”+p);
}
}
8. Write a program using float type variables to find the area and perimeter of a square whose side is
12.5 cm.
Ans. class q8
{
static void main()
{
float s=12.5f,a,p;
a=s*s;
p=4*s;
[Link](“Area=”+a);
[Link](“Perimeter=”+p);
}
}
9. Write a program using int variables to find the area and perimeter of a rectangle of length 12cm
and breadth 8cm.
Ans. class q9
{
static void main()
{
int l=12,b=8,a,p;
a=l*b;
p=2*(l+b);
[Link](“Area=”+a);
[Link](“Perimeter=”+p);
}}
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;
}}
11. Write a program to input the Principal, Rate and Time and calculate the Simple Interest.
}}
15 Revision Tour I
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;
[Link](“Before Interchange: a=”+a+“b=”+b);
c=a; a=b; b=c;
[Link](“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;
[Link](“Sum=”+d);
}}
15. Write a program to initialise an int variable a with 76498 and from it extract the first digit and
store it into a variable f and extract the last digit into a variable l and display both these digits.
Ans. class q15
{
static void main()
{
int a=76498,f,l;
f=a/10000; l=a%10;
[Link](“First Digit=”+f);
[Link](“Last Digit=”+l);
}}
16. Write a program using ternary operator to check whether 27 is a multiple of 3 or not.
Ans. class q16
{
static void main()
{
[Link]((27%3==0)?“Multiple of 3”:“Not a multiple of 3”);
}
}
17 Revision Tour I
Ans. d. Addition is required but subtraction is performed.
C. State whether the following statements are True (T) or False (F).
1. Scanner class is present in the [Link] package. F
2. [Link]( ) is used to find the absolute value of a number. T
3. The return type of [Link]( ) function is float. F
4. The fraction 1/2 will evaluate to 0.5. F
19 Revision Tour II
5. The continue statement in a switch block is used to avoid fall through. F
6. The default statement is essential in a switch block. F
7. The for loop is an entry controlled loop. T
8. The while loop is an exit controlled loop. F
9. The do-while loop is generally used when the number of iterations is known. F 10. You can have
only the for loop as the nested loops. F
SECTION A
Answer the following questions.
3. What are the different types of errors that may occur in a Java program?
Ans. Syntax Error, Logical Error and Run-time Error.
9. What is the difference between the Scanner class functions next() and nextLine()?
Ans. next() can read the input only till the space. It can’t read two words separated by space. Also, next()
places the cursor in the same line after reading the input. nextLine() reads input including space
between the words (that is, it reads till the end of line \n).
12. What are logical operators? Explain each of them with the help of an example.
Ans. The logical operators are used to combine simple relational statements into more complex
expressions.
21 Revision Tour II
Entry Control Loop Exit Control Loop
The test expression or condition is checked The test expression or condition is checked
before entering the loop. after entering the loop.
It the test expression evaluates to false, the Even if the test expression evaluates to false,
loop doesn’t get executed. the loop gets executed atleast once.
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)
[Link](“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
{
[Link](“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.
18. What are Nested-loops? Give an example of a nested for-loop to show its functionality.
Ans. A loop within a loop is called a nested loop.
Example of a nested loop is:
public class Loops
{
static void Nested()
23 Revision Tour II
Difference: The for loop may have initialisation, test expression and updation, written before the loop.
The while loop have the initialisation always before the loop and updation in the body of the loop.
22. Analyze the following program segment and determine how many times the body of loop will be
executed (show the working).
Ans. The loop executes as long as the given condition is true.
24. Give the output and determine how many times the loop will execute:
x=1; y=1;
while(x<=y)
{ y = y/x;
[Link](y);
}
Ans. x=1; y=1; x<=y -> the loop
executes once. y=y/x =1/1=1
x<=y -> the loop executes next time
The entire process will continue infinite number of times, with the output as 1 in different lines.
30. Convert the following segment into an equivalent do loop. int x,c;
for (x=10, c=20; c>=10; c = c – 2) x++;
Ans.
int x=10,c=20;
do {
x++;
c=c-2;
}while(c>=10);
31. Give the output of the following program segment and also mention how many times the loop is
executed: int i; for (i = 5 : i > 10; i ++)
[Link](i);
[Link](i * 4); Ans.
Output:
20
The loop do not execute, as the condition results to false.
32. Convert the following while loop to the corresponding for loop:
int m = 5, n = 10;
while (n>=1)
25 Revision Tour II
{
[Link](m*n); n–;
}
Ans.
int m=5,n; for(n=10;n>=1;n--)
{
[Link](m*n);
}
33. Convert following do-while loop into for loop.
int i = 1; int d=5; do { d=d*2;
[Link](d;) i++ ; } while (i<=5); Ans.
int I,d=5;
for(i=1;i<=5;i++)
{
d=d*2;
[Link](d);
}
34. What will be the output of the following code?
int m=2; int n=15; for(int i = 1; i<5; i++); m++; –
–n;
[Link](“m=” +m);
[Link](“n=” +n); Ans.
m=3 n=14
35. Analyze the given program segment and answer the following questions:
for(int i=3;i<=4;++)
{
for(int j=2;j<i;j++)
{
[Link](“ ”);
}
[Link](“WIN”);
}
i. How many times does the inner loop execute ? ii. Write the output of the
program segment.
Ans.
i. The inner loop executes 3 times.
ii. Output:
WIN
WIN
27 Revision Tour II
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 = [Link]([Link](a)); double y =
[Link]([Link](a,b)); Ans. x=6.0 and y=15.0
48. Analyze the given program segment and answer the following questions:
(i) Write the output of the program segment.
(ii) How many times does the body of the loop gets executed?
for(int m=5; m<=20; m+=5)
{
if(m%3 == 0) break;
else
if(m%5 == 0) [Link](m);
continue;
}
Ans. i. Output:
5 10
ii. The loop executes 3 times.
49. Give the output of the following program segment and also mention the number of times the loop
is executed:
29 Revision Tour II
Ans. Output:
12
The loop executes 2 times.
Ans.
a. [Link](a+b)
b. 1/3.0+[Link](a,3)+1/3.0*[Link](b,3)
c. s=u*t+1/2.0*a*[Link](t,2)
d. d=[Link](l*l+b*b);
e. (-b+[Link](b*b-4*a*c))/(2*a)
f. ([Link](a,3)+[Link](b,3))/ ([Link](a,3)-[Link](b,3))
g. [Link]((a-b)/(a+b))
h. [Link]((a+b)/(a*b))
i. [Link](a+b.n)/[Link](3+b)
j. z=(5*x*x*x+2*y)/(x+y);
k. [Link](2*a*s+u*u)
l. [Link](3*x+x*x)/(a+b)
m. (a*a+b*b)/(2*a*b)
n. T=[Link](A*A+B*B+C*C);
o. a*[Link](x,5)+b*[Link](x,3)+c
31 Revision Tour II
SECTION B
Programming Questions
1. Write a program to input the area of a square and find its perimeter.
Ans. import [Link].*; class Sol1
{
static void main()
{
Scanner sc=new Scanner([Link]);
double a,s,p;
[Link](“Enter the area of a square:”);
a=[Link](); s=[Link](a);
p=4*s;
[Link](“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 [Link].*; class Sol5
{
static void main()
{
Scanner sc=new Scanner([Link]); int
a,b,c;
[Link](“Enter 3 integers:”);
a=[Link]();
b=[Link]();
c=[Link](); if(a<b &&
a<c)
[Link](“Smallest:”+a); else
if(b<a && b<c)
[Link](“Smallest:”+b); else
[Link](“Smallest:”+c);
33 Revision Tour II
}}
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 [Link].*; class Sol6
{
static void main()
{
Scanner sc=new Scanner([Link]); int
a,b,c;
[Link](“Enter 3 angles:”);
a=[Link](); b=[Link]();
c=[Link](); if(a+b+c==180)
{
if(a<90 && b<90 && c<90)
[Link](“Acute angled triangle”);
else if(a>90 || b>90 || c>90)
[Link](“Obtuse angled triangle”);
else
[Link](“Right angled triangle”);
} else
[Link](“Cannot form a triangle”);
}}
7. Write a program to input the three sides 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, each side should be less the sum of the other two sides.
To form an equilateral triangle every side should be equal.
To form an isosceles triangle any two sides should be equal.
To form a scalene triangle all three sides should be different from each other.)
Ans. import [Link].*; class Sol7
{
static void main()
{
Scanner sc=new Scanner([Link]); int
a,b,c;
[Link](“Enter 3 sides:”);
a=[Link](); b=[Link]();
c=[Link]();
35 Revision Tour II
}}
9. Write a program to accept a mark obtained by a student in computer science and print the grades
accordingly:
Marks Grade
Above 90 A
70 to 89 B
50 to 69 C
below 50 D
Ans. import [Link].*; class Sol9
{
static void main()
{
Scanner sc=new Scanner([Link]); int
c;
[Link](“Enter marks in Computer science:”); c=[Link]();
if(c>=90)
[Link](“Grade=A”); else
if(c>=70 && c<90)
[Link](“Grade=B”); else
if(c>=50 && c<70)
[Link](“Grade=C”); else
[Link](“Grade=D”);
}}
10. A cloth showroom has announced the following festival discounts on the purchase of items, based
on the total cost of the items purchased:
Total Cost Discount (in Percentage)
Less than `2000 5%
`2001 to `5000 25%
`5001 to `10000 35%
Above `10000 50%
Write a program to input the total cost and compute and display the amount to be paid by the customer
after availing the discount.
Ans. import [Link].*; class Sol10
{
static void main()
{
Scanner sc=new Scanner([Link]); float
tc,d,ap;
37 Revision Tour II
else if(a>=25001 && a<=57000)
d=5/100f*a;
else if(a>=57001 && a<=100000)
d=7.5f/100*a;
else
d=10/100f*a;
}
if(type==’D’)
{
if(a>=0 && a<=25000)
d=5/100f*a;
else if(a>=25001 && a<=57000)
d=7.5f/100*a;
else if(a>=57001 && a<=100000)
d=10f/100*a;
else
d=15/100f*a;
}
na=a-d;
[Link](“Name:”+name);
[Link](“Address:”+add);
[Link](“Ndet amount:”+na);
}}
12. Given below is a hypothetical table showing rates of Income Tax for male citizens below the age of
65 years:
Taxable Income (TI) in Income Tax in
Does not exceed 1,60,000 Nil
Is greater than 1,60,000 and less than or (TI – 1,60,000) * 10%
equal to 5,00,000
Is greater than 5,00,000 and less than or [(TI – 5,00,000) * 20%] + 34,000
equal to 8,00,000
Is greater than 8,00,000 [(TI – 8,00,000) * 30%] + 94,000
Write a program to input the age, gender (male or female) and Taxable Income of a person. If the age is
more than 65 years or the gender is female, display “wrong category*.
If the age is less than or equal to 65 years and the gender is male, compute and display the Income Tax
payable as per the table given above.
Ans. import [Link].*; class Sol12
{
static void main()
{
Scanner sc=new Scanner([Link]);
39 Revision Tour II
b) class Sol13
{ static void main()
{
int i;
for(i=99;i>=1;i-=2)
{
[Link](i+“ ”);
}
}
}
c) class Sol13
{ static void main()
{
int i;
for(i=7;i<=70;i+=7)
{
[Link](i+“ ”);
}
}
}
d) class Sol13
{ static void main()
{
int i;
for(i=80;i>=8;i-=8)
{
[Link](i+“ ”);
}
}
}
e) class Sol13
{
static void main()
{
int i;
for(i=1;i<=10;i++)
{
[Link]((i*i)+“ ”);
}
f)
class Sol13
{
static void main()
{
int i;
for(i=1;i<=10;i++)
{
[Link]((i*i-1)+“ ”);
}
}
}
g) import [Link].*;
class Sol13
{
static void main()
{
int i,n,s=1;
Scanner sc=new Scanner([Link]); [Link](“Enter the number of terms:”);
n=[Link]();
for(i=1;i<=n;i++)
{
[Link](s+“ ”);
s=s+i;
}
}
}
h) import [Link].*;
class Sol13
{ static void h()
{
int i,n,s=2,c=2;
Scanner sc=new Scanner([Link]); [Link](“Enter the number of terms:”);
n=[Link]();
for(i=1;i<=n;i++)
{
[Link](s+“ ”);
41 Revision Tour II
s=s+c; c=c+2;
}
}
}
i)
import [Link].*;
class Sol13
{
static void main()
{
int i,n,s=1,c=1;
Scanner sc=new Scanner([Link]); [Link](“Enter the number of terms:”);
n=[Link]();
for(i=1;i<=n;i++)
{
[Link](s+“ ”);
s=s+c; c=c+2;
}
}
} j) import [Link].*;
class Sol13
{
static void main()
{
int i,n,f=1,s=0,t;
Scanner sc=new Scanner([Link]);
[Link](“Enter the number of terms:”); n=[Link]();
for(i=1;i<=n;i++)
{
t=f+s;
[Link](t+“ ”);
f=s; s=t;
}
}
}
k) import [Link].*;
class Sol13
{
static void main()
14. Write a program to find the sum of all 3-digit even natural numbers.
Ans. class Sol14
{
static void main()
{ int i,s=0;
for(i=100;i<=998;i+=2)
{ s+=i;
}
[Link](“Sum=”+s);
}}
15. Write a program to find the sum of all 3 digit odd natural numbers, which are multiples of 5.
Ans. class Sol15
{
static void main()
{ int i,s=0;
for(i=101;i<=999;i+=2)
{
If(i%5==0)
s+=i;
}
[Link](“Sum=”+s);
}
}
16. Write a program to input an integer and find its factorial. Factorial of a number is the product of all
natural numbers till that number. For example factorial of 5 is 120 since 1×2×3×4×5=120.
Ans. import [Link].*; class Sol16
{
43 Revision Tour II
static void main()
{
long i,n,f=1;
Scanner sc=new Scanner([Link]); [Link](“Enter
an integer:”);
n=[Link]();
for(i=1;i<=n;i++)
{
f=f*i;
}
[Link](“Factotrial:”+f);
}
}
17. Write a program to input an integer and check whether it is a prime number or not.
Ans.
import [Link].*;
class Sol17
{
static void main()
{
long i,n,c=0;
Scanner sc=new Scanner([Link]); [Link](“Enter
an integer:”);
n=[Link]();
for(i=1;i<=n;i++)
{
If(n%i==0)
c++;
}
If(c==2)
[Link](“Prime Number”); else
[Link](“Not a Prime Number”);
}}
18. Write a program to input 10 integers and find the sum of two-digit as well as three-digit numbers
separately.
Ans.
import [Link].*;
class Sol18
{
static void main()
{
45 Revision Tour II
Ans. import [Link].*; class Sol20
{
static void main()
{
int i,n,f=0;
Scanner sc=new Scanner([Link]); [Link](“Enter
10 integers:”);
for(i=1;i<=10;i++)
{
n=[Link]();
if(n%2!=0)
f=1;
} if(f==0)
[Link]
n(“All are even
numbers”);
else
[Link](“All are not even numbers”);
}}
21. Write a program to input 10 integers and check whether all the entered numbers are same or
not.
For Example, INPUT:
Enter 10 numbers: 10 12 13 234 45 34 67 78 76 12 OUTPUT:
All numbers are not same.
INPUT:
Enter 10 numbers: 12 12 12 12 12 12 12 12 12 12 OUTPUT:
All numbers are same.
Ans. import [Link].*; class
Sol20
{
static void main()
{
int i,n,f=0,p=0;
Scanner sc=new Scanner([Link]); [Link](“Enter
10 integers:”);
for(i=1;i<=10;i++)
{
n=[Link]();
if(i==1)
p=n; else
47 Revision Tour II
static void main()
{
int i,n,f=1,s=0,t;
for(i=1;i<=15;i++)
{
t=f+2*s;
[Link](t+“ ”);
f=s;
s=t;
}
}}
24. Write a program to find the sum of 1st 10 numbers of Lucas series i.e. 2,1,3,4,7,11,18,…. Lucas series
is such a series which starting from 2 and 1, and subsequent numbers are the sum of the previous
two numbers.
Ans.
class Sol24
{
static void main()
{
int i,n,f=2,s=1,t,sum=0;
sum=f+s; for(i=1;i<=8;i++)
{ t=f+s;
sum+=t; f=s;
s=t;
}
[Link](“Sum=”+sum);
}}
25. Write a program to input an integer and check whether it is perfect, abundant or deficient number. If
the sum of the factors excluding itself is equal to that number it is perfect, if greater than that
number it is abundant and if less than that number it is deficient number.
Ans. import [Link].*; class Sol25
{
static void main()
{
int i,n,s=0;
Scanner sc=new Scanner([Link]);
[Link](“Enter an integer:”);
n=[Link]();
for(i=1;i<n;i++)
{
if(n%i==0)
49 Revision Tour II
123 543 321
1234 5432 4321
12345 54321 54321 iv.
54321 v. 54321 vi. 1
5432 4321 22
543 321 333
54 21 4444
5 1 55555 vii. 55555
viii. 11111 ix. 5
4444 2222 44
333 333 333
22 44 2222
1 5 11111
x. * xi. ***** xii * *
** **** ** *** *** *
**** ** * *
***** * * *
xiii. 1 xiv. 12345 xv 1
01 2345 01
101 345 010
0101 45 1010
10101 5 10101
010101
xxiv. xxv.
xxvi. 1 xxvii. 1
11 23
121 456
1331 7 8 9 10
14641 11 12 13 14 14
1 5 10 5 1
1 6 15 15 6 1
Ans.
i)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
[Link](j);
}
[Link]();
}
}
}
51 Revision Tour II
ii)
{
int i,j;
for(i=5;i>=1;i--)
{ for(j=5;j>=i;j-
-)
{
[Link](j);
}
[Link]();
}
}
}
iii)
class Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{ for(j=i;j>=1;j-
-)
{
[Link](j);
}
[Link]();
}
}
}
{ for(j=5;j>=i;j-
-) {
[Link](j);
}
[Link]();
}
}
}
v) class Sol27
{ static void
main()
{
int i,j;
for(i=5;i>=1;i--)
{ for(j=i;j>=1;j-
-)
{
[Link](j);
}
[Link]();
}
}
}
53 Revision Tour II
}
}
vii)
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
[Link](i);
}
[Link]();
}
}
}
viii)
class Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
{
[Link](i);
}
[Link]();
}
}
} ix) class
Sol27
{ static void
main()
{
int i,j;
for(i=5;i>=1;i--)
{
}
}
x) class Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
[Link](“*”);
}
[Link]();
}
}
}
xi) class
Sol27
{ static void
main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
[Link](“*”);
55 Revision Tour II
}
[Link]();
}
}
}
xii)
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i==j || i+j==6)
[Link](“*”);
else
[Link](“ ”);
}
[Link]();
}
}}
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)
[Link](“1”);
else
[Link](“0”);
}
[Link]();
}
}}
57 Revision Tour II
for(j=1;j<=i;j++)
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; else --f;
[Link](f);
}
[Link]();
}
}}
59 Revision Tour II
{
int i,j; for(i=6;i>=1;i--)
{
for(j=i;j<=5;j++) [Link](“ ”); for(j=i;j>=1;j--)
[Link](j); for(j=2;j<=i;j++) [Link](j);
[Link]();
}
}}
61 Revision Tour II
{
for(j=1;j<=11;j++)
{
if(i+j>=7 && j-i<=5) [Link](“*”); else
[Link](“ ”);
}
[Link]();
}
}}
63 Revision Tour II
}
c2=0;
for(j=1;j<=r;j++)
{
if(r%j==0)
c2++;
}
if(c1==2 && c2==2)
[Link](i+“ ”);
}
}
}
30. Input an integer and form a new number where the digits are in ascending order.
Ans. import [Link].*;
class Sol30
{
static void main()
{
Scanner sc=new Scanner([Link]);
int i,j,n,s=0,c=0,d;
[Link](“Enter a number:”);
n=[Link]();
for(i=9;i>=0;i--) {
for(j=n;j>0;j/=10)
{
d=j%10;
if(d==i)
s=s+d*(int)[Link](10,c++);
}
}
[Link](“New Number:”+s);
}
}
31. Write a program to pass an integer as argument and print the largest as well as smallest digit.
Ans.
class Sol31
{
static void main(int n)
{
int i,d,max=0,min=0;
for(i=n;i>0;i/=10)
65 Revision Tour II
13
Ans.
import [Link].*;
class Sol33
{
static void main()
{
Scanner sc=new Scanner([Link]); int i,d,n,s=0,c=0;
[Link](“Enter a number:”);
n=[Link]();
for(i=n;i>0;i/=10)
{
d=i%10; if(d%2==1)
s=s+d*(int)[Link](10,c++);
}
[Link](“New Number:”+s);
}
}
34. Write a program to pass an integer as argument and print the number by having the digits
arranged in ascending order.
Ans.
class Sol34
{
static void main(int n)
{
int i,j,s=0,c=0,d;
for(i=9;i>=0;i--)
{
for(j=n;j>0;j/=10)
{
d=j%10;
if(d==i)
s=s+d*(int)[Link](10,c++);
}
}
[Link](“New Number:”+s);
}
}
35. Write a program to pass an integer as argument and check whether all digits in it are unique
or not.
67 Revision Tour II
37. Write a program to input an integer and check whether it is an automorphic, trimorphic or
triautomorphic number or not. A number n is said to be automorphic, if its square ends in n. For
instance 5 is automorphic, because 52= 25, which ends in 5, 25 is automorphic, because 252=625,
which ends in 25. A number n is called trimorphic if n3 ends in n. For example 493, = 117649, is
trimorphic. A number n is called tri-automorphic if 3n2 ends in n; for example 667 is tri-
automorphic because 3 × 6672, = 1334667, ends in 667. Ans. import [Link].*; class Sol37
{
static void main()
{
Scanner sc=new Scanner([Link]);
int i,j,f=0,n;
[Link](“Enter a number:”);
n=[Link]();
for(i=n;i>0;i/=10)
f++;
if((n*n)%(int)[Link](10,f)==n)
[Link](“Automorphic Number”);
else if((n*n*n)%(int)[Link](10,f)==n)
[Link](“Trimorphic Number”); else
if((3*n*n)%(int)[Link](10,f)==n)
[Link](“Tri-automorphic Number”);
else
[Link](“Not Automorhic,Trimorphic or Tri-automorphic Number”);
}
}
38. Write a program to input a number and check whether it is a happy number or not. If you
iterate the process of summing the squares of the decimal digits of a number and if this
process terminates in 1, then the original number is called a happy number. For example 7=>
(72)=49=> (42+92)=97=>(92 +72)=130 =>(12 +32+02)=10 =>(12+02)= 1.
Ans.
import [Link].*;
class Sol38
{
static void main()
{
Scanner sc=new Scanner([Link]);
int d,s,n;
[Link](“Enter a number:”);
n=[Link]();
do
{
69 Revision Tour II
[Link](“Magic Number”);
else
[Link](“Not a Magic Number”);
}
}
40. Write a program to input an integer and check whether it is Harshad or Niven number or not.
A number is said to be Harshad if it is divisible by the sum of the digits of that number, example
126 and 1729. Ans.
import [Link].*;
class Sol40
{
static void main()
{
Scanner sc=new Scanner([Link]);
int d,s=0,n,i;
[Link](“Enter a number:”);
n=[Link]();
for(i=n;i>0;i/=10)
{
d=i%10;
s+=d;
}
if(n%s==0)
[Link](“Harshad Number”);
else
[Link](“Not a Harshad Number”);
}
}
41. Write a program to input a number and check whether it is a Kaprekar number or not. Take a
positive whole number n that has d number of digits. Take the square n and separate the
result into two pieces: a right-hand piece that has d digits and a left-hand piece that has
either d or d-1 digits. Add these two pieces together. If the result is n, then n is a Kaprekar
number. Examples are 9 (92 = 81, 8 + 1 = 9), 45 (452 = 2025, 20 + 25 = 45), and 297 (2972 =
88209, 88 + 209 = 297).
Ans. import [Link].*;
class Sol41
{
static void main()
{
Scanner sc=new Scanner([Link]);
int f=0,n,i,h1,h2;
71 Revision Tour II
Enter 2 integers:
12
8 OUTPUT:
H.C.F. = 4 Ans.
import [Link].*;
class Sol43
{
static void main()
{
Scanner sc=new Scanner([Link]);
int i,a,b,l=0;
[Link](“Enter 2 numbers:”);
a=[Link](); b=[Link]();
for(i=a;i<=a*b;i++)
{
if(i%a==0 && i%b==0)
{ l=i;
break;
}
}
[Link](“HCF.:”+(a*b)/l);
}
}
44. Write a menu driven class to accept a number from the user and check whether it is a
Palindrome or a Perfect number.
(a) Palindrome number- (a number is a Palindrome which when read in reverse order is same as
read in the right order) Example: 11, 101, 151, etc.
(b) Perfect number- (a number is called Perfect if it is equal to the sum of its factors other than the
number itself.) Example: 6=1+2+3 Ans.
import [Link].*;
class Sol44
{
static void main()
{
Scanner sc=new Scanner([Link]);
int i,n,s=0,ch,d;
[Link](“M E N U”);
[Link](“1. Palindrome Number”);
[Link](“2. Perfect Number”);
[Link](“Enter your choice:”);
ch=[Link]();
{ case
1:
for(i=n;i>0;i/=10)
{
d=i%10;
s=s*10+d;
}
if(s==n)
[Link](“Palindrome Number”);
else
[Link](“Not a palindrome
number”); break; case 2:
for(i=1;i<n;i++)
{
if(n%i==0)
s+=i;
}
if(s==n)
[Link](“Perfect Number”);
else
[Link](“Not a perfect
number”); break; default:
[Link](“Invalid choice!”);
}
}
}
45. Write a menu driven program to accept a number from the user and check whether it is
‘BUZZ’ number or to accept any two numbers and print the ‘GCD’ of them.
(a) A BUZZ number is the number which either ends with 7 or divisible by 7.
(b) GCD (Greatest Common Divisor) of two integers is calculated by continued division method.
Divide the larger number by the smaller; the remainder then divides the previous divisor. The
process is repeated till the remainder is zero. The divisor then results the GCD.
Ans. import [Link].*;
class Sol45
{
static void main()
73 Revision Tour II
{
Scanner sc=new Scanner([Link]);
int i,n,r,ch,d;
[Link](“M E N U”);
[Link](“1. Buzz Number”);
[Link](“2. GCD”);
[Link](“Enter your choice:”);
ch=[Link]();
switch(ch)
{ case
1:
[Link](“Enter a number:”);
n=[Link]();
if(n%10==7 || n%7==0)
[Link](“Buzz Number”);
else
[Link](“Not a Buxx
number”); break; case 2:
[Link](“Enter 2
numbers:”); n=[Link]();
d=[Link]();
do
{
r=n%d;
if(r!=0)
{ n=
d;
d=r;
}
}while(r!=0);
[Link](“GCD:”+d);
break; default:
[Link](“Invalid choice!”);
}
}
}
46. Write a program to find the sum of the following series:
S=1+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+3+4+5)+…+(1+2+3+4+…+10)
(Please note that no nested loop is to be used) Ans. class
Sol46
{
75 Revision Tour II
Ans.
import [Link].*;
class Sol48
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a,n,i,f=1; float
sum=0;
[Link](“Enter the value of a:”); a=[Link]();
[Link](“Enter the value of n:”); n=[Link]();
for(i=1;i<=n;i++)
{
sum+=(float)(a+f)/(f+1);
f+=2;
}
[Link](“Sum:”+sum);
}
}
49. Write a program to compute and display the sum of the following series:-
Ans.
import [Link].*;
class Sol49
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a=1,n,i,p=1;
float sum=0;
[Link](“Enter the value of n:”);
n=[Link]();
for(i=1;i<=n;i++)
{
a=a+(i+1);
p=p*(i+1);
sum+=(float)a/p;
}
[Link](“Sum:”+sum);
77 Revision Tour II
for(j=1;j<=i;j++)
{
[Link](i);
}
[Link]();
} break; default:
[Link](“Invalid choice!”);
}
}
}
51. Write a program to input a number and print whether the number is a special number or not.
(A number is said to be a 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 l! + 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 [Link].*;
class Sol51
{
static void main()
{
Scanner sc=new Scanner([Link]);
int i,n,j,ch,d,f,s=0;
[Link](“Enter a number:”);
n=[Link]();
for(i=n;i>0;i/=10)
{
d=i%10;
f=1;
for(j=1;j<=d;j+
+) f=f*j;
s+=f;
}
if(s==n)
[Link](“Special Number”);
else
[Link](“Not a Special Number”);
}
}
Ans.
import [Link].*;
class Sol52
{
static void main()
{
Scanner sc=new Scanner([Link]);
int i,n,ch;float s=0;
[Link](“M E N U”);
[Link](“1. First Series”);
[Link](“2. Second Series”);
[Link](“Enter your choice:”);
ch=[Link]();
switch(ch)
{ case 1:
[Link](“Enter the number of terms:”);
n=[Link]();
for(i=1;i<=n;i++)
{
s=i*i-1;
[Link](s+“ ”);
}
break; case
2:
for(i=1;i<=19;i+=2)
{
s+=(float)i/(i+1);
}
[Link](“Sum=”+s);
break; default:
[Link](“Invalid choice!”);
}
}}
53. Write a program to input a number and print all its prime factors using prime factorization.
For Example,
79 Revision Tour II
INPUT: Enter an integer: 24
OUTPUT: Prime Factors using Prime Factorisation are:
2
2
2
3 Ans.
import [Link].*;
class Sol53
{
static void main()
{
Scanner sc=new Scanner([Link]);
int n,f=2;
[Link](“Enter a number:”);
n=[Link]();
while(n>1)
{
if(n%f==0)
{
[Link](f);
n=n/f;
}
else
f++;
}
}
}
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 [Link].*;
81 Revision Tour II
Sum of digits = 5 + 9 = 14
Product of its digits = 5 x 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits to the product of its
digits.
If the value is equal to the number input, output the message “Special 2-digitnumber” otherwise,
output the message “Not a special2-digit number”.
Ans. import [Link].*;
class Sol55
{
static void main()
{
Scanner sc=new Scanner([Link]);
int n,f,l;
[Link](“Enter a number:”);
n=[Link]();
if(n>=10 && n<=99)
{
f=n/10;
l=n%10;
if(f+l+f*l==n)
[Link](“Special 2-digit number”);
else
[Link](“Not a Special 2-digit number”);
}
else
[Link](“Not a 2-digit number”);
}
}
56. Using the switch statement, write a menu driven program to calculate the maturity amount of
a Bank Deposit.
The user is given the following
options: i. Term Deposit ii.
Recurring Deposit
For option (i) accept principal(P), rate of interest(r) and time period in years(n). Calculate and
output the maturity amount(A) receivable using the formula
For option (ii) accept Monthly Instalment (P), rate of interest(r) and time period in months(n).
{ case
1:
[Link](“Enter the principal:”);
p=[Link]();
[Link](“Enter the rate:”);
r=[Link]();
[Link](“Enter the time period:”);
n=[Link]();
A=p*[Link](1+r/100,n);
[Link](“Amount=”+A);
break; case 2:
[Link](“Enter the principal:”);
p=[Link]();
[Link](“Enter the rate:”);
r=[Link]();
[Link](“Enter the time period:”);
n=[Link]();
A=p*n+p*n*(n+1)/2*r/100*1/12.0;
83 Revision Tour II
[Link](“Amount=”+A);
break; default:
[Link](“Invalid choice!”);
}
}
}
57. Use switch statement,write a menu driven program to:
(i) To find and display all the factors of a number input by the user (including 1 and excluding
number itself.)
Example:
Sample Input : n=15.
Sample Output : 1,3,5
(ii) To find and display the factorial of a number input by the user(the factorial of a non-negative
integer n ,denoted by n!, is the product of all integers less than or equal to n.
Example:
Sample Input : n=5
Sample Output : 5!=1×2×3×4×5=120.
For an incorrect choice, an appropriate error message should be displayed.
Ans.
import [Link].*;
class Sol57
{
static void main()
{
Scanner sc=new Scanner([Link]);
int ch,n,i,f=1;
[Link](“M E N U”);
[Link](“1. Factors”);
[Link](“2. Factorial”); [Link](“Enter your
choice:”); ch=[Link]();
[Link](“Enter a number:”);
n=[Link]();
switch(ch)
{ case 1:
for(i=1;i<n;i++)
{
if(n%i==0)
[Link](i+” “);
85 Revision Tour II
(where x = 2)
(ii) To display the following series:
11 111 1111 11111
For an incorrect option, an appropriate error message should be displayed.
Ans.
import [Link].*;
class Sol59
{
static void main()
{
Scanner sc=new Scanner([Link]);
int ch,n,i,f=0;double s=0;
[Link](“M E N U”);
[Link](“1. First Series”);
[Link](“2. Second Series”);
[Link](“Enter your choice:”);
ch=[Link]();
switch(ch)
{ case
1:
for(i=1;i<=20;i++)
{
if(i%2==1)
s=s+[Link](2,i);
else
s=[Link](2,i);
}
[Link](“Sum=”+s);
break; case 2:
for(i=1;i<=5;i++)
{
f=f*10+1;
[Link](f+“ ”);
}
break;
default:
[Link](“Invalid choice!”);
}
}
}
87 Revision Tour II
A. Tick () the correct option.
1. Which among the following is not a primitive data type?
a. int b. short
c. String d. Long
Ans. c. String
2. Name the operator that is used to allocate memory space for an object.
a. Dot b. New
c. Both a and b d. None of these
Ans. b. New
3. What is the name given to a memory location called in Java?
a. Variable b. Constant
c. Data Type d. None of these
Ans. a. Variable
4. Which are the data types used in Java?
a. Primitive data type b. Composite data type
c. Both a and b d. None of these
Ans. c. Both a and b
5. How are the characteristics of an object represented in a class?
a. Data Members b. Member Functions
c. Access specifiers d. None of these
Ans. a. Data Members
6. Which among the following is used to change the state of an object?
a. Data Members b. Name of the class
c. Both a and b d. None of these
Ans. a. Data Members
7. How is encapsulation implemented in a program?
a. Using a class b. Using only
Functions
c. Using only Variables d. None of these
89 Revision Tour II
8. Information passed to a method through arguments is called _____________.
a. Message b. Variables
c. Numbers d. Data
Ans. a. Message
9. What among the following is not a component of a message?
a. An object identifier b. A method name
c. Arguments d. Data Members
Ans. d. Data Members
10. How many objects can you create from a class?
a. One b. Two
c. Three d. Any number
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();
[Link](“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.
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( );
[Link]( );
[Link](“Object created”);
[Link](“I am X=”+vin.x);
[Link](“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
D. Find the errors in the program given below and rewrite the corrected form:
My class
{
int a; int b; void display()
{
[Link](a+“ ”+b);
SECTION B
Write programs for the following:
1. Write a class with name Employee and basic as its data member, to find the gross pay of an
employee for the following allowances and deduction. Use meaningful variables.
Dearness Allowance = 25% of the Basic Pay
House Rent Allowance = 15% of Basic Pay
Provident Fund = 8.33% of Basic Pay
Net Pay = Basic Pay + Dearness Allowance + House Rent Allowance
Gross Pay = Net Pay − Provident Fund
Ans. class Employee
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;
[Link](“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.
Ans.
import [Link].*;
class Salary
{
String Name, Address,subSpe;
double mSal,it; long phone;
void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter your name:”);
Name=[Link]();
[Link](“Enter your address:”);
Address=[Link]();
[Link](“Enter Subject Specialization:”); subSpe=[Link]();
[Link](“Enter Phone No.:”); phone=[Link]();
class Employee
{
String pan, name; double
tax_income,tax;
void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter your PAN no.:”); pan=[Link]();
[Link](“Enter your name:”); name=[Link]();
[Link](“Enter taxable income:”);
tax_income=[Link]();
}
void display()
{
[Link](“Pan Number\t\tName\t\tTax-income\t\tTax”);
[Link](pan+“\t\t”+name+“\t\t”+tax_income+“\t\t”++ tax);
}
void calc()
{
if(tax_income<=100000)
tax=0;
else if(tax_income>100000 && tax_income<=150000) tax=10/100.0*(tax_income-
100000);
else if(tax_income>150001 && tax_income<=250000)
tax=5000+20/100.0*(tax_income-150000); else
tax=25000+30/100.0*(tax_income-250000);
}}
5. Define a class called Mobike with the following description: Instance variables/ Data
members:
bno : to store the bike’s number
phno : to store the phone number of the customer
name : to store the name of the customer
days : to store the number of days the bike is taken on rent
charge : to calculate and store the rental charge
void withdraw(int a)
{
if(bal-a<1000)
[Link](“Minimum balance should be 1000 rupees”);
else bal-=a;
}
void datainput()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the name:”); name=[Link]();
[Link](“Enter the consumer no.:”); consumerno=[Link]();
[Link](“Enter the unit consumed:”); unitconsumed=[Link]();
}
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()
{
[Link](“Consumer Name\t\tConsumer No\t\tUnit Consumed\t\tBill Amount”);
[Link](name+“\t\t”+consumerno+“\t\t”+unitconsumed+“\t\t”+compute());
}
}
9. Write a program with the following specifications:
Class : Empl
Data Members:
void feedinfo()
{
Scanner sc=new Scanner([Link]); [Link](“Enter the flight no:”);
fl_no=[Link]();
[Link](“Enter the destination:”); dest=[Link]();
[Link](“Enter the distance:”);
dist=[Link]();
calfuel();
void Checkin()
{
void display()
{
[Link](“Name\t\tCalls Made\t\tAmount\t\tTotal Amount”);
[Link](name+“\t\t”+call+“\t\t”+amt+“\t\t”+total);
}
public static void main(String args[])
{
Telephone ob=new Telephone();
[Link](); [Link]();
[Link]();
}}
16. Define a class named movieMagic with the following description:
17. Define a class ParkingLot with the following description: Instance variables/data
members:
int vno – To store the vehicle number
int hours – To store the number of hours the vehicle is parked in the parking lot
double bill – To store the bill amount
Member methods:
void input() – To input and store vno and hours
void calculate() – To compute the parking charge at the rate of ` 3 for the first hour or
part thereof, and ` 1.50 for each additional hour or part
thereof.
void display() – To display the detail
Write a main method to create an object of the class and call the above methods
Ans. import [Link].*; class ParkingLot
{
int vno,hours; double bill;
void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the vehicle number:”); vno=[Link]();
[Link](“Enter the number of hours:”); hours=[Link]();
}
void calculate()
{
if(hours<=1) bill=3*hours;
else
bill=3*1+(hours-1)*1.50;
}
void display()
{
[Link](“Vehicle number:”+vno);
[Link](“Number of hours:”+hours);
[Link](“Bill:”+bill);
}
public static void main(String args[])
{
First_AC 700
Second_AC 500
Sleeper None
• 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 [Link].*; class
RailwayTicket
{
String name, coach;
long mobno; int
amt,totalamt;
void accept()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the name:”); name=[Link]();
[Link](“Enter the type of coach:”); coach=[Link]();
[Link](“Enter the mobile number:”); mobno=[Link]();
[Link](“Enter the amount:”);
amt=[Link]();
}
void update()
{
double rate=0;
if([Link](“First_AC”))
totalamt=amt+700;
else if([Link](“Second_AC”))
totalamt=amt+500;
else if([Link](“Third_AC”)) totalamt=amt+250; else
if([Link](“Sleeper”)) totalamt=amt;
}
void print()
{
[Link](“Name of the customer:”+name);
[Link](“Type of coach:”+coach);
[Link](“Total amount:”+totalamt);
[Link](“Mobile Number:”+mobno);
}
public static void main(String args[])
{
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.
4. If a function contains several return statements, how many of them will be executed?
Ans. The first one.
5. Name the keyword that causes the control to transfer back to the method call.
Ans. return
11. State the difference between Call by Value and Call by Reference.
Ans.
Difference between Call by Value and Call by Reference
Call by Value Call by Reference
Using this technique a copy of the values in Using this technique a reference to the values
the actual parameter is made in the formal in the actual parameter is made by the formal
parameters. parameters.
Any changes made to the formal Any changes made to the formal parameters is
19. How are static methods of one class called by methods in other classes?
Ans. The function invocation should be preceded with the name of the class followed by the dot
operator.
4. Protected access method largest which accepts a float type, int type and double type data as
parameters and have a byte type as return type.
Ans. protected byte largest(float a, int b, double c)
5. Public access static method calculate which accepts a byte and int type data type as parameters
and return float type.
Ans. public static float calculate(byte b, int d)
6. Write the function prototype for the function “sum” that takes an integer variable (x) as its
argument and returns a value of float data type.
Ans. float sum(int x)
C. Answer as directed:
SECTION B
Write programs for the following:
1. Create a method which accepts two int type variable a and b as parameter and evaluate the
following expression:
2
4 52. a b+
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 [Link].*; class Sol7
{
static int largest(int n)
{
111 1
S=1+ + + + ... 2! 3! 4! n!
(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
{ r=n%d;
if(r!=0)
{
n=d; d=r;
}
}while(r!=0);
[Link](“GCD:”+d);
break; default:
[Link](“Invalid choice!”);
}
}}
37. Write a menu driven program to accept a number and check and display whether it is a Prime
Number or not OR an Automorphic Number or not. (Use switch-case statement).
a. Prime number: A number is said to be a prime number if it is divisible only by 1 and itself and
not by any other number. Example : 3,5,7,11,13, etc.
b. Automorphic number: An automorphic number is the number which is contained in the last
digit(s) of its square. Example: 25 is an automorphic number as its square is 625 and 25 is
present as the last two digits.
Ans.
import [Link].*; class Sol37
{ static boolean isPrime(int n)
{ int i,c=0; for(i=1;i<=n;i++)
{
if(n%i==0) c++;
}
161 Constructors
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.
9. Point out the difference between implicit and explicit default constructors.
Ans. Implicit default constructor is the default constructor created by java if the user do not create a
constructor. Explicit default constructor is a non-parameterised constructor defined by the user to
initialise data members with legal initial values.
10. What are temporary objects? How are they created, explain with the help of an example?
Ans. Temporary or anonymous objects or instances are the ones that live in the memory as long as it is
being used or referenced in an expression and after that it dies. Temporary objects are created by
explicit call to a constructor, preceded with the new command. For example,
public class temp
{
int a,b;
temp(int x, int y)
{
a=x;
b=y;
}
void show()
{
[Link](a+“,”+b);
}
static void test( )
{
new temp(1,2).show( );
}
}
Here the statement new temp(1,2) of the statement new temp(1,2).show(); creates an anonymous
temporary object and lives in the memory as long as show() of the statement new temp(1,2).show();
is being executed. Upon completion of the execution of the show() function, the temporary object
gets wiped out of the memory.
163 Constructors
Java
public class Perimeter
{
public Perimeter() // I {
[Link](“From default”);
}
public Perimeter(int x) // II {
[Link](“Circle perimeter: “ + 2*[Link]*x);
}
public Perimeter(int x, int y) // III {
[Link](“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.
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( )
{
[Link](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);
[Link]();
}
}
165 Constructors
void show( )
{
[Link](a+ “ ”+b);
}
public static void main(String args[])
{
Myclass ob2=new Myclass(12,15); Myclass
ob3=new Myclass(7); [Link]();
[Link]();
}
}
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(); [Link](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 [Link].
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);
[Link](c);
}
167 Constructors
SECTION B
Write programs for the following:
169 Constructors
[Link](); [Link]();
}}
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()
{
[Link](“Sum:”+s);
}}
5. Define a class named Conversion having the following static methods:
i. int mTocm(int m ), which converts metre(m) to centimeter and return it.
ii. int multiply(int x, int y ), which returns the product of x and y.
Define another class named Rectangle which contains the following data members:
• length of int type which holds the length of a rectangle in metre.
• breadth of int type which holds the breadth of a rectangle in centimeter.
Create member functions:
i. Constructor to initialise the data members.
ii. Convert the length to centimetre by calling the relevant method of the above class.
iii. Compute the area by calling the relevant method of the above class and display
the result. Ans.
class Conversion
171 Constructors
• 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 [Link].*; class Palin
{
int num,revnum;
Palin()
{
num=0;
revnum=0;
}
void accept()
{
Scanner sc=new Scanner([Link]); [Link](“Enter
a number:”);
num=[Link]();
}
int reverse(int y)
{
for(int i=num;i>0;i/=10)
{
int d=i%10;
revnum=revnum*10+d;
}
return revnum;
}
void check()
{
if(num==reverse(num))
[Link](“Palindrome”); else
[Link](“Not palindrome”);
}
public static void main(String args[])
{
Palin ob=new Palin();
[Link]();
[Link]();
}}
173 Constructors
Ans. class Number
{ int a;
Number(int x)
{ a=x;
}
Number()
{ a=0;
}
void show()
{
[Link](a);
}
Number sum(Number t)
{
Number x=new Number();
x.a=a+t.a;
return x;
}
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. Calculate 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.
175 Constructors
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 [Link].*;
class Taximeter
{ int taxino; String name;
int km; Taximeter()
{
taxino=0;
name=“ ”;
km=0;
}
void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the taxi no.:”); taxino=[Link]();
[Link](“Enter the name:”); name=[Link]();
[Link](“Enter the kilometer:”); km=[Link]();
}
int calculate()
{
int bill=0; if(km==1)
bill=25*km; else if(km>1
&& km<=6) bill=10*km;
else if(km>6 && km<=12)
bill=15*km; else if(km>12 &&
km<=18) bill=20*km; else
bill=25*km;
return bill;
}
void display()
{
[Link](“Taxino\t\tName\t\tKilomtres travelled\t\tBill amount”);
[Link](taxino+“\t\t”+name+“\t\t”+km+“\t\t”+calculate());
}
}
11. Create a class which will contain the following components:
177 Constructors
Instance variables/data members: int product_code - stores the product
code number
String flavour - stores the flavour of the juice.(orange, apple, etc.)
String pack_type - stores the type of packaging (tetra-pack, bottle, etc.)
int pack_size - stores package size (200ml, 400ml, etc.)
int product_price - stores the price of the product
Member Methods:
FriuitJuice() - default constructor to initialise integer data members to zero and
string data members to “”.
void input() - to input and store the product code, flavour, pack type, pack size and
product price.
void discount() - to reduce the product price by 10.
void display() - to display the product code, flavour, pack type, pack size and product
price.
Create an object in the main method and call all the above methods in it. Ans.
import [Link].*;
class FruitJuice
{
int product_code,pack_size,product_price;
String flavour,pack_type;
FruitJuice()
{
product_code=pack_size=product_price=0;
flavour=pack_type=””;
}
void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the product code:”); product_code=[Link]();
[Link](“Enter the flavour:”); flavour=[Link]();
[Link](“Enter the pack type:”); pack_type=[Link]();
[Link](“Enter the pack size:”); pack_size=[Link]();
[Link](“Enter the product price:”); product_price=[Link]();
}
void discount()
{
product_price-=10;
}
void display()
{
[Link](“Product code:”+product_code);
[Link](“Flavour:”+flavour);
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 [Link].*;
class SalaryCalculation
{
String name;
double basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary, AnnualSal; SalaryCalculation()
{
Scanner sc=new Scanner([Link]); [Link](“Enter the
name:”); name=[Link]();
[Link](“Enter the basic pay:”); basicPay=[Link]();
conveyanceAlw=1000.00;
}
179 Constructors
void SalaryCal()
{
specialAlw=25/100.0*basicPay; pf=10/100.0*basicPay;
gross = basicPay + specialAlw + conveyanceAlw;
netSalary=gross-pf; AnnualSal=12*netSalary;
}
void display()
{
[Link](“Name:”+name);
[Link](“Basic Pay:”+basicPay);
[Link](“Special Allwance:”+specialAlw);
[Link](“Conveyance allowance :”+conveyanceAlw);
[Link](“Gross:”+gross);
[Link](“Provident fund:”+pf);
[Link](“Net Salary:”+netSalary);
[Link](“Annual Salary:”+AnnualSal);
}
public static void main(String args[])
{
SalaryCalculation ob=new SalaryCalculation(); [Link]();
[Link]();
}}
14. A class Compound is created to calculate the compound interest using:
r
CI = P = 1+ 100 1 −P where P - is the Principal amount, r - rate of interest and t-time period
in years.
Data memebers of class: pamt, rate (double data type to store principal amount and rate of interest),
time (integer to store time period) Functions of the class:
i. Compound()-constructor to assign default values to all the data memebers.
ii. void input()-to input the principal, rate and time from the user. iii. double findInterest()-to
find and return compound interest using the given formula. iv. void printData()-to print the
principal, rate and time.
Write a main function to input required data and by invoking suitable functions print the entered data
and compound interest.
Ans.
import [Link].*;
class Compound
{
double pamt, rate; int time;
181 Constructors
Next 100 calls 0.80 @ unit
Next 200 calls 1.00 @ unit Remaining
calls 1.20 @ unit
ii. A constructor to assign initial values of customerName as “Raju”, phoneNumber as 259461,
no_of_units as 50, rent as 100, amount as 100. iii. A function accept( ) which allows user to
enter customerName, phoneNumber, no_of_ units and rent and should call function
calculate( ).
iv. A function Display( ) to display the values of all the data members on the screen. Ans.
import [Link].*;
class PhoneBill
{
String customerName;
long phoneNumber; int
no_of_units,rent; float
amount;
void calculate()
{
float cost=0;
if(no_of_units<=50) cost=0;
else if(no_of_units>50 && no_of_units<=150)
cost=50*0+(no_of_units-50)*0.80f; else
if(no_of_units>150 && no_of_units<=350)
cost=50*0+100*0.80f+(no_of_units-150)*1.00f;
}
PhoneBill()
{
customerName=”Raju”;
phoneNumber=259461; no_of_units=50;
amount=rent=100;
}
void accept()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the customer name:”); customerName=[Link]();
[Link](“Enter the phone number:”); phoneNumber=[Link]();
[Link](“Enter the no. of units:”); no_of_units=[Link]();
[Link](“Enter the rent:”);
rent=[Link]();
}
void Display()
{
183 Constructors
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the code:”); s_code=[Link]();
[Link](“Enter the sports name:”); s_name=[Link]();
[Link](“Enter the duration:”); duration=[Link]();
if(s_name.equalsIgnoreCase(“Table Tennis”)) fees=2000;
else if(s_name.equalsIgnoreCase(“Swimming”)) fees=4000;
if(s_name.equalsIgnoreCase(“Football”)) fees=3000;
}
void displaySports()
{
[Link](“Code:”+s_code);
[Link](“Sports name:”+s_name);
[Link](“Duration:”+duration);
[Link](“Fees:”+fees);
}
}
17. Create a class called GeneratePrime which will be used to generate n number of prime numbers. 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.
ii. Method called isPrime() which accepts an integer as a parameter and return true if it is a prime
number otherwise return false.
Method called display() which displays the first n prime number by calling the above function.
Ans.
import [Link].*;
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++;
}
void display()
{
int i=0,p=2;
while(i<n)
{
if(isPrime(p)==true)
{
[Link](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.
ii. Method called isPrime() which accepts an integer as a parameter and return true if it is a prime
number otherwise return false.
Method called sumOfPrimeDigits() which accepts an integer as a parameter and find the sum of
prime digits only. Ans.
import [Link].*;
class PrimeDigits
{ int n;
PrimeDigits(int a)
{ n=a;
}
boolean isPrime(int n)
{ int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
185 Constructors
if(c==2)
return true; else
return false;
}
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;
}
[Link](“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 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 [Link].*; 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++)
187 Constructors
Scanner sc=new Scanner([Link]); [Link](“Enter a real number in n:”);
n=[Link]();
}
void roundOff()
{
r=[Link](n*100)/100.0;
}
void display()
{
[Link](“n=”+n+“r=”+r);
}
}
189 Constructors
Ans. b. [Link]
SECTION A
A. Answer the following questions.
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.
8. Explain the usage of <Wrapper Class>.parse…( ) method.
12. Name the package that contain the wrapper classes. Ans. [Link]
1. Answer as directed:
a. Assign a integer 123 to an int variable a.
b. Convert the variable a to a String and store it in the variable s.
Ans. a. int a=123;
b. String s=[Link](a);
2. Answer as directed:
a. Assign an string “123” to a String variable a.
b. Convert the variable a to an integer and store it in the variable s.
Ans. a. String a=”123”;
b. int s=[Link](a);
3. For the program given below mark the parts ___1___ and __2__ as autoboxing or unboxing.
class Example
{
static void main()
SECTION B
Write programs for the following:
{ a=x;
b=y;
}
void swap()
{ int
t=a; a=b;
b=t;
}
void display()
{
[Link](a+” “+b);
}
{ s=t;
n=0;
}
void assign()
{
n=[Link](s);
}
void largest()
{
int i,d,l=0;
for(i=n;i>0;i/=10)
{
d=i%10;
if(l==0) l=d;
if(d>l) l=d;
}
[Link](“Largest Digit:”+l);
}
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:
209 Encapsulation
• Default
• private
• protected
• public
3. State the difference between:
a. Public and private access specifier
b. Protected and default access specifier
Ans. a. Public access specifier allows accessibility inside a package as well as outside the package.
Private access specifier allows accessibility only within the class.
b. The protected specifier allows access by all subclasses of the class in a program, whatever
package they reside in, as well as to other code in the same package. The default specifier
allows access by other code in the same package, but not by code that is in subclasses residing
in different packages.
4. What can’t a class be declared as private?
Ans. A top-level class as private would be completely useless because nothing would have access to
it.
211 Encapsulation
SECTION B
Write programs for the following:
213 Encapsulation
[Link]();
}
}
215 Encapsulation
private void CalcFee()
{
if([Link](“Outdoor”))
Fee=5000;
else if([Link](“Indoor Non-AC”))
Fee=6500;
else if([Link](“Indoor AC”))
Fee=7500;
}
public void Register()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the Seminar ID:”);
SeminarID=[Link]();
[Link](“Enter the Topic:”);
Topic=[Link]();
[Link](“Enter the Venue Location:”);
VenueLocation=[Link]();
CalcFee();
}
public void ViewSeminar()
{
[Link](“Seminar ID:”+SeminarID);
[Link](“Topic:”+Topic);
[Link](“Venue Location:”+VenueLocation);
[Link](“Fee:”+Fee);
}
if(!([Link](“COTTON”)))
GPrice=GPrice-10/100f*GPrice;
}
public Garments()
{
GCode=GType=GFabric=”NOT ALLOTED”;
GPrice=GSize=0;
}
public void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter the GCode:”);
GCode=[Link]();
[Link](“Enter the GType:”);
217 Encapsulation
GType=[Link]();
[Link](“Enter the GFabric:”);
GFabric=[Link]();
[Link](“Enter the GSize:”);
GSize=[Link]();
Assign();
}
public void Display()
{
[Link](“GCode:”+GCode);
[Link](“GType:”+GType);
[Link](“GFabric:”+GFabric);
[Link](“GSize:”+GSize);
[Link](“GPrice:”+GPrice);
}
219 Encapsulation
[Link](“Distance:”+Distance);
[Link](“Fare:”+Fare);
}
221 Encapsulation
• Function isArmstrong() that checks whether the number in N is an Armstrong number or not
and accordingly returns a true or a false.
(ii) Outside the package using suitable import statements create a class called “Check” that will
have a main() function defined where an integer is taken from the user using Scanner and using the
member functions of the “Number” class check whether it is an Armstrong number or not. Ans.
(i)
package Number;
public class Armstrong
{
private int N;
public Armstrong(int n)
{
N=n;
}
public boolean isArmstrong()
{
int i,d,s=0;
for(i=N;i>0;i/=10)
{
d=i%10;
s+=d*d*d;
}
if (s==N)
return true; else
return false; }
}
(ii)
import [Link]; import
[Link]; class Check
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]); int
n;
[Link](“Enter a number:”);
n=[Link]();
Armstrong ob=new Armstrong(n);
if ([Link]())
[Link](“Armstrong No.”); else
[Link](“Not an Armstrong No.”);
223 Encapsulation
else if(tax_income>100000 && tax_income<=150000)
tax=10/100.0*(tax_income-100000); else if(tax_income>150001 &&
tax_income<=250000) tax=5000+20/100.0*(tax_income-150000); else
tax=25000+30/100.0*(tax_income-250000);
}
public static void main(String args[])
{
Employee ob1=new Employee ();
Employee ob2=new Employee (); [Link]();
[Link](); [Link](); ob2. calc (); [Link]();
ob2. display ();
}
}
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 [Link].*;
class Salary
{
String Name, Address,subSpe;
double mSal,it; long
phone;
void input()
{
Scanner sc=new Scanner([Link]);
[Link](“Enter your name:”);
Name=[Link]();
[Link](“Enter your address:”);
Address=[Link]();
[Link](“Enter Subject Specialization:”); subSpe=[Link]();
[Link](“Enter Phone No.:”); phone=[Link]();
[Link](“Enter monthly salary:”); mSal=[Link]();
}
void display()
{
[Link](“Name:”+Name);
[Link](“Address:”+Address);
225 Encapsulation
static int factorial(int p)
{ int i,f=1;
for(i=1;i<=p;i++)
f=f*i;
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)
[Link](“Special Number”);
else
[Link](“Not a Special Number”);
}
}
4. How do you initialise single and 2-dimensional arrays? Explain with examples.
Ans. The general form of Initialisation of single dimensional array is:
type array-name[ ]={ list of values }; For
example,
int n [ ] = {5, 12, 7};
The general form of Initialisation of two dimensional array is:
type array-name[ ][ ]={ {list of values},{list of values},{list of values}... }; For
example,
int a[][]={{5,1,3},{7,2,6}};
5. With the help of an example, show how arrays in Java are dynamic in nature.
Ans. Java arrays are dynamic in nature:
For example, int n;
Scanner sc=new Scanner ([Link]);
[Link](“Enter the size;”); n=[Link](); //Enter
the size from the user int arr [ ]=new int[n]; //declare an array
of size (dynamic)
As you can see the memory for the array arr is created only after taking the size ‘n’ from the user.
227 Encapsulation
<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<[Link]; i++)
{
a[i]=2*a[i];
}
}
public static void main (String args[])
{
int a []={4,5,12,7,8,3};
[Link](“Original Array...”);
for (inti=0;i<a. length;i++)
[Link](a[i]+“/t”); doubleIt(a); //
this is how you pass an array as
//parameter.
[Link] (“InUpdated Array...”);
for(int i=0;i<[Link];i++)
[Link](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 Searchii. 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.
9. Compare Selection Sorting and Bubble sorting.
229 Arrays
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.
231 Arrays
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];
}
[Link](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++)
{
[Link](sum);
}
}
}
}
Ans.
class First
{
public static void main(String args[])
{
int sum[][]=new int[2][4]; for(i=0;i<2;i++)
{
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 [Link].*; class
Sol1
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,s=0;
233 Arrays
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=[Link]();
for(i=0;i<10;i++)
s+=a[i];
[Link](“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 [Link].*; class
Sol2
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,se=0,so=0;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=[Link]();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
se+=a[i]; else
so+=a[i];
}
[Link](“Sum of even numbers=”+se);
[Link](“Sum of odd numbers=”+so);
}}
3. Write a program to input 10 numbers into an integer array and print those numbers which are less
than its average.
Ans.
import [Link].*; class
Sol3
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,s=0;
for(i=0;i<10;i++)
{
if(a[i]%2==0)
s+=a[i];
}
av=(float)s/10;
[Link](“Numbers less than average:”);
for(i=0;i<10;i++)
{
if(a[i]<av)
[Link](a[i]+“ ”);
}
}}
4. Write a program to input 10 numbers into an integer array and find the sum of prime numbers
only.
Ans.
import [Link].*; class
Sol4
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,s=0,j,c;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=[Link]();
for(i=0;i<10;i++)
{ c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
235 Arrays
}
if(c==2)
s+=a[i];
}
if(s>0)
[Link](“Sum of prime numbers:”+s);
else
[Link](“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 [Link].*; class
Sol5
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i;
boolean f=true;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=[Link]();
for(i=0;i<10;i++)
{
if(!(a[i]>=100 && a[i]<=999))
f=false;
}
if(f)
[Link](“All are 3 digit numbers”);
else
[Link](“All are not 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.
for(i=0;i<10;i++)
{
if(a[i]!=a[0])
f=false;
}
if(f)
[Link](“All are same”);
else
[Link](“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 [Link].*; class
Sol7
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i;
boolean f=true;
[Link](“Enter 10
numbers:”); for(i=0;i<10;i++)
a[i]=[Link]();
for(i=0;i<9;i++)
{
237 Arrays
if(a[i]>a[i+1])
f=false;
}
if(f)
[Link](“All are in ascending order”);
else
[Link](“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 [Link].*; class
Sol8
{ static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,l=0,s=0;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
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)
[Link](“Position of largest number:”+i);
if(a[i]==s)
[Link](“Position of smallest number:”+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;
}
[Link](“Modified Array:”);
for(i=0;i<10;i++)
{
[Link](a[i]+“ ”);
}
}}
239 Arrays
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(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;
}
[Link](“Modified Array:”);
for(i=0;i<10;i++)
{
[Link](a[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)
[Link](“Smallest prime number:”+s);
else
[Link](“No prime number found”);
}
}
12. Write a program to input 10 numbers into an integer array and print the position of the second
largest number in it. import [Link].*;
class Sol12
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,l=0,sl=0,p=0;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
l=a[0];
for(i=1;i<10;i++)
241 Arrays
{ 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;
}
}
}
[Link](“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 [Link].*;
class Sol13
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,j,t;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]<a[j])
{ t=a[i];
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 [Link].*;
class Sol14
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,j,t;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]<a[j+1])
{ t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
[Link](“Sorted Array:”);
for(i=0;i<10;i++)
{
[Link](a[i]+“ ”);
243 Arrays
}
}
}
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
Ans.
import [Link].*;
class Sol15
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,t;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=0;i<5;i++)
{ t=a[i];
a[i]=a[9-i];
a[9-i]=t;
}
[Link](“Modified Array:”);
for(i=0;i<10;i++)
{
[Link](a[i]+” “);
}
}}
16. Write a program to input 10 numbers into an integer array and interchange the consecutive
elements in it. That is, interchange a[0] with a[1], a[2] with a[3], a[4] with a[5] … 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]
245 Arrays
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=0;i<9;i++)
{
if(a[i]>l)
l=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]==l)
c++;
}
[Link](“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
for(i=p;i<9;i++)
{
a[i]=a[i+1];
}
a[9]=0;
for(i=9;i>p;i--)
{
a[i]=a[i-11];
}
a[p]=n;
[Link](“Modified Array:”);
247 Arrays
for(i=0;i<10;i++)
{
[Link](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 [Link].*;
class Sol20
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,j,t;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]<0 && a[j+1]>0)
{ t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
[Link](“Modified Array:”);
for(i=0;i<10;i++)
{
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 [Link].*;
class Sol21
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,j,t;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
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;
}
}
}
[Link](“Modified Array:”);
for(i=0;i<10;i++)
{
249 Arrays
[Link](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 [Link].*;
class Sol22
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,j;
boolean f;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=[Link]();
for(i=0;i<=9;i++)
{ f=false;
for(j=0;j<10;j++)
{
if(a[j]==i)
f=true;
}
if(f==false)
[Link](i);
}
}}
23. Write a program to input 10 numbers into an integer array and find the frequency of each two-
digit numbers present in it.
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]
251 Arrays
{ c=f=0;
for(j=0;j<10;j++)
{
if(a[i]==a[j])
{
c++;
if(j<i)
f=1;
}
} if(f==0)
[Link](“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
Output should be:
Number having maximum frequency=12 Ans.
import [Link].*;
class Sol25
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,j,max=0,n=0,c;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=0;i<10;i++)
{ c=0;
for(j=0;j<10;j++)
{
if(a[i]==a[j])
c++;
}
if(c>max)
{
253 Arrays
b[0] b[1] b[2] b[3] b[4] b[5]
34 7 36 16 14 123
Ans.
import [Link].*;
class Sol27
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,b[]=new int[10],c=0,j,p=0;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=0;i<10;i++)
{ p=0;
for(j=0;j<10;j
++)
{
if(a[i]==a[j])
p++;
}
if(p==1)
b[c++]=a[i];
}
[Link](“Resultant Array:”);
for(i=0;i<c;i++)
{
[Link](b[i]+ “ ”);
}
}}
28. Write a program to input 10 numbers into an integer array and store each number only once into
another array irrespective of the number of times it is present in the array.
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 16
The resultant array should be:
b[0] b[1] b[2] b[3] b[4] b[5] b[6]
99 12 34 7 36 16 14
import [Link].*;
class Sol28
{ p=0;
for(j=i+1;j<10;j++)
{
if(a[i]==a[j])
p++;
}
if(p==0)
b[c++]=a[i];
}
[Link](“Resultant Array:”);
for(i=0;i<c;i++)
{
[Link](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 [Link].*;
class Sol29
255 Arrays
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]=new int[10],i,b[]=new int[10],c[]=new int[10];
int ib=0,ic=0;
[Link](“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=[Link]();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
b[ib++]=a[i]; else
c[ic++]=a[i];
}
[Link](“Resultant Array Even No.s:”);
for(i=0;i<ib;i++)
{
[Link](b[i]+“ ”);
}
[Link](“Resultant Array Odd No.s:”);
for(i=0;i<ic;i++)
{
[Link](c[i]+“ ”);
}
}}
30. Write a program to input numbers into a 5×5 integer matrix and find the sum of all numbers in it.
Ans. import [Link].*; class
Sol30
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,s=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
257 Arrays
}
}
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
The resultant matrix should be:
5 12 13 45 22
17 67 48 19 156 100 17 10 128 79
11 28 2 59 63
72 29 37 59 71
Ans. import [Link].*; class Sol32
{
static void main()
{
Scanner sc=new Scanner([Link]); int a[][]=new int[5][5],i,j,l=0,s=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
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(i=0;i<5;i++)
{
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
[Link](“\t”+a[i][j]);
}
[Link]();
}
}}
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 [Link].*;
class Sol33
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,s=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
259 Arrays
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(i=0;i<5;i++)
{ s=0;
for(j=0;j<5;j++)
{
s+=a[i][j];
}
[Link](“Sum of row”+(i+1)+ “=” +s);
}
}}
34. Write a program to input numbers into a 5×5 integer matrix and find the sum of each column
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 column 1 = 17
Sum of column 2 = 22
Sum of column 3 = 30
Sum of column 4 = 28
Sum of column 5 = 17
Ans.
import [Link].*;
class Sol34
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,s=0;
{ s=0;
for(j=0;j<5;j++)
{
s+=a[j][i];
}
[Link](“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 [Link].*;
261 Arrays
class Sol35
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,f=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]%2!=0)
f=1;
}
}
if(f==0)
[Link](“All are even numbers”);
else
[Link](“All are not even numbers”);
}}
36. Write a program to input numbers into a 5×5 integer matrix and print the largest and the
smallest number among both the diagonals.
Ans. import [Link].*; class
Sol36
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,l=0,s=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
{ t=a[i][i];
263 Arrays
a[i][i]=a[j][j];
a[j][j]=t;
}
}
}
[Link](“Sorted Array:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
[Link](“\t”+a[i][j]);
}
[Link]();
}
}}
38. Write a program to input numbers into a 5×5 integer matrix and sort the minor diagonal
elements in ascending order.
Ans.
import [Link].*;
class Sol38
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,t;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i][4-i]<a[j][4-j])
{
t=a[i][4-i]; a[i][4-
i]=a[j][4-j]; a[j][4-j]=t;
265 Arrays
[Link](“\t”+a[i][j]);
}
[Link]();
}
}
}
39. Write a program to input numbers into a 5×5 integer matrix and sort elements of each row
in ascending order.
Ans.
import [Link].*;
class Sol39
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,t,r;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
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;
}
}
}
}
[Link](“Sorted Array:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
[Link](“\t”+a[i][j]);
}
[Link]();
}
}
}
40. Write a program to input numbers into a 5×5 integer matrix and sort elements of each column
in descending order.
Ans.
import [Link].*;
class Sol40
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,t,c;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(c=0;c<5;c++)
{
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i][c]<a[j][c])
{
t=a[i][c];
a[i][c]=a[j][c]; a[j]
[c]=t;
}
}
}
267 Arrays
}
[Link](“Sorted Array:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
[Link](“\t”+a[i][j]);
}
[Link]();
}
}
}
41. Write a program to input numbers into a 5×5 integer matrix and print the number having
maximum frequency.
Ans.
import [Link].*;
class Sol41
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,t,r,c,p,max=0,n=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
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];
}
}
}
[Link](“No. having maximum frquency=:”+n);
}
}
42. Write a program to input numbers into a 5×5 integer matrix and print the frequency of each
number.
Ans.
import [Link].*;
class Sol42
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,l=0,s=0,x,c;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
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];
269 Arrays
if(a[i][j]<s)
s=a[i][j];
}
}
}
for(x=s;x<=l;x++)
{ c=0;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
{
if(x==a[i][j])
c++;
}
}
if(c>0)
[Link](“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 [Link].*;
class Sol43
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,f=0,n;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
[Link](“Enter the number to search:”);
n=[Link]();
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]==n)
{
[Link](“Position present at i=”+i+ “j=”+j);
f=1;
}
}
}
if(f==0)
[Link](“Not Found”);
}
}
44. Write a program to input numbers into a 5×5 integer matrix and check whether it is a unit
matrix or not. Unit matrix is such a matrix whose major diagonal elements are 1 and the rest
are 0.
Ans. import [Link].*;
class Sol44
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,f=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
{
if(a[i][j]!=1)
f=1;
271 Arrays
}
else
{
if(a[i][j]!=0)
f=1;
}
}
}
if(f==0)
[Link](“Unit Matrix”);
else
[Link](“Not a Unit Matrix”);
}
}
273 Arrays
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:
275 Arrays
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,f=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(j>i)
{
if(a[i][j]!=0)
f=1;
}
else if(j<i)
{
if(a[i][j]==0)
f=1;
}
}
}
if(f==0)
[Link](“ Lower Triangular Matrix”);
else
[Link](“Not a Lower Triangular Matrix”);
}
}
49. Write a program to input numbers into two - 3×3 integer matrices and find their sum and store
it in the third matrix.
Ans.
import [Link].*;
class Sol49
{
static void main()
277 Arrays
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,f=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]!=0)
f=1;
}
}
if(f==0)
[Link](“Null Matrix”);
else
[Link](“Not a Null Matrix”);
}
}
51. Write a program to input numbers into a 5×5 integer matrix and check whether it is a scalar
matrix or not. Scalar matrix is such a matrix whose major diagonal elements are all same.
Ans.
import [Link].*;
class Sol51
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[][]=new int[5][5],i,j,f=0;
[Link](“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
{ roll
=r;
name=n;
}
void search(int r)
{ int
i,f=0;
for(i=0;i<[Link];i++)
{
279 Arrays
if (roll[i]==r)
{
[Link](“Name:”+name[i]);
f=1;
}
}
if(f==0)
[Link](“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 [Link].*;
class Sol53
{
static 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;
}
static void main(int a[][])
{
int i,j,f=0;
for(i=0;i<[Link];i++)
{
for(j=0;j<a[0].length;j++)
{
if(i+j==a[0].length-1)
{
if(isPrime(a[i][j])==false)
f=1;
281 Arrays
}
}
Write a program to read the data, calculate and display the following:
b. Print the roll number and average marks of the students whose average mark is above 80.
c. Print the roll number and average marks of the students whose average mark is below 40.
Ans.
import [Link].*;
class Sol55
{
static void main()
{
Scanner sc=new Scanner([Link]);
int roll[]=new int[50],i;
int m1[]=new int[50],m2[]=new int[50],m3[]=new int[50];
float av[]=new float[50];
[Link](“Enter the roll and marks:”);
for(i=0;i<50;i++)
{
roll[i]=[Link]();
m1[i]=[Link]();
m2[i]=[Link]();
m3[i]=[Link]();
av[i]=(float)(m1[i]+m2[i]+m3[i])/3;
}
[Link](“Average marks obtained by each student:”);
[Link](“Roll\t\tAverage”);
for(i=0;i<50;i++)
{
[Link](roll[i]+“\t\t”+av[i]);
}
[Link](“Average marks above 80 obtained by each student:”);
[Link](“Roll\t\tAverage”);
for(i=0;i<50;i++)
{
if(av[i]>80)
[Link](roll[i]+“\t\t”+av[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];
}
[Link](“Resultant Array:”);
for(i=0;i<10;i++)
{
[Link](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
283 Arrays
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 [Link].*;
class Sol57
{
static void main()
{
Scanner sc=new Scanner([Link]);
int a[]={1982,1987,1993,1996, 1999, 2003, 2006, 2007, 2009, 2010},l,u,n,m,f=0;
[Link](“Enter the year of
graduation:”); n=[Link](); l=0;u=[Link]-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)
[Link](“Record exists”);
else
[Link](“Record does not exist”);
}
}
58. Write a program to accept name and total marks of N number of students in two single
subscript array name[] and totalmarks[].
Calculate and print:
i. The average of the total marks obtained by N number of students.
ii. Deviation of each student’s total marks with the average.
[deviation=total marks of a student - average]
Ans.
import [Link].*;
class Sol58
285 Arrays
Answer as directed
1. Give the output of the following program fragment:
String s=new String(“He went to the market”);
String r; r=[Link](“went”,“is going”); [Link](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; [Link](s+a+b);
[Link](a+s+b);
[Link](a+b+s); Ans.
Output:
String1245
12String45
57String
3. Give the output of the following program fragment:
String s=“india”,s1=“IndIA”,s2=s;
[Link]([Link](s1));
[Link]([Link](s1));
[Link](s2==s);
[Link]([Link]()==[Link]());
[Link]([Link](“IN”.toLowerCase()));
[Link]([Link](“iA”.toUpperCase())); Ans.
Output: false true true false true true
4. What do the following functions return for:
String x =“hello”;
String y =“world”
[Link](x + y);
[Link]([Link]();
[Link]([Link](3));
[Link]([Link](y)); Ans.
Output: helloworld 5
l
false
5. What is the output of the following:
3. Write a program to input a sentence and count the number of vowels in it.
Ans. import [Link].*; class Sol3
{
static void main()
{
Scanner sc=new Scanner([Link]);
String s;
int i,c=0;
[Link](“Enter a sentence:”);
s=[Link](); s=[Link]();
for(i=0;i<[Link]();i++)
{
char x=[Link](i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’) c++;
}
[Link](“No. of vowels:”+c);
}
}
4. Write a method to accept a word and print it in the following way:
Parameter-> TRIAL
Output-> L
AL
IAL
RIAL
TRIAL
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 [Link].*; class
Sol16
{ static void main()
{
Scanner sc=new Scanner([Link]);
String s[]=new String[50]; int i,c=0,j;
[Link](“Enter 50 names:”);
for(i=0;i<50;i++) s[i]=[Link]();
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;
}
}
}
[Link](“No. of words :”+c);
}
}
{ w+=x;
if([Link](x))
c++;
}
else {
if(w!=“ ”)
p++;
w=“ ”;
}
}
[Link](“The total number of words :”+p);
[Link](“The number of alphabets in the given text. :”+c);
}}
18. 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.
for(i=0;i<[Link]()-1;i++)
{
if((char)([Link](i)+1)== [Link](i+1))
c++; }
[Link](“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 [Link].*;
class Sol19
{
static void main()
{
Scanner sc=new Scanner([Link]);
String s,n;
int i;
[Link](“Enter a word:”);
s=[Link]().toUpperCase();
for(i=0;i<[Link]();i++)
{
char x=[Link](i);
if(x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
break;
}
Question 1
(a) Differentiate between class variable and instance variable.
(b) Mention two difference between Binary search and Linear search.
(c) Define wrapper class.
{ t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
for(i=0;i<[Link];i++)
[Link](a[i]+“ ”);
}
}
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
101
110
111
Ans. class Q7
{
static void display(int n)
{ int i,j,s=0,c; for(i=1;i<=n;i++)
{ c=0; for(j=0;j<=i;j++)
{ if (i%j==0) c++;
} if(c==2) s+=i;
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
*******************************
Ans.
(a) import [Link].*; class Q9a
{
static void main()
{
Scanner sc=new Scanner([Link]); int n,i,p,m=2,c=3,v=1,j,b=0; double
s=0;
[Link](“Enter the no. of terms:”); n=[Link](); for(i=1;i<=n;i++)
{ p=1; for(j=1;j<=m;j++) p=p*j; m=m+c;
c=c+2; if(b%3==0) s=s+(double)v/p; else s=s-
(double)v/p; v=2*v;b++;
}
[Link](“Sum=”+s);
}
}
}
}
(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.
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.
(b) Write the output of the following:
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.
Ans.
import [Link].*;
class Q5
void display()
{
[Link](“EMPLOYEE No.\t\tNAME\t\tGROSS SALARY\t\tPF”);
[Link](Emp_No+“\t\t”+Name+“\t\t”+gross+“\t\t”+PF);
}
} else
[Link](“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 [Link].*; class Q8
{
static long fact(long k)
{
long i,f=1; for(i=1;i<=k;i++)
k=k*i;
return k;
}
{ case
1:
[Link](“Enter the no. of terms:”);
n=[Link]();
for(i=1;i<=n;i++)
[Link](“Sum=”+s);
break; case 2:
[Link](“Enter the value of n:”);
n=[Link]();
for(i=1,j=n;i<=n;i++,j--)
{
b=b+i*j;
}
[Link](“Sum=”+b);
break; default:
[Link](“Invalid choice”);
}
}
}
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 [Link].*;
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.
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”;
[Link]([Link](0,8).concat([Link](9)));
[Link]([Link](“e”)); (d)
Write the output of the following:
(i) [Link]([Link](‘R’));
(ii) [Link]([Link](‘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;
}
[Link](p);
(b) What will be the output of the following code?
(i) int k=5, j=9; k+ = k++ - ++j + k;
[Link](“k=”+k);
[Link](“j=”+j);
(ii) double b=-15.6;
double a=[Link]([Link](b));
[Link](“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.
(ii) distinguishes between instance variables and class variables.
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 [Link].*;
class mobike
{
int bno,phno,days,charge;
String name;
void input()
{
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 [Link].*;
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 [Link].*;
class Q6
{ static int fact(int
k)
{ int i,f=1;
for(i=1;i<=k;i++)
k=k*i; return k;
}
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 [Link].*;
class Q7
{ static void
main()
{ int
i;
String w,n=“ ”;
Scanner sc=new
Scanner([Link]);
[Link](“Enter a word:”);
w=[Link]();
w=[Link]();
for(i=0;i<[Link]();i++)
{
char x=[Link](i); if(x==‘a’ || x==‘e’ || x==‘i’ || x==‘o’ || x==‘u’)
n=n+(char)(x+1); else n=n+x;
}
[Link](“New word:”+n);
}
}
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 [Link].*; class Q9
{
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…
Ans.
import [Link].*;
class Q5
{
static void main()
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 [Link].*;
class Q6
{
void calc()
{
Scanner sc=new
Scanner([Link]); int units;
double charge;
[Link](“Enter the no. of
units:”); units=[Link]();
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; [Link](“Charge:”+charge);
}
public static void main(String args[])
{
Q7 ob=new Q7();
[Link]();
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=[Link]();
s2=[Link]();
for(i=0;i<[Link]();i++)
{
char x=[Link](i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
c1++;
}
for(i=0;i<[Link]();i++)
{
char x=[Link](i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
c2++;
}
if(c1>c2)
[Link](s1);
else
[Link](s2);
}
void prStr(String s, char ch)
{
s=[Link](‘ ’, ch);
[Link](s);
}
void prStr(String s)
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 [Link].*;
class Q9
{
{ case
1:
[Link](“Enter 10 strings:”);
for(i=0;i<10;i++)
{
w[i]=[Link]();
(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;
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:
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]
{ case 1:
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
for(i=n;i>0;i/=10)
{ d=i%10;
r=r*10+d;
}
if(r==n && c==2)
[Link](“Pal-prime”);
else
[Link](“Not Pal-prime”);
break; case 2:
for(i=n;i>0;i/=10)
{ d=i%10;
r=r+d*d*d;
}
if(r==n)
[Link](“Armstrong”);
else
[Link](“Not Armstrong”);
default:
Question 9
Write a program to input a word in uppercase and rearrange the characters of the word in
alphabetical order.
Ans.
import [Link].*; class
Q9
{
static void main()
{
String w,n=“ ”; char x;
int i;
Scanner sc=new Scanner([Link]); [Link](“Enter a word:”); w=[Link]();
w=[Link]();
for(x=‘A’;x<=‘Z’;x++)
{
for(i=0;i<[Link]();i++)
{
if([Link](i)==x) n+=x;
}
}
[Link](n);
}
}