You are on page 1of 86

[JLS0.

1] Sum of two numbers

Given two integers N1 and N2, find their sum and store in R.

The code to read N1 and N2 as well as to print R has already been provided.

[JLS0.2] Subtraction of a number from another

[JLS0.3] Division of a number by another

Given two integers N1 and N2, divide the former by the latter and store the result in float type
number R.

The code to read N1 and N2 as well as to print R has already been provided.

Input

50

Output

10.00

Note: The output has been truncated to two decimal places.

[JLS0.4] Maximum Marks


An Engineering student has to secure P% marks for a pass. He gets T marks and fails by N marks. Write a
program to find the maximum marks.
Sol. P=45, T=153, N=27
Passing marks = 153 + 27 = 180
If passing mark is at 45, total marks must be 100. Since 180 is the passing mark, max.marks =

marks.

Test Case 1:
Input:
45
153
27
Output:
400.0
Test Case 2:
Input:
50
175
35
Output:
420.0

Lab 1
[JLS1.2] Product of two numbers

Given two integers N1 and N2, find their product and store it as integer R.

Input

10

Output

50

[JLS1.3] Divide the former number by the latter number

Given two integers N1 and N2, divide the former by the latter and store the result in float type
number R.

Input

50

Output

10.00

Note: The output has been truncated to two decimal places.


[JLS1.4] Remainder of a number by another
Given two integers N1 and N2, divide the former by the latter and find the remainder.
Input:
43
5
Output
3

[JLS1.5] Difference of two Number

Given two integers N1 and N2, find out the absolute difference of these number and store the result
in R.
Input
10
20

Output
10

[JLS1.6] Multiplication of two numbers using bitwise operator


Given an integer N as input, write a program to multiply N by 2 using bitwise operator.

Input:
10

Output:
20

[JLS1.7] Equality of two numbers

Given 2 integers as input, check whether they are equal or not. Display "Yes" if they are equal
otherwise "No".

Input:

12

67

where:

• First line represents first number.


• Second line represents second number.

Output:

No

Explanation:

• The input numbers are not equal, hence the output "No".

[JLS1.8] Sum of first N number

Given a number N, display the sum of the first N numbers.

Input:
10
where:
First line represents number N.

Output:
55

[JLS1.9] Position of first 1 bit from right

Given a number N, Write a program to display position of first 1 from right to left, in a binary
representation of an Integer.

Input:
48
where:
First line represents input number N

Output:
5
Here, the binary representation of 48 is 110000 and 1st one in the representation is at 5th position
from the right.

Data Types and Conversions (Lab 2)


[JLS2.1] Java Primitive Datatypes
Write a program to demonstrate following datatypes available in Java:
a) Boolean
b) byte
c) int
d) float
e) char
f) string
Input: (Boolean, byte, int, float, char, string)
Output:
Boolean: true
byte: 124
int: -4250000
float: 42.3
char: c
String: Java Programming

[JLS2.2] To convert int to char


Program to show the demo of conversion from int to char. Take two integers and print the
respective character for them.

Input: (N1, N2)


65
97
Output:
A
a

[JLS2.3] Convert int to char by adding integer.


Write a program to convert a given character to a new character by adding an integer (0-9)

Input
5

Output:

Input

Output:

[JLS2.4] Convert char to int


Write a program to take character from user and convert it to int.
Input:
A
Output:
65
Input:
?
Output:
63

[JLS2.5] Convert string to int using parseint method


Write a program to demonstrate the usage of parseInt() method to convert string to int.
Input: (String)
67
Output:
67
[JLS2.6] Concatenation of strings

Write a program to concatenate two strings by adding space in between the strings.

Input: (String1, String 2)


Bennett
University

Output:
Bennett University

[JLS2.7] Float to int conversion


Write a program to convert a float number to integer.
Input: (Float)
3.66
Output:
converting float to int
Float value: 3.66
Int value: 3
Input:
-11
Output:
converting float to int
Float value: -11.0
Int value: -11

[JLS2.8] Convert Float to Int using round method

Write a program to convert float to int using built-in round function.


Input: (Float)
3.99

Output:
converting float to int
Float value: 3.99
Round value: 4

Input:
-9.1

Output:
converting float to int
Float value: -9.1
Round value: -9

[JLS2.9] Convert int to double type

Write a program to convert int to float.

Input:
9
Output:
9.0

Input:
-9
Output:
-9.0

[JLS2.10] Temperature Conversion

Write a program to convert Fahrenheit to Celsius by using the following formula:

celsius =(( 5 *(fahrenheit - 32.0)) / 9.0)

Input: (Temperature in Fahrenheit)


212
Output:
212.0 degree Fahrenheit is equal to 100.0 in Celsius

Input:
100.3
Output:
100.3 degree Fahrenheit is equal to 37.94444444444444 in Celsius

Week 2
Lab 3
Data Types and Conversions

[JLS3.1] Byte Datatype


Write a program to show the usage of byte datatype in Java. Take a byte input and increment
it three times (one by one) to demonstrate the range of byte.

Note: Byte, can hold whole number between -128 and 127.

Input: (Byte)
126
Output:
126
127
-128
-127

Input:
-11
Output:
-11
-10
-9
-8
[JLS3.2] Widening Typecasting.
Convert an integer to double without using typecast operator.
Input:(integer)
9
Output:
9.0

Input:
-9
Output:
-9.0

[JLS3.3] Narrowing Typecasting.


Convert double to int by using typecast operator.

Input:
19.87
Output:
19

[JLS3.3] Typecasting 1.
Write a program that takes two integers as input and store their submission in float type (use
wide Typecasting)

Input:
12
10
Output:
22.0

[JLS3.4] Typecasting 2.
Write a program that takes two floats as input and store their submission in int type (use
narrow Typecasting)

Input:
12.0
1.2
Output:
13

[JLS3.5] Typecasting 3.
Write a program that calculate the simple interest (SI) and final amount (FA) for the given
principal, rate and time (float values). Take care that simple interest cannot have decimal
values.

SI=(P*R*T)/100
FA= SI +P

Input: (P,R,T)
100.2
3
2.5
Output: (SI, FA)
7
107.2

[JLS3.6] char-int-float-double
Write a program to take character from user and convert it to int. Add a float number to the
int obtained and print the result in double datatype.

Input: (char, float)


A
2.3
Output:
int value: 65
int + float: 67.30000305175781

[JLS3.7] char+char
Add two characters and convert their submission to int.

Input:
a
b
Output:
195

Lab 4
1. [JLS4.1]: Write a program to find a number whose 30% is N. Truncate output after decimal
places to one, if any.
Sol. Let x be the number whose 30% is 150 (Assume N=150)

Test Case 1:
Input: 150
Output: 500.0

Test Case 2:
Input: 300
Output: 1000.0

Test Case 3:
Input: 450
Output: 1500.0

2. [JLS4.2]: Consider a circle with radius r. Write a program that compute difference between the new
perimeter and old perimeter if its radius is tripled. Truncate the output 2 decimal places.

Solution:
Let ‘r’ be the radius of the circle.
Circumference = 2πr
When radius is tripled, radius = 3r.
New Circumference = 2 ×π× 3r = 3 × 2πr = 3 times its previous Circumference.
Difference = 3x2πr – 2πr

Test Case 1:
Input: 5
Output: 62.80

Test Case 2:
Input: 8
Output: 100.48

3. [JLS4.3]: Write a program to convert temperature from Celsius to Fahrenheit, and Fahrenheit to
kelvin, Truncate output after decimal places to two, if any.
Input
100
Output
212.0
373.15
Sol. Relation between Celsius, Fahrenheit, kelvin
C/5 = (F-32)/9 = (K+273)/5

4. [JLS4.4]: Shatabdi train travels 120 km/hr. Write a program that computes the meters travel by this train
in n minutes. where n is the input from the user. Truncate output after decimal places to one, if any.

Sol:

Distance travelled in 1 hour i.e. 60 minutes = 18 km

= 18×1000 metres.

∴ Distance travelled in 12 minutes =

= 3600 metres.

Test case:

Sample Input:

12

Sample Output:

Meters travelled: 24000.0

5. [JLS4.5]: Anand gets R% more marks than Arun. Write a program to find out the % of marks does Arun
get less than Anand? Truncate after decimal places to two, if any.

Sol.

Let us assume, Arun gets 100 marks. Anand gets 115 marks

In comparison to Anand, the % of marks Arun gets less than Anand

Test case:

Sample Input:
15
Sample Output:
13.04
6. [JLS4.6]: Pluto wheel rotates N times each minute. Write a program that calculate degrees will it rotate
in 12 seconds of time. Where N is input from the user. Truncate after decimal places to one, if any.

Sol:

In 12 seconds or of a minute, the wheel rotates or 3 times. Angle through which it turns = 3 ×
360

= 1080

Test case:

Sample Input:

15

Sample Output:

1080

7. [JLS4.7]: If a shopkeeper sells an item for Rs.141, he loses 6%. Write a program that compute the price
he should sellin order to gain 10%, Truncate after decimal places to one, if any.
S.P = Rs.141

Loss = 6%

C.P =

Now, C.P = 150

P-profit = 10%

S.P =

He should sell the item for Rs.165 in order to get a profit of 10%
Test case1
Input
141
6
10
Ouput
165.0
Test case2
Input
141
6
20
Ouput

180.0

8. [JLS4.8]: A right-angle triangle is given with height A, base B and Hypotenuse C. Write a
program to compute its area and circumference. Truncate after decimal places to one, if any.
Input
4
3
5
Output
6.0
12

Solution:
Perimeter = A+B+C

Area = AB

9. [JLS4.9]: Mr. A buys an article for Rs.350 and sells to Rs.420, write a program to find his percentage
profit. Truncate after decimal places to one, if any.

C.P = Rs.350

S.P = Rs.420

Profit on C.P = 420 – 350 = 70

%profit on C.P =

Test case:

Sample Input:

C.P = Rs.350

S.P = Rs.420

Sample Output:

20.0

10. [JLS4.10]: If 12 man can do a piece of work in 36 days. Write a program that calculate the number of
days require by 18 men to do the same work. Truncate after decimal places to one, if any.

Solution:
12 men can do a work in 36 days.

18 men can do the work in = 24 days.

Note:

If the number of men is increased, the number of days to finish the work will
decrease.

Test Case 1:
Input:
12
36
18
Output:
24.0

Test Case 2:
Input:
15
30
20
Output:
22.5

Lab 5
1. [JLS5.1] The price of paint is Rs.100 per kg. A kilogram of paint covers 25sq.m. Write a program that
calculate the cost to paint the inner walls and the ceiling of a room having 6 meters each side.

Solution:

Area to be painted = Area of the 4 walls + area of the ceiling

=4a2 +a2 where a = 6m.

=5×6×6 = 180m2

Cost of painting = rupees.

= = Rs.720

Test Case 1:
Input:
100
25
6
Output:
720

Test Case 2:
Input:
150
30
8
Output:
1600.0

2. [JLS5.2] The radii of two concentric circles are 8cm and 10cm. Write a program that find the area of the
region between them.

Solution:

Given, R= 10cm, and r = 8cm.

Area between the two circles = outer area – Inner area= =π(R2-r2)= =

= 18π× 2 = 36 ,

where π = 3.14 approx

Test Case 1:
Input:
10
8
Output:
113.04

Test Case 2:
Input:
15
10
Output:
392.5

3. [JLS5.3] Abhirup basic monthly salary is input through the keyboard. His dearness allowance is
40% of basic salary, and house rent allowance is 20% of basic salary. But due to the prevailing
situation of the Covid-19, there is a salary deduction of 25%. Write a program to calculate his
annual gross salary.

Test Case 1
Sample input:
100000
Sample output:
annual salary is: 1440000.0
Test Case 2
Sample input:
20000
Sample output:
annual salary is: 288000.0

4. [JLS5.4] Abraham wants to visit his collage with his grandfather regarding admission. His
grandfather asks him the distance from his hometown to collage. So he replied in
Kilometers but his grandfather asks the distance in Miles as he is not much familiar with
Kilometers. Abraham does not know how to convert Kilometers to Miles. Therefore, WAP
in Python to help Abraham.

Test Case 1:
Input:
7.5
Output:
4.66

Test Case 2:
Input:
3.5
Output: 2.17

5. [JLS5.5] Write a python program which allows users to enter five different marks for five
subjects: English, Math, Computer, Physics, and Chemistry. Next, Program finds the
Total, average, and Percentage of those five Subjects. For this python program, you are
using the Arithmetic Operators to perform arithmetic operations.

Test Case 1:
Input:
98
48
69
87
65
Output:
Total Marks = 367.00
Average Marks = 73.40
Marks Percentage = 73.40

Test Case 2:
Input:
76
98
79
89
67
Output:
Total Marks = 409.00
Average Marks = 81.80
Marks Percentage = 81.80

6. [JLS5.6] Write a program that calculate the number mangoes he would purchases for Rs.50 to get a profit
of 60%, Truncate output after decimal places to one, if any.

Sol.

S.P of 10 mangoes = Rs.50

Profit % = 60%

C.P of 10 mangoes =

For Rs.31.25, he bought 10 mangoes

For 50 rupees he bought = 16 mangoes

He would have bought 16 mangoes for 50 rupees and sold at 10 mangoes for Rs.50 to earn a
profit of 60%

Test Case:1
Input:
50
10
60
Output:16.0

Test Case:2
Input:
100
20
60
Output:32.0

7. [JLS5.7] The simple interest on a loan is calculated by the formula Interest = principal
amount * rate * year / 100; the preceding formula assumes that rate is the annual interest
rate. Develop a program that will input principal amount, rate and years for several loans,
and will calculate and display the simple interest for each loan, using the preceding
formula. Truncate output after decimal places to one, if any.

Test Case 1:
Input:
2000
4.5
3
Output:
270.0

Test Case 2:
Input:
195000
8.0
5
Output:
78000.0

8. [JLS5.8] John son came to him and ask for help in science homework. His son science
teacher gives the homework to prepare an equivalence temperature table which contains
temperature in Celsius and Fahrenheit. Therefore, John asks you to help in conversion
of temperatures from Celsius to Fahrenheit, So Write a program to convert temperatures
from Celsius to Fahrenheit. Truncate output after decimal places to one, if any.
Note: C/5 = (F-32)/9, where C = Celsius and F = Fahrenheit

Test Case 1:
Input:
37
Output:
98.6

Test Case 2:
Input:
78
Output:
172.4

Week 3
Lab 6
[JLS6.1] Write a program in Java that inputs data (class, age, marks in mathematics, science) about
two persons- Ram and Shyam. The program uses relational operators to check whether they study in
same class? Is Ram younger to Shyam? Is Ram’s marks in mathematics more than Shyam? Is Ram’s
marks in science less than Ram? The answer by the program is either True or False. The operators to
be used are: <, >, ==.

Sample input:
R_class=12
S_class=12
R_age=18
S_age=19
R_math=80
S_math=90
R_sci=85
S_sci=92

Sample Output:
Both are in same class ?true
Both are of different age ?true
Ram score more than Shyam in Math ?false
Ram score less than Shyam in Science ?true
Ram score more or equal than Shyam in Math ?false

[JLS6.2] Chulbul pandey is numerologer i.e. belief in relationship between numbers. He decides to
purchase the car and will decide the registration number by calculating the sum of the digits (four digit
rto number), If the sum is greater than 12 than only he says yes. Write a java program to implement the
logic.

Test Case1
Sample input:
3454

sample output:
Chulbul agree for the number? True

Test Case2
Sample input:
1234

sample output:
Chulbul agree for the number? False

[JLS6.3] Write a program to read a positive integer X and verify whether:


(1) X is divisible by 2.
(2) X is divisible by 3.
(3) X is lesser than 50.
(4) X is not equal to 51.

Sample Input:
42
Sample Output:
Is X divided by 2: False
Is X divided by 3: False
Is X lesser than 50: True
Is x not equal to 51: True

[JLS6.4] Iron man and Hawkeye are good friends. While Captain America and winter soldiers are
good friends. Take the input of net income of all four and Verify
1. "Is ironman +hawkeye < Captainamerica+wintersoldier ?"
2. "Is ironman +hawkeye = Captainamerica+wintersoldier ?"
3. "Is ironman +hawkeye > Captainamerica+wintersoldier ?"

Test case 1
Sample Input:
Ironman: 56
Hawkeye: 45
captainamerica: 23
wintersoldier: 45

Sample Output:

Is I+H < C+W ? False


Is I+H = C+W ? False
Is I+H > C+W ? True

[JLS6.5] Dhoni is fond of playing but his father is not. He asked his father whether he can go to play
after school. His father said “yes or no” based on whether dhoni completed his homework and took
lunch. Now, add a program to take input of the task completed and output his father’s decision.

Conditions:
1. Dhoni completed his home work: y/n
or
2. Dhoni cleaned his room:y/n
and
3. Dhoni had lunch: y/n

Test case 1

Sample input:
Y
n
y
Sample output:
true

Test case 2
Sample input:
y
n
n
Sample output:
false

[JLS6.6]
Modi wants to go to the Himalayas for meditation. He asked his mother. The mother says ‘yes’ based
on three conditions.
1. Only when Modi's father says Yes
or
2. When Modi is at least 18 years old
and
3. Modi is not married.

Test Case 1
Sample Input:

Father says: y
Age: 17
Married: 0
Sample Output:
True

Test Case 2
Sample Input:

Father says: n
Age: 21
Married: 1
Sample Output:
False

Test Case 3
Sample Input:

Father says: n
Age: 17
Married: 0
Sample Output:
False

[JLS6.7] Your five friends group wants to go for the hackathon quiz. They can go if their percentage
on avg. is greater than 75 and they have a letter of invitation from the organizers or permission letter
from HOD. You are asked to get the percentage of 5 of your friends. Now your task is to design a
program that figures out the average percentage of all of your friends and check whether they can
participate in the hackathon quiz or not.

Three conditions:
1. Only when their avg. % is greater than 75
and
2. They have permission from HOD
or
3. Letter of invitation

Test case1

Sample Input:
70
80
95
85
98
HOD permission: y
Invitation: n

Sample Output:
True

Test case2

Sample Input:
67
80
65
74
73
HOD permission: y
Invitation: n

Sample Output:
False

Test case3

Sample Input:
70
80
95
85
98
HOD permission: n
Invitation: y

Sample Output:
True

[JLS6.8] Write a program to read a positive integer X and verify whether:


(1) X is divisible by 2 or 3.
(2) X is divisible by 5 and 10.

Sample Input:
42
Sample Output:
Is X divisible by 2 or 3: True
Is X divisible by 5 and 10: False

[JLS6.9] Given two integers N1 and N2 as input, find whether they are equal or not using
bitwise operator.
Input:
5
5
where:
• First line represents the integer N1.
• Second line represents the integer N2.
Output:
Yes
Assumption:
• Value of N1 and N2 can be in the range -10000 to 10000.

[JLS6.10]
Multiply a given number by 2 without using * multiplication operator.

Sample Input:
24
Sample output:
48

Lab 7
[JLS7.1] Even Odd
Given an integer N, determine whether N is even or odd. Display “Even” if N is even or “Odd”
otherwise.

Input:
15
Output:
0

[JLS7.2] Maximum of three numbers

Given three integers N1, N2 & N3, find the largest number.

Input: (N1, N2 , N3)


4
5
6

Output:
6 is the maximum number.

Input: (N1, N2 , N3)


1
1
1

Output:
1 is the maximum number.

[JLS7.3] Blood Donation!


Given is the age and weight of a person as an input, Determine whether the person is eligible
for donating blood or not. Display "Yes" if the person is eligible otherwise display "No".
A person is said to be eligible to donate blood only if,
Age > = 17 years and,
Hemoglobin > = 10.

Input:
18
12

Output:
Yes

[JLS7.4] Simple Interest..not so simple.


Given Principal Amount P, Rate of Interest per year R and Number of Years T. Calculate
simple interest. The simple interest is only calculated if all the assumption are satisfied else
print invalid input.
Assume that,
P is an integer within the range [ 100 to 10000].
R is a double within the range [ 1 to 1000 ].
T is an integer within the range [ 1 to 10 ].

Simple interest = ( Principle amount * Rate of Interest * Number of Years ) / 100

Input:
5000
5
5

Output:
1250.000

Input:
50000
-3
8

Output:
Invalid input

[JLS7.5] Dog’s Age


As we know that dog’s life is much lower than human life. Suppose your friend wants to
estimate Dog’s life equivalence to dog's years. So write a program to estimate a dog's age
in dog's years.
Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog
year equals 4 human years.

Test Case 1:
Input:
15
Output:
73

Test Case 2:
Input:
2
Output:
21

Test Case 3:
Input:
-15
Output:
This cannot be true!

Test Case 4:
Input:
0
Output:
This corresponds to 0 human years!

[JLS7.6] Quadrant System.


Write a program to demonstrate that the given points x,y (Integer) lies in which quadrant?
print '1st quadrant ', if point is in 1st quadrant.
print '2nd quadrant ', if point is in 2nd quadrant.
print '3rd quadrant ', if point is in 3rd quadrant.
print '4th quadrant ', if point is in 4th quadrant.
Else print “Origin”.

Input: (x,y)
-12
4
Output:
2nd quadrant

Input: (x,y)
0
0
Output:
Origin

[JLS7.7] Electricity Bill

Andhra Pradesh Power Corporation Limited supplies electricity to peoples of Utter Pradesh.
They have four ranges of charges for all the residential connections. The charges per unit with
surcharge for different ranges of consumptions are given as follows.

Write a program using if else to calculate the bill (upto 2 decimal places) for a user based on
no. of unit consumed (float).

Test Case 1:

Input:

243

Output:

Electricity Bill = 1256.85

Test Case 2:

Input:

487

Output:

Electricity Bill = 3318.65

[JLS7.8] Tourist Attraction:

Ravi’s friend Mark planned a tour to North India. He asked Ravi for the tourist places in
different cities of India. Ravi being a computer Engineer, made a program which can help Mark
in this. He asked Mark to input the name of the city and then the programs lists the Tourists
attractions in that city. If Mark names a wrong city, then by default the “Taj Mahal” the most
visited places is shown.
Cities and Tourist Attraction are as follows:

Delhi: India Gate, Lal Kila, Humayun's Tomb, Qutab Minar, Red Fort

Agra: Taj Mahal, Agra Fort, Fatehpur Sikri

Lucknow: Bara Imambara, British Residency, Rumi Darwaza,

Amritsar: Golden Temple, Company Bagh, Jallianwala Bagh

Default Case: Taj Mahal.

Input: (Place)
Amritsar

Output:

Golden Temple

Company Bagh

Jallianwala Bagh

Input:
Any place

Output:
Taj Mahal

[JLS7.9] Days in a month

In a school, a teacher finds an interesting way to make the students learn the number of days in
a month. She ask the students to press a number between 1-12 and then display a playcard with
that number on which, month, month name and no. of days is written. Being a computer
engineer, write a program to help the teacher to automate rather than writing it on playcards!

If the student chooses a wrong number than the playcard displays "invalid Month".

Input: (Month value)

12

Output:
12 - December- 31 Days

Input:

13

Output:

Invalid Month!

[JLS7.10] My Calc !

A mini project is assigned to students where they have to develop their own calculator that
performs “ +,-,* and /” operations. The user is asked to input the choice of operator and then
the two numbers (double) n1 and n2 respectively. As per the choice input the result is displayed.
For wrong choice, the calculator displays “Invalid operator !”.

Input: (operator, n1,n2)


+
20
30

Output:
20.0+30.0 = 50.0

Input:
T
2
3

Output:
Invalid operator!

Week 4
Lab 8
Lab01:31. Print natural numbers in reverse: Given a number N, print natural numbers in reverse
from N to 1.
Input:
10
where:
First line represents value of N.
Lab01:32. Arithmetic Progression (A.P.): Given three integers N1 and N2 and N3, find the sum of
an Arithmetic Progression ( A.P. ).
Input:
1
5
3
where:
First line represents the value of N1, which is the first number of A.P.
Second line represents the value of N2 which is total numbers in the A.P.
Third line represents the value of N3 which is a common difference of the A.P.
Output:
35
Explanation: An A.P. is a sequence of numbers, where the difference between the consecutive
terms is constant.
Here N1 represents the start point, N2 is the number of elements in A.P. and N3 represents
the common difference between consecutive terms.
Factors: Given numbers N, find all factors of it.
Input:
12
where:
First line represents value of N.
Output:
1 2 3 4 6 12
Assumptions:
N can be in the range 1 to 100000.

Lab01:34. Perfect Squares Between Two Integers: Given two numbers representing a range of
integers, count the number of perfect squares that exist between them, the two integers inclusive.
Input
4
17
Output
3

Lab01:35. Automorphic Number: Given an integer, check whether it is automorphic or not.


Automorphic number: An automorphic number is a number which is contained in the last
digit(s) of its square. e.g. 25 is an automorphic number as its square is 625 and 25 presents as
the last two digits. 5, 6 and 75 are also automorphic.
Display true if the number is automorphic otherwise false.
Input
25
Output
True
Assume that,
The integer ranges from [0 to 2,147,483,647].

Lab01:36. Convert an octal number into binary: Given an octal number N, convert it into a binary
number.
Input:
57
where: First line represents an octal number N.
Output:
101111

Lab01:37. Display Fibonacci Series: The Fibonacci series is a series where the next term is the sum
of pervious two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.
Input : 10
Output:
The Fibonacci sequence: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34+

Lab01:38. Armstrong Number: Given an integer N, find whether it is Armstrong number or not.
Display 1 if it is an Armstrong number else 0.
Input:
153
where:
First line represents input number N.
Output:
1
Explanation: For 153 number of digits are 3. Sum of digits raises to the power total number of digits =
13 + 53 + 33 = 153, which is equal to an original number and hence 153 is an Armstrong number.

Lab01:39. Number Pattern -Alternate 1 and 0 in columns: Given two integers N1 and N2, display
the number pattern of 1's and 0's at alternate columns.
Input:
4
5
where:
First line represents the value of N1( number of rows ).
Second line represents the value of N2( number of columns ).
Output:
01010
01010
01010
01010

Lab01:40. Hollow Rectangle star pattern: Given an integer N1 and N2, print Rectangle Star pattern
as described in output.
Input:
6
4
Where:

• First line represents the value of N1.


• Second line represents the value of N2.
Output:
****
* *
* *
* *
* *
****
Assumptions:

• N1 can be in the range 1 to 1000.


• N2 can be in the range 1 to 1000.
Program Solution:

Lab 9

Lab01:41. Positive even numbers: Given an integer N, print positive even numbers up to N using
while statement.
Input
19
Output
2 4 6 8 10 12 14 16 18
Where, There must be a single space between consecutive numbers.
There should be no spaces before the first number and after the last number.
Program Solution:

Lab01:42. Factorial of a number: Given a positive integer, find factorial of it(Use for loop).
Input:
5
Output:
120
For N = 5, factorial of 5 (5!) = 5 * 4 * 3 * 2 * 1 = 120
Assume that, Value of N can be in the range from [0 to 20]

Program Solution:

Lab01:43. Positive even numbers: Given an integer N, print positive even numbers up to N using
while statement.
Input
19
Output
2 4 6 8 10 12 14 16 18
Where, There must be a single space between consecutive numbers.
There should be no spaces before the first number and after the last number.

Program Solution:
Lab01:44. Consecutive alphabets: Given a character C, print all the alphabets up to and including
the given character.
Input
d
Output
abcd
Where,
There must be a single space between consecutive alphabets.
There should be no spaces after the last alphabet.
Assume that,
C is a character within the range [{'a'...'z'}, {'A'...'Z'} ].
Alphabet(s) in input & output are case-sensitive.
Program Solution:

Lab01:45. Squares of numbers: Display the squares of numbers in specified range: Given an
integer N, display the square all the numbers from 1 to N numbers.
Input:
5
where: First line represents value of N.
Output:
1 4 9 16 25
Assumptions: N can be in the range 1 to 600.

Lab01:46. Display the ascii values of alphabets in Hexadecimal format: Display the ASCII values
of all upper and lower case alphabets in Hexadecimal.
Output:
41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A
61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A
where
First line represents all upper case alphabets.
Second line represents all lower case alphabets.

Lab01:47. Least Common Multiple (LCM) and HCF of two numbers: Given two integers N1 and
N2, find the LCM and HCF of those numbers.
Input
30
50
Output
LCM is 150
HCF is 10

Lab01:48. Dudeney Numbers: Given an integer n, the task is to check if n is a Dudeney number or
not. A Dudeney number is a positive integer that is a perfect cube such that the sum of its decimal
digits is equal to the cube root of the number
Input:
N = 19683
Output:
Yes
Explanation:
19683 = 273 and 1 + 9 + 6 + 8 + 3 = 27

Lab01:49. Rectangle Star pattern: Given two integers N1 and N2, display the Rectangle Star
pattern as described in output.
Input:
5
3
Where:
• First line represents the value of N1( number of rows ).
• Second line represents the value of N2( number of columns ).
Output:
***
***
***
***
***
***

Lab01:50. Number Pattern - Diamond number pattern – 1: Given an integer N, print number
pattern as described in output.
Input:
5
where:
First line represents the rows input N.
Output:
1
12
123
1234
12345
1234
123
12
1
Assumptions:
N can be in the range 1 to 1000

Lab 10

Lab02:31. Disarium Number: Given an integer N, find whether N is a Disarium or not. Display 1 if
N is Disarium number else 0.
In Disarium Number, sum of digits powered with their respective position is equal to an original
number.
Input
135
Output
1
For 135, sum of digits powered with their respective position = 11 + 32 + 53 = 135, which is equal to an
original number.

Lab02: 32. Count total number of ones in a binary number: Given an integer N as input, find the
total number of 1's in the binary equivalent of N.
Input:
5
where:
First line represents the value of integer N.
Output:
2

Lab02:33. Rhombus star pattern: Given an integer N, display the Rhombus Star pattern as
described in output.
Input:
5
where:

• First line represents the value of N( number of rows ).


Output:
*****
*****
*****
*****
*****

Lab02:34. Hollow Mirrored Parallelogram star pattern: Given two integers N1 and N2, display
the Hollow Mirrored Parallelogram star pattern as described in output.
Input:
5
4
where:

• First line represents the value of N1( number of rows ).


• Second line represents the value of N2( number of columns ).
Output:
****
* *
* *
* *
****

Lab02:35. Mirrored Hollow Right triangle star pattern: Given an integer N, display the hollow
mirrored right triangle star pattern as described in output.
Input:
5
where:

• First line represents the value of N( number of rows ).


Output:
*
**
* *
* *
*****

Lab02:36. Inverted mirrored right triangle star pattern: Given an integer N, display the Inverted
mirrored right triangle star pattern as described in output.
Input:
5
where: First line represents the value of N( number of rows ).
Output:
*****
****
***
**

Lab02:37. Half diamond star pattern: Given an integer N, display the half diamond star pattern as
described in output.
Input:
5
where: First line represents the value of N.
Output:
*
**
***
****
*****
****
***
**
*

Lab02:38. Hallow Diamond star pattern: Given an integer N, display the hallow diamond star
pattern as described in output.
Input:
5
where:

• First line represents the value of N( number of rows in one half of the pattern ).
Output:
**********
**** ****
*** ***
** **
* *
* *
** **
*** ***
**** ****
**********
Lab02:39. Plus star pattern: Given an integer N, display the plus star pattern as described in output.
Input:
5
where: First line represents the value of N.
Output:
+
+
+
+
+++++++++
+
+
+
+

Lab02:40. Heart star pattern: Given an integer N, display the heart-star pattern as described in
output.
Input:
10
where:

• First line represents the value of N.


Output:

***** *****
******* *******
********* *********
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*

Lab 12
Lab02:61. Student Class: Create a class name as 'Student' with String variable 'name' and integer
variable 'roll_no'. Assign the value of roll_no as '2' and name as "John" by creating an object of the
class Student.
Input:
John
2
Where first line denotes name and second line denotes his roll no.
Output:
Name is John and roll number is 2

Lab02:62. Employee Details: Define a class named Employee with the following characteristics:
Variables
• int employeeId
• String employeeName
• String designation
• int salary
Methods
• void getEmployee() - Accepts console input for employeeId, employeeName,
designation, and salary.
• void showGrade() - Displays grade of an employee based on criteria specified below.
• Void ShowEmployee() - Displays employee details.

Salary Grade
0 to 20000 D
20001 to 50000 C
50001 to 100000 B
100001 and above A

Input
1
Codezinger
Software Developer
800000
where,
• First line represents employee ID.
• Second line represents employee's name.
• Third line represents employee's designation.
• Fourth line represents employee's salary.
Output
Employee grade is:
A Grade
Employee details are:
Employee ID=1
Employee Name=Codezinger
Designation=Software Developer
Salary=800000
where,
• Display grade (i.e. A,B,C,D) concatenated with “Grade”.
• Employee details are separated by a new line.
• No new line should be present after salary.

Lab02:63. Arithmetic Operation Class: Create a class Arithmetic with the following characteristics:
Variables
• double number1
• double number2
• char operator
• double Result
Methods
• void getInput() - Accepts console input for number1, number2, and the type of
arithmetic operator (+, -, *, /)
• void ComputeResult() – Compute the results according to the given operator and store
the result in the Result variables.
• Void ShowResult() - Displays results stored in the Result variables.
Input
4.5
3.0
+
where
• First line represents a value of N1.
• Second line represents a value of N2.
• Third line represents an operator.
Output
7.5

Lab02:64. Constructor overloading: Create a class ProblemSolution with the following


characteristics:
• First constructor accepts two integer parameters N1 and N2 and displays addition of 2 numbers.
• Second constructor accepts three integer parameters N1, N2 and N3 and displays addition of 3
numbers.
Input
10
20
45
where
• First line represents a value of N1.
• Second line represents a value of N2.
• Third line represents a value of N3.
Output
30
75

Lab02:65. Triangle Class: Write a program to print the area and perimeter of a triangle having sides
of a, b and c units by creating a class named 'Triangle' without any parameter in its constructor.
Input
2
5
6
Output
13
4.68
Explanation: Solve using (s=(a+b+c)/2, area=s*(s-a)*(s-b)*(s-c)^1/2)

Lab02:66. Instance variable initialization: Create a class Problem Solution with the following
characteristics:
• Two private variables name & designation of string type.
• Parameterized constructor which takes 2 parameters to initialized name & designation.
• Method with no input parameter and void return type. A method should print the variable values
in new lines.
Input:
John Snow
Warrior
where,
• First line represents a name.
• Second line represents a designation.
Output:
John Snow
Warrior

Lab02: 67. Student Class: Write a program to print the names of students by creating a Student class.
If no name is passed while creating an object of Student class, then the name should be "Unknown",
otherwise the name should be equal to the String value passed while creating object of Student class.
Input:
xyz
Output:
xyz

Lab02:68. Rectangle Class: Write a program to print the area of a rectangle by creating a class named
'Area'. It takes the values of its length and breadth as parameters of its constructor and having a method
named 'returnArea' which returns the area of the rectangle. Length and breadth of rectangle are entered
through keyboard.
Input
5
4
Output
20

Lab 13

Lab02:69. Define a class Fan: Create a class named as Fan with the following characteristics:
Variables:

• int speed – specifies the speed of the fan (default 1).


• boolean f_on – specifies whether the fan is on (default false).
• double radius – specifies the radius of the fan (default 4).
• String color – specifies the color of the fan (default blue).

Methods:

• Default constructor()
• Parameterized constructor(speed, f_on, color, radius)
• "void display()" to display the details of a fan and its state.
• If the fan is 'on' display details in "FAN_STATE SPEED COLOR RADIUS" format. If the
fan is 'off' display details in "FAN_STATE COLOR RADIUS".
• if the fan is on the FAN_STATE will be “ON” and if a fan is off FAN_STATE will be
"OFF".

Input
2
black
6
true
3

where,

• First line represents default constructor (1) or parameterized constructor (2).


• Second line represents Fan's color.
• Third line represents Fan's radius.
• Forth line represents whether a Fan is on or off. (true means Fan is on)
• Fifth line represents Fan's speed.

Output
ON 3 black 6

Lab02:70. MovieMagic Class: Create class MovieMagic with the following characteristics:
Variables:

• int year – to store the year of release of a movie.


• String title – to store the title of the movie.
• float rating – to store the popularity rating of the movie. (minimum rating = 0.0 and maximum
rating = 5.0)

Methods:

• Default constructor to initialize numeric variables to 0 and String variable to "".


• accept - Read the value of a year, title and rating from the console. The return type of this
method is void.
• display - Displays the title of the movie and a message based on the rating as per the table
below.

RATING MESSAGE TO BE DISPLAYED


0.0 to 2.0 Flop
2.1 to 3.4 Semi-hit
3.5 to 4.5 Hit
4.6 to 5.0 Super Hit
Input
2016
Deadpool
4.0
where,

• First line represents the year of release.


• Second line represents the title of the movie.
• Third line represents rating.

Output
Deadpool Hit

Lab01: 61: Write a program for calculating hospital bill. It should have four methods:
1. Patientdetails()-This method is to assign patient details.
Details are:
String Name;
Int age;
String address
Blood Group
String staff_assigned
2. ShowPatient()- This method is used to the show the details of the patient.
3. Bloodneed()-This method will get active, if the patient needs the blood. Make a variable
named blood in main, where if blood==’y’. Bloodneed() should get active and calculate
the bill.
if the bloodgroup is “O”, 2000rs will be charged.
if the bloodgroup is “A”, 2100rs will be charged.
if the bloodgroup is “B”, 2200rs will be charged.
if the bloodgroup is “AB”, 2500rs will be charged.
4. Treatment()- This should specify the treatment type of the patient.
If the patient had “Minor Surgery” 50,000rs will be charged.
If the patient had “Major Surgery” 1,00,000rs will be charged.
If the patient had “Vaccine Therapy” 3000rs will be charged.
If the patient had “Chemotherapy” 2,00,000rs will be charged.
5. Discount()- This method should provide discount based on the age.
if the patient’s age is above 60, he/she will get a discount of 50%
if the patient’s age lies in 40 –60, he/she will get a discount of 30%.
if the patient’s age lies in 20-39, he/she will get a discount of 20%.
If the patient’s age is below 20, he/she will get a discount of 10%.
6. showBill()-This will show the final bill.
Input
Ram
21
Patiala
O
Sham
Chemotherapy
Where first line represents the name, second line represents the age, third line represents the
address, fourth line represents the Blood group, fifth line represents the assigned staff member,
sixth line represent the treatment type.
Output
161600.00

Lab01:64. Given an integer N, find the sum of digits of N using recursion.


Write a function that accepts an integer N. The function should return the sum of digits
of N using recursion.
Input:
1231
where:
First line represents a value of N.
Output:
7
Explanation: For 1231, the sum of its digits = 1+2+3+1 = 7

Lab01:65. Write a program to calculate the batting average, batting strike rate, bowling
average and bowling strike rate. The formulas for calculating the mentioned entities are:
BatAver() calculates the batting average of the batsman. It is calculated as:
avg=totalruns/(innings-notout);

Batstrike() calculates strike rate of batting. It is calculated as:


batstrike=(runs/balls)*100;
Bowlaver() calculates the bowling average of the bowler. It is calculated as:
bowlavg= runs_conceed/wickets;
Bowlstrike() calculates the strike rate of the bowler. It is calculated as:
bowlst=total_balls_bowled/wickets;
Input
65
62
2
5454
1223
10
40
20
89
6
Where the first line represents Matches, second line represents Innings, third line represents
the number of times batsman remained notout, fourth line represents the total runs scored by
the batsman. These inputs are used to calculate batting average.
Fifth line represents the runs_conceeded followed, sixth line represents wickets taken by the
bowler. These inputs are used for calculating bowler’s average.
Seventh line represents runs, eight line represents the balls taken by the batsman. These inputs
are used for calculating batting strike rate.
Eight line represent total balls bowled and ninth line represents the total wickets taken in those
balls. These inputs are used for calculating bowler’s strike rate

Lab01:68. Given an integer N, find the sum of digits of N using iterative method. Write a
function that accepts an integer N. The function should return the sum of N's digits.
Input
121
Output
4
For 121, the sum of its digits = 1+2+1 = 4
Assume that,
N is an integer within the range [0 to 1000000000].

Lab02:74. Multiply your commission rate by your commission base for the period
to calculate your commission payment. Write a function calculateCommission, which accepts
the amount and commission percentage and returns the calculated commission.

Example:
For example, if you made $30,000 worth of sales from March 1 to March 15 and
your commission rate is 5 per cent, your commission payment is $1,500.
Input
1000
17.55
Output
175.50000000000003

Week 6

Lab 14

Lab 14.1

Write a program to take 'n' elements in an array and print the array.

Input: (N, elements)

0
9
8
7
6

Output:

Array elements are:


0
9
8
7
6

Lab 14.2
Write a program the print the ‘n’ elements of an array in reverse order.

Input:
5
5
4
3
2
1

Output:
1
2
3
4
5

Lab 14.3:

Write a program to find the sum of ‘n’ elements (float type) in an array.

Input: (n, elements)

Output:

Sum of Array elements are:


6.0

Lab 14.4 String array

Write a program to demonstrate String array by taking 'n' names as input and display them

Input: (n,names)

priya

shruti

Output:

priya
shruti

Lab 14.5
Create three arrays of same size n, the value of n should be taken from the user. In the first
array the roll no of students should be stored followed by the second array where names
are entered, and third array should contain the marks of the students. All the values in the
arrays should be taken as input. Also, create a function to display the information of all the
students. .
Input
3
Sam
Pam
Tam
1
2
3
98
70
20
First line represents the size of array. Next three line represents the name, Afterward the next
three lines represents the roll no and the next three lines represents marks of the students.

Output
Sam 1 98
Pam 2 70
Tam 3 20

Lab 14.6 2D Array


Write a program to demonstrate 2 Dimensional array of m*n array and print the array in matrix form.

Input: (m,n)
2
3
1
2
3
4
5
6
Output:
Elements of the array in 2d matrix:
123
456

Lab 14.7 Largest number in an array

Write a program to take 'n' integer numbers in an array and find the largest element among
them.

Input: (n, elements)

12

34

78

Output:

Largest element 78
Lab1:72. Create an array of n size to store n integer numbers. The array should store only distinct
elements. If user enters a number more than one times, then it should be stored once, and
removes duplicate values while storing the elements in the array. After storing all the elements
from the user, display the distinct array elements entered and also display the distinct element
in increasing order in increasing order, as shown in the output.
Note: You are also not allowed to use any additional array.
Input:

5 (Size of Array)
5
10 Array Elements
3
10
9

Output:
Distinct elements in entered order are: 5 10 3 9 0
Size of Array is: 5
Distinct elements in increasing order are: 3 5 9 10 0

Lab1:73. Lab1:73: Create two arrays with name A and B of size n and m respectively. Check
whether all the distinct elements of array B are included in the array A or not. If all the elements
(distinct) of B are included in A then display “Yes”, otherwise displays “No”.
Note: You are not allowed to use any extra array.

Test Case 1

Input:
5 (Size of first Array)
3 (Size of Second Array)
1 3 7 5 9 (First Array Elements)
7 9 2 (Second Array Elements)

Output:
No

Test Case 2

Input:
5 (Size of first Array)
3 (Size of Second Array)
1 3 7 5 9 (First Array Elements)
7 9 9 (Second Array Elements)

Output:
Yes

Lab1:75 Make a method named perf_Fact () which should take an integer array as an input
of n size. The function should check each array element, if element is perfect square, then
the factorial of sum of its digits should be displayed. Input will be entered from the user.
Input

4
16 121 34 12

Output
The factorial of sum of digits: 5040
The factorial of sum of digits: 24

Lab 15
Lab 15.1

Write a program to enter the 'n' integer numbers in an array using inbuilt package ArrayList.

Input: (n, elements)

45

36

12
Lab 15.2

Write a program to show the usage of Calendar class to print the present year, maximum
number of days in a week, maximum number of weeks in the present year.

Input: (No input req)

Output:

At present Calendar's Year: 2021


Maximum number of days in week: 7
Maximum number of weeks in year: 53

Lab 15.3

Write a program that takes the name of a student, his marks in physics and mathematics.
Find the sum of marks by using Math.addExact method and Math.max to find the maximum
of two marks by importing java.lang package.

Input: (Nmae, physics marks, maths marks)

Rahul

10

20

Output:

Welcome : Rahul
Total of Physics and Maths marks = 30
Max of Physics and Maths marks = 20
Lab02:89. Create a public Class Arithmetic in a package Pack1 with following protected methods:

a. int sum(int a, int b): Computes and returns the sum of a and b.
b. int difference(int a, int b): Computes and returns the absolute difference of a and b.
c. long mul(int a, int b): returns the multiplication of a and b.
d. double div(int a , int b): returns the result by dividing a by b.

Now, create another class Compute in the package Pack2 that contains the following methods:
a. void area(): compute and display the area of rectangle.
b. void Perimeter(): compute and display the perimeter of rectangle,
c. Void EdgeDiff (): Computes the absolute difference of two adjacent sides and display it.
d. Void EdgeSum(): Computes the sum of two adjacent sides and display it.
e. Void AreaPerimenterDiv(): Display the results by dividing area with perimeter if area is
greater than perimeter else display the results by dividing the perimeter by area.

Every operation in all these methods i.e. addition, subtraction, multiplication and division must be
performed using the respective method of Arithmetic class. No operator i.e. ‘+’, ‘-‘, ‘*’ and ‘/’ can
use in the Compute class to perform an operation.

Further, create a Main class in another package namely Pack3 and defined the main method in this
class. Finally, create an object of the Compute class in main method and call the methods of Compute
class to display the respective result.

Note: Specify the appropriate access modifier wherever it require.

Test Case1

Input:
45

Where, Input line represents the two number to perform the different operations.
Output:
Area: 20
Perimeter: 18
Edge Difference: 1
Edge Sum: 9
Aare Perimeter Division: 1.11

Test Case2
Input:
17 8
Output:
Area: 136
Perimeter: 50
Edge Difference: 9
Edge Sum: 25
Aare Perimeter Division: 2.72

Lab02:90. Write a program which uses packages. Create a class Animal in package Pack1 with the
following methods:
Void sleep()-This method will print “Zzzzzzzz”.
Void Noise()- This method will print “Grrrr”
Void roam()- This method should print “Roaming near water”.
Create another class Lion in package Pack2 that overrides the method Noise() of Animal class as
follows:
Void Noise()- It should print “Roar:Rrrrrrrrr”. And also calls the method Noise() of the Animal
class.
Further, create another class Cat in package Pack2 that overrides the method Noise() as follows:
Void Noise()- It should print “Meow Meow”.
Further, create another class Wolf in package Pack2 that overrides the method Noise() and sleep() as
follows:
Noise()- It should print “Howling: Ouooooo!”.
sleep()- It should print “Wolf: hrrr”. This method also calls the sleep() method of Animal class.

Finally, create a Main class in package Pack3 and display sleep, noise and roam for all the method for
all the animals by calling the respective method in main method using the reference of (base) Animal
class while creating the objects.

Output:
wolf=====
Howling: Ouooooo!
Roaming near water
Wolf: hrrr
Zzzzzzzz

Lion=====
Roar:Rrrrrrrrr
Grrrr
Roaming near water
Zzzzzzzz
Cat=====
Meow Meow
Roaming near water Zzzzzzzz

Lab 16
Lab01: 62. Method overloading: Design a class ProblemSolution to overload a function
solution.
Write a function int solution(int N, char CH) that accepts integer N and character CH.
The function should return square of a number (N), if a character (CH) is "s". Otherwise,
return cube of a number.
int solution(int N, int M, char CH) that accepts two integers (N and M) and one
character CH. The function should return the product of two integers, if a character
(CH) is ‘p’. Otherwise, return their sum.
boolean solution(String S1, String S2) that accepts two strings S1 and S2. The function
should return true, if S1 and S2 are equal. Otherwise, false.
Input
1
4
s
where,
First line represents a choice for calling one of the defined methods. (1 for solution(int
N, char CH), 2 for solution(int N, int M, char CH) and 3 for solution(String S1, String
S2)).
Second line represents number input.
Third line represents choice CH.
Output
16
Here, the first line contains 1 and hence solution(int N, char CH) will be invoked and
since the number is 4 and choice CH is ‘s’, the function returns 16.

Lab01: 63. Arithmetic operations with method overloading: Use method overloading
to write 2 overloaded functions to perform the arithmetic operations.
Write the functions float calculator(int N1, int N2, String CODE) that accepts two
integer parameters N1 and N2 and a string parameter CODE. The function should
perform arithmetic operations based on CODE and return the result as a float data type.
int calculator(float N1, float N2, String CODE) that accepts two integer parameters
N1 and N2 and a string parameter CODE. The function should perform arithmetic
operations based on CODE and return the rounded result as an int data type.
Note: CODE values can be “+”, “-”, “*” and ”/” only. In case of division by zero, return
0.
Input
1
2
3
/
Where,
First line of input represents the type of function to call.
Second and third lines represent N1 and N2, respectively.
Fourth line represents choice of arithmetic operation.
Output
0.6666667

Lab01:66. Overload function polygon: Write 3 overloaded functions polygon, which draws
a polygon according to the given input.
Write a function
void polygon(int N, String S) that accepts an integer N and String S. The function
should draw a filled square of side N using the String S.
For N=2 and S='O', the polygon will look like
OO
OO
void polygon(int X, int Y) that accepts integer X and Y. The function should draw
a filled rectangle of X rows and Y columns using the character ‘@’.
For X=2 and Y=5, the polygon will look like
@@@@@
@@@@@
void polygon(int n) that accepts integer N, The function should draw a filled isosceles
right triangle using the character ‘*’ as shown below.
For N=3, polygon will look like
*
**
***
Input
3
3
Where,
First line of input represents the type of function to call. (1 for polygon(int N, char S),
2 for polygon(int X, int Y) and 3 for void polygon(int n))
Second line of input represents the size of square for 1st type OR a number of rows in
the rectangle for 2nd type OR size of the isosceles right triangle for the 3rd type of
polygon function.
Third line of input represents a character to display for 1st type OR number of columns
in the rectangle for 2nd type of polygon function
Output
*
**
***

Lab01:67. Overload a function compare: Use function overloading to create an overloaded


method "compare", which accepts two values of the same type (either integer, character or
String).
Write the functions int compare (int N1, int N2) that accepts two integer parameters
N1 and N2 and compares them. The function should return 1 if N1 is greater, -1 if N2
is greater or 0 if both are equal.
int compare (char N1, char N2) that accepts two-character parameters N1 and N2
and compares their numeric values. The function should return 1, if N1 is greater, and
-1, if N2 is greate. Otherwise, return 0, if both are equal.
int compare (String N1, String N2) that accepts two string parameters N1 and N2 and
compares their lengths. The function should return 1, if N1 is greater, and -1, if N2 is
greater. Otherwise, return 0, if both are equal.

Input
3
Hello
Codezinger
Where,
First line of input represents the type of function to call on the basis of arguments passed
as 1 for integer, 2 for character and 3 for the string.
Second and third lines represent N1 and N2, respectively.
Output
-1

Lab02:72. Write a method calpower(), which takes two input. The first input is the number
and the second input is the power of the first number. For example: the first input is 4, and the
second input is 2, then calpower() should return 4^2=16
Input
2
9
Output
512

Lab01: 61: Write a program for calculating hospital bill. It should have four methods:
1. Patientdetails()-This method is to assign patient details.
Details are:
String Name;
Int age;
String address
Blood Group
String staff_assigned
2. ShowPatient()- This method is used to the show the details of the patient.
3. Bloodneed()-This method will get active, if the patient needs the blood. Make a variable
named blood in main, where if blood==’y’. Bloodneed() should get active and calculate
the bill.
if the bloodgroup is “O”, 2000rs will be charged.
if the bloodgroup is “A”, 2100rs will be charged.
if the bloodgroup is “B”, 2200rs will be charged.
if the bloodgroup is “AB”, 2500rs will be charged.
4. Treatment()- This should specify the treatment type of the patient.
If the patient had “Minor Surgery” 50,000rs will be charged.
If the patient had “Major Surgery” 1,00,000rs will be charged.
If the patient had “Vaccine Therapy” 3000rs will be charged.
If the patient had “Chemotherapy” 2,00,000rs will be charged.
5. Discount()- This method should provide discount based on the age.
if the patient’s age is above 60, he/she will get a discount of 50%
if the patient’s age lies in 40 –60, he/she will get a discount of 30%.
if the patient’s age lies in 20-39, he/she will get a discount of 20%.
If the patient’s age is below 20, he/she will get a discount of 10%.
6. showBill()-This will show the final bill.
Input
Ram
21
Patiala
O
Sham
Chemotherapy
Where first line represents the name, second line represents the age, third line represents the
address, fourth line represents the Blood group, fifth line represents the assigned staff member,
sixth line represent the treatment type.
Output
161600.00

Week 7
Lab 17
Lab 17.1

Define a package animals which has an interface "Animal" having following methods():

void eat()

void travel()

Implement the interface Animal in the package animals having class MammalInt with the
following characteristics:

the methods are called by taking the choice as input:

if choice is 1, the void eat() method is called which prints "Mamals eats".

if choice is 2, the void travel() method is called which prints "Mamals travels".

if choice is 3, the int legs() method is called which returns the number of legs mamals have
i.e 4.
For any other choice it prints "Wrong Input".

Input: (choice)

Output:

Mamals eats

Input: (choice)

Output:

Lab02:91. Create a public Class Arithmetic in a package Pack1 with following methods:

e. int sum(int a, int b): Computes and returns the sum of a and b.
f. int difference(int a, int b): Computes and returns the absolute difference of a and b.
g. long mul(int a, int b): returns the multiplication of a and b.
h. double div(int a , int b): returns the result by dividing a by b.

Note: Specify the appropriate access modifier wherever it require.

Now, create another class Compute in the package Pack2 that contains the area, perimeter, edgeDiff,
edgeSum, APDiv public data members and following private methods:
f. void area(): Compute and store the area of rectangle in area data member.
g. void Perimeter(): Compute and store the perimeter of rectangle in perimeter data
member,
h. void EdgeDiff (): Computes the absolute difference of two adjacent sides and store it in
edgeDiff data member.
i. void EdgeSum(): Computes the sum of two adjacent sides and store it in , edgeSum data
member.
j. void AreaPerimenterDiv(): Stroe the results in APDiv by dividing area with perimeter if
area is greater than perimeter else store the results by dividing the perimeter by area.

Every operation in all these methods i.e. addition, subtraction, multiplication and division must be
performed using the respective method of Arithmetic class (without inheriting). No operator i.e. ‘+’,
‘-‘, ‘*’ and ‘/’ can use in the Compute class to perform an operation. Note: You can define a
separate method with appropriate access modifier to call the above method if require.
Further, create a Main class in another package namely Pack3 and defined the main method in this
class. Finally, create an object of the Compute class in main method and display results which are
evaluated using methods of Compute class.

Test Case1

Input:
45

Where, Input line represents the two number to perform the different operations.
Output:
Area: 20
Perimeter: 18
Edge Difference: 1
Edge Sum: 9
Aare Perimeter Division: 1.11

Test Case2
Input:
17 8
Output:
Area: 136
Perimeter: 50
Edge Difference: 9
Edge Sum: 25
Aare Perimeter Division: 2.72

Lab01:91. Write a program which uses inheritance. There should be a class Animal which will
be a base class, class wolf is class which extends to animal class and class main is used to run
the program.
Animal class – This class have methods sleep(), Noise(), roam().
sleep()-This method will print “Zzzzzzzz”.
Noise()- This method will print “Grrrr”
roam()- This method should print “Roaming near water”.

Animal class have these three common methods, but every animal will make different
noise. So, make another class Lion which inherits from animal. It should override the
Noise() method of the animal class.
Noise()- It should print “Roar:Rrrrrrrrr”

Make another class Cat which extends to animal. It should have a makeNoise() method as
follows:
Noise()- It should print “Meow Meow”.

In the same way, make another class Wolf which extends to animal. It should have a Noise()
method as follows:
Noise()- It should print “Howling: Ouooooo!”.
In the end make a variable choice which takes input from the user. If the input is 1, it should
execute the methods of wolf, for 2 it should execute the methods of lion and for 3 it should
execute the noise, sleep and roam methods of wolf.

Test Case 1:
Input
1
Output:
wolf=====
Howling: Ouooooo!
Roaming near water
Zzzzzzzz
Test Case 2:
Input
2
Output:
Lion=====
Roar:Rrrrrrrrr
Roaming near water
Zzzzzzzz
Test Case-3
Input:
3
Output:
Cat=====
Meow Meow
Roaming near water
Zzzzzzzz

Lab01:92. Create two Calculator classes named calc_int and calc_ double. The calc_int should
inherit the variable a and b from calc_double. which calculates divide, multiply, modulus,
addition and subtraction. Main method should call the derived class calculation methods which
inturns calls the base class’s same method. For eg- if the derived class Add(int a, int b) is called
from main, then the Add method of calc_int should call the add method of base class
(calc_double) and so on.

The methods of calc_int are defined as:


Add(int a, int b)- This method should take int a and b as input and returns the addition.
Sub(int a, int b)- This method should take int a and b as input and returns the subtraction.
Mul(int a, int b)- This method should take int a and b as input and returns the multiplication.
Mod(int a, int b)- This method should take int a and b as input and returns the modulus.

The methods of calc_ double are defined as:


Add(double a, double b)- This method should take double a and b as input and returns the
addition.
Sub(double a, double b)- This method should take double a and b as input and returns the
subtraction.
Mul(double a, double b)- This method should take double a and b as input and returns the
multiplication.
Mod(double a, double b)- This method should take double a and b as input and returns the
modulus.
Test Case 1:
Input:
12 5

Output:

Derived Class Addition: 17


Base Class Addition: 17.0
Derived Class Subtraction: 7
Base Class Subtraction: 7.0
Derived Class Multiplication: 60
Base Class Multiplication: 60.0
Derived Class Modulus: 2.0
Base Class Modulus 2.0
Test Case 2:
Input:
145 58
Output:
Derived Class Addition: 203
Base Class Addition: 203.0
Derived Class Subtraction: 87
Base Class Subtraction: 87.0
Derived Class Multiplication: 8410

Base Class Multiplication: 8410.0


Derived Class Modulus: 29.0
Base Class Modulus 29.0

Lab 18

Lab01:86. Given an integer numbers N, create a class 'ProblemSolution' which demonstrates


inheritance with the following characteristics

1. Must inherit from 'Base' class.


2. Create a 'solution' method with an integer parameter and void return type.
3. The 'solution' method should assign the given value N into 'Base' class property 'num' and call
the 'display' function of 'Base' class.

Input:
4
Where, input denotes the value to assign the num
Output:
Base Calling Num is: 4
Lab01:87. Given two integer numbers N1 and N2, create a class 'ProblemSolution' with
following characteristics.

1. Must extend a 'Base' class.


2. Create a method 'solution' with two integer parameters (N1 and N2) and long return type.
3. The 'solution' method should call the addition and subtraction methods of 'Base' class and
return multiplication of returned results of addition and subtraction method.

Result = (N1 + N2) * (N1 - N2)

Input:
53
Where, input line denotes the value of N1 and N2 which is passed while calling solution in
main method.
Output:
Base Addition: 8
Base Subtraction: 2
Child Multiplication: 16

Lab01:88. Given a string NAME and three integers ID, HR, HW. Create a
Class HourlyEmployee with following characteristics

1. Extend an Employee class.


2. Private member variable hourlyRate and hoursWorked as an integer.
3. Parameterized Constructor with parameters in the order of NAME, ID, HR (for hourlyRate)
and HW (for hoursWorked).
4. Parameterized Constructor should call a super class constructor with NAME and ID. Also,
initialize hourlyRate with HR and hoursWorked with HW.
5. The public function getGrosspay without any parameter and return gross pay amount of type
integer.

Grosspay = (hourlyRate * hoursWorked )

Input
Alex
101
100
5

Where,

• First line represents NAME.


• Second line represents ID.
• Third line represents hourly rate HR.
• Forth line represents hours worked HW.

Output
101
Alex
500

Where,
• The first line represents an ID.
• The second line represents a NAME.
• The third line represents Gross Pay.

Lab01:89. Create a Class Shape with following methods:

i. void area (int a): compute the area of Square and display it.
j. void area (int a, int b): compute the area of rectangle.

Further, create another class Compute that inherits the class Shape and overrides the method area (int
a) for computing the area of circle (i.e. 3.14*r*r). Finally, display the area of square, rectangle and
circle by calling the respective method in main using the references of (base) Shape class while
creating the objects of different classes.

Input:
34
Where, input line represents the value of a and b to compute the area.
Output:
Base Calling Area of Square: 9
Base Calling Area of Rectangle: 12
Derive Calling Area of Circle: 28.6

Lab01:90. Create a Class Shape with following methods:

k. void area (int a): compute the area of Square and display it.
l. void area (int a, int b): compute the area of rectangle.

Further, create another class Compute that inherits the class Shape and overrides the method area (int
a) for computing the area of circle (i.e. 3.14*r*r). Finally, display the area of square, rectangle and
circle only using the reference and object of the derived (Compute) class.

Lab 19.1
Description:
Create a class student with the following properties:
Three variables: rollno (int), Name (String) and University (static variable).
Assign the name of the University as “Bennett”
Constructor is used to initialize the rollno and name.
The class has a method called as display (void type) that displays the rollno, name and University of
the respective student.
Make a class main that call the display function using object of class student.
Input: Rollno, Name
10 Rahul
Output:
10 Rahul Bennett

Lab 19.4 Create class to read time in seconds and convert into time in (HH:MM:SS) format

Create a class named Time with following characteristics:

1. It has private parameters hour, minute,second.


2. Create a constructor which takes total time of day in seconds, converts into hour, minute and
second and store in the respective private vairables. Use long data type as input argument.
3. Create a method getTime() which returns time in 24- hour format (HH:MM:SS) as string.

Lab 19.5
Given a class Car , create two classes 'BMW' and 'Honda' with following characteristics

• BMW class should have private property alloyWheels of integer type.


• Honda class should have private property normalWheels of integer type.
• Both BMW and Honda are inherited from 'Car' class.
• Both classes should implement setData which will set model, the color of super class and
wheel count.
• BMW class should implement "getAlloyWheelCount" to return count of alloyWheels;
• Honda class should implement "getNormalWheelCount" to return count of normalWheels;

Input
BMW1Series5-door Red 4
i-VTECS1497 Black 6

where,

• First line of input is a model, color, alloyWheels of BMW separated by space.


• Second line of input is a model, color and normalWheels count of Honda separated by space.

Output
BMW1Series5-door Red 4
i-VTECS1497 Black 6

where,

• First line is a model, color and alloyWheels count of BMW separated by space.
• Second line is a model, color and normalWheels count of Honda separated by space.

Assume:

• Wheel counts for both cars are integers within the range [1 to 20].
Week 8
Lab 20
Lab01:104. Introduction to Abstract class and Abstract method:

Given an integer N, create an Abstract class “Shape” with an abstract method “printArea” that
accepts integer parameter and has return type void.

Also, create a “Square” class inherited from “Shape” class which implements a “printArea”
method to print the area of the square (Area of Square = N2).

Input
50

Output
2500

Assume that,

• N is an integer within the range [1 to 1000000].

Lab01:105. Create 'Employee' as an abstract class and 'Developer' and 'Driver' its subclasses. Both the
sub class having a private integer variable namely ‘salary’. Both the class also defines their parametrized
constructor to initialize the data member and override the abstract method int getSalary() method of the
Employee class to return the respective salary. Finally, create class Main that create the object of both
sub class and display the salary of Developer and Driver by calling respective getSarlary() method as
shown in output.

Test Case 1
Input:
5000 3000
Input line represents the salary of developer and driver respectively.

Output:
Salary of developer: 5000
Salary of driver: 3000

Test Case 2
Input:
15000 7000
Input line represents the salary of developer and driver respectively.

Output:
Salary of developer: 15000
Salary of driver: 7000
Lab01:106.

Write a program which uses inheritance and abstract class. Make an abstract class Animal which
sshould have three subclasses Lion, Cat and Wolf. Animal class have the abstract method Noise and
all other classes and methods are defined below:

Animal class – This class have methods sleep(), abstract Noise(), roam().
sleep()-This method will print “Zzzzzzzz”.
roam()- This method should print “Roaming near water”.

Animal class have these three common methods, but every animal will make different noise. So,
make another class Lion which inherits from animal. The noise will be described as follows:
Noise()- It should print “Roar:Rrrrrrrrr”

Make another class Cat which extends to animal. It should have a Noise() method as follows:
Noise()- It should print “Meow Meow”.

In the same way, make another class Wolf which extends to animal. It should have a Noise() method
as follows:
Noise()- It should print “Howling: Ouooooo!”.

In the end make a variable choice which takes input from the user. If the input is 1, it should execute
the methods of wolf, for 2 it should execute the methods of lion and for 3 it should execute the
noise, sleep and roam methods of wolf.
Test Case 1:
Input
1
Output:
wolf=====
Howling: Ouooooo!
Roaming near water
Zzzzzzzz
Test Case 2:
Input
2
Output:
Lion=====
Roar:Rrrrrrrrr
Roaming near water
Zzzzzzzz
Test Case-3
Input:
3
Output:
Cat=====
Meow Meow
Roaming near water
Zzzzzzzz
Lab01:107. Given a Book class and a Solution class, write a MyBook class that does the following:
a. Inherits from Book
b. Has a parameterized constructor taking these 3 parameters:
i. string title
ii. string author
iii. int price
c. Implements the Book class' abstract display() method so it prints these lines:
i. Title: a space, and then the current instance's title.
ii. Author: a space, and then the current instance's author.
iii. Price, a space, and then the current instance's price.
Note: Because these classes are being written in the same file, you must not use an access modifier
(e.g.: public) when declaring MyBook or your code will not execute.

Test Case 1
Input:
Java: The Complete Reference
SCHILDT and HERBERT
750
First and second line represents the Book title and author respectively. Third line represents the price
of the book.

Output:
Title: Java: The Complete Reference
Author: SCHILDT and HERBERT
Price: 750

Test Case 2
Input
The Alchemist
Paulo Coelho
248
Output
Title: The Alchemist
Author: Paulo Coelho
Price: 248

Lab01:108. Create abstract class EmployeeDetails with two private data member namely name and
emp_id of string and integer type respectively. This class contains the following methods:
a. Parameterized constrictor to initialize the data member.
b. commonEmpDetaills: Display the name and employee id as shown in output.
c. Abstract method: confidentialDetails();
Noe create a sub class HR which is inherited from the EmployeeDetails. This class contains two
private data member salary and performance with integer and String type. This class contains the
following methods:
a. Parameterized constrictor to initialize its own data members and base class data member
b. Overrides the confidentialDetails() method to display the salary and performance of the
employee as shown in output.
c.
Finally, create a Main class to create the object of subclass and display the following output according
to the given input;

Input:
Ankit
2
5000
Good
Where, first two line represent the employee name and id. Last two line represent the salary and
performance.

Output:
Salary=5000;
Performance=Good
Employee Name=Ankit
Employee Id=2

Lab01:112. Multiple Inheritance using Interface: Create a class “Bat” and implements interfaces
“Mammal” and “WingedAnimal”.

Also, override methods in “Bat” class, a method eat() of interface “Animal” which display “Bat
can eat”, a method breathe() of interface “Mammal” which display “Bat can breathe” and a
method flap() of interface “WingedAnimal” which display “Bat can fly”.

Note: Animal, Mammal and WingedAnimal interfaces already created.

Output
Bat can eat
Bat can breathe
Bat can flap
Note: Here no new line after last line “Bat can flap”.

Lab01:106. Define an interface named Faculty with following characteristics

• getDetails method to return string.


• getSalary method to return double type salary.

Define AssistantProfessor which implements Faculty has following characteristics


• Parameterized constructor(name, basic, DA) to initialize all data members of a class. Call the
base class constructor to initialize name & basic.
• Data member DA (integer type) which is % of basic salary.
• Override getSalary to calculate and return salary as, "basic + ((basic * DA)/100)".
• getDetails method to return name & salary separated by space in "AssiProf NANE
SALARY" format.

Define AssociateProfessor which extends AssistantProfessor has following characteristics

• Parameterized constructor(name, basic, DA, MedAllowance) to initialize all data members of


a class. Call the base class constructor to initialize other values.
• Data member MedAllowance (integer type) which fixed amount.
• Override getSalary to calculate and return salary as, basic + ((basic * DA)/100) +
MedAllowance.
• getDetails method to return name & salary separated by space in "AssoProf NANE
SALARY" format.

Define Professor which extends AssociateProfessor has following characteristics

• Parameterized constructor(name, basic, DA, MedAllowance, OtherAllowance) to initialize all


data members of a class.
• Data member OtherAllowance (integer type) which is % of total income.
• Override getSalary to calculate and return salary as, "Salary of AssociateProfessor" +
(OtherAllowance% of "Salary of AssociateProfessor").
• getDetails method to return name & salary separated by space in "Prof NANE SALARY"
format.

Input
3
John
450000
125
10000
5

where,

• First line represents a choice for which class to instantiate.


• Second line represents the name of the professor.
• Third line represents basic salary.
• Forth line represents DA value.
• Fifth line represents MedAllowance value.
• Sixth line represents OtherAllowance value.

Output
Prof John 1073625
Week 9
Lab 23:
Lab 23.1
Write a program that takes the size of an array (long) and if the size of the array is negative/exceeds
the limit an exception is generated. Also write a final block that display the message “ Block finally
always executes”

Input:
10
Output:
value of n is 10
Block finally always executes.

Input:
-50
Output:
value of n is-50
java.lang.NegativeArraySizeException
Block finally always executes.

Lab 23.2
Write a program that takes two input (int), size of the array and the position of the element (i).
Generate the Exception to print the element at (size+1), and in final block print the element at ith
position in the array along with the message “The finally statement is executed


Input:
5
3
10
20
30
40
50

Lab 23. 3
Write a program to print the multiplication of the lower triangular elements of a matrix. A
lower triangular matrix is a matrix in which all the upper triangular elements are zero. That is,
all the non-zero elements are on the main diagonal or in the lower triangle:

Input: (row, col, array elements)


3
3
1
1
1
2
2
2
3
3
3
Output:
Upper triangular matrix multiplication is:
108

Lab 23.4
Write a program to handle the user defined exception using throw keyword. Write a program that
deposits amount (int) in bank. If the amount is less than throw a user defined exception that display
“Invalid Amount”.
Input:
-500
Output:
Invalid Amount

Lab 23.5
Write a program that takes the size of and array and its elements and then displays the second largest
and smallest element in the array.
Input: (size, elements in array)
8
2
5
1
7
8
6
9
3
Output:
Second Largest:8
Smallest:1

Lab 24
Lab 24.1 start()
Define a class thread with the following characteristics:
a) It extends Thread class
b) It has a public method run() with return type void and no input argument.
c) Run method displays the string once the thread is started.
d) In the main, make an object of the class thread and initiate the start() to start the thread
and display the string input.

Input: (string)
Start method
Output:
Start method

Lab 24.3 Runnable Interface.


Create a Thread by implementing Runnable Interface with the following characteristics:
a) implement a run() method provided by a Runnable interface
b) instantiate a Thread object using constructor
c) Using the object call start() method, which executes a call to run( ) method
d) Use Thread.sleep(50) to make the tread sleep for a while.
e) Parallelly run the two threads (4 times) by taking two String input.

Note* Input and Output is given for further assistance.

Input: (String 1, String 2)


Test-1
Test-2
Output:
Creating Test-1
Starting Test-1
Creating Test-2
Starting Test-2
Running Test-1
Thread: Test-1, 4
Running Test-2
Thread: Test-2, 4
Thread: Test-1, 3
Thread: Test-2, 3
Thread: Test-1, 2
Thread: Test-2, 2
Thread: Test-1, 1
Thread: Test-2, 1
Thread Test-1 exiting.
Thread Test-2 exiting.

Lab 24.4
Multithreading in general does not guarantee the order of execution of threads. we can make
sure that the threads executes in a particular order By using join() method appropriately.
Write a program that does the same.
Create a class that implements Runnable Interface with the following characteristics:
a) implement a run() method provided by a Runnable interface
b) Create three threads th1, th2, and th3 and apply join() to execute all the three threads in
order (th1, th2 , th3).
While using join(), keep in mind the Exceptions (InterruptedException) That might get
generated and use try, catch block to handle it.

Input:
Output;
Thread started: th1
Thread ended: th1
Thread started: th2
Thread ended: th2
Thread started: th3
Thread ended: th3
All three threads have finished execution

Lab 24.5
Create a class Mythread with the following characteristics:
a) Mythread implements Runnable Interface
b) implement a run() method provided by a Runnable interface
c) instantiate two Thread objects using constructor having two different strings.
d) run the run method 5 times
e) Take care of the InterruptedException using try catch block.

Input:
hi
hello
Output:
Run method: hi
Run method: hello
Run method: hi
Run method: hello
Run method: hi
Run method: hello
Run method: hi
Run method: hello
Run method: hi
Run method: hello
Run method: hi
Run method: hello
Week 10
Lab 25
Lab01:116. Design a class Customer with following characteristics.

Member method:

int giveCupOfCoffee(int temperature)

• The method should check whether the coffee is too cold or too hot.
• The method throws exception TooColdException if coffee is cold (below 35).
• The method throws exception TooHotException if coffee is overly hot (over 60).
• Return 1 if coffee is at a perfect temperature.

Input
30

Output
Too Cold

Lab01:117. Check employee details with custom exception: Design a class Employee with
following characteristics.
Member variables

• String name – To store the name of an employee.


• int age – To store the age of an employee.

Member method

• void setName(String name) - The method should trigger an


exception InvalidNameException if the name is a number.

• void setAge(int age) - The method should trigger an exception InvalidAgeException if the
age is greater than 50.

Also, override toString method in a class to return name and age of employee separated by a single
space.

Input
300
57

where,

• First line represents the name of an employee.


• Second line represents the age of an employee.

Output
InvalidName
InvalidAge
Lab01:118. Given a string S, find the length of string and create and raise the custom
exception NotGoodLengthException” when the length of the string is less than 10.

Write a function
public int solution (String S) that accepts a string S. The function should return the length of string
or throw the NotGoodLengthException exception if the length is less than 10.

Input
Terminate

Output
NotGoodLengthException

Lab01:119. Create a class MyException with following characteristics.

Data members:

• int numbers[] – to store 10 integer numbers.


• Initialize the array with value 0.

setNumber(String index, String number) method

• This method sets the particular value at a specific index in an array.


• The method should throw ArrayIndexOutOfBoundsException exception if the index value is
less than 0 or greater than 9.
• Also, the method should throw IllegalArgumentException if a passed value is not
between −32,768 to 32,767.
• If number and index are valid, then set the number at given index of the array.

getNumber(String index) method

• This method gets a value at a specified index. It takes integer index as a parameter.
• The method should throw ArrayIndexOutOfBoundsException exception if the index value is
less than 0 or greater than 9.
• Also, the method should throw IllegalArgumentException if a passed value is not
between −32,768 to 32,767.
• If the index is valid, then return number at that index position.

Input
0 4 6 13 5
12 34 10 4 abc
0 4 6 13 5

where,

• First line represents indices for inserting values in the array.


• Second line represents values to be inserted in the array.
• Third line represents the index of an array for accessing values.
Output
java.lang.ArrayIndexOutOfBoundsException
java.lang.IllegalArgumentException
12
34
10
java.lang.ArrayIndexOutOfBoundsException
0

Lab 26
Lab02:109. Input Exception: create a class Person with the following characteristics:
private Data members:
• String name: Single word name i.e. first name
• int age,
• String Add: multi word address.

Methods:
• Parametrized constructor to initialize the data members.

Now takes the input using Scanner in the main method and assign the values to the data members using
constructor method of the Person class. Please only use the three methods i.e. next(), nextInt() and
nextLine() of the Scanner class to takes the input. You are not allowed to use any additional nextLine()
method while taking the input from the user.
Write an exception handling code for taking proper input from the user and showing proper message
using existing exception class and creating custom exception as shown in output to the user if there is
input mismatch or an input having null or empty (blank string) value.

Test case 1
Input:
Alok Gupta
45
Greater Noida

Output:
java.util.InputMismatchException

Test case 2
Input:
Alok
45
Greater Noida

Output:
Address is null
Lab02:110. Check Balance with custom Exception: create a class BankExeption along with the
following characteristics:
Private Member variables

• String name[] – To store the names of customer.


• double balance[] – To store the balance of respective customer.

Member method

• Parameterized constructor to initialize the data members.


• BankExeption(String str): parameterized constructor to call the contractor of Exception
class with the given string argument.
• Void display(): display the information of customer as shown in output. This method
display a custom exception i.e. BankExeption whenever balance amount is below Rs
1000. And display the message Balance is less than 1000.

Test case1

Input:
2
Nisha 1000
Abhi 999
Where, first line is the number of customer and second and third line represent the customer name and
his account balance.
Output:

Nisha 10000.0
Abhi 999.0
Balance is less than 1000

Test case 2

Input:
2
Abhi 999
Nisha 1000

Where, first line is the number of customer and second and third line represent the customer name and
his account balance.

Output:
Abhi 999.0
Balance is less than 1000

Lab02:111. NegativeNumberException custom exception: Given a number N, find the number


is positive, negative or zero. If the number is negative, then raised the custom exception
named NegativeNumberException.

Write a function
public int solution (int N)
that accepts an integer N. The function should return 1 if N is positive, 0 if N is 0 and throw
exception NegativeNumberException if N is negative.

Input
-10

Output
NegativeNumberException

Lab02:112. ArrayIndexOutOfBounds custom exception: Given an integer array of N size,


continuously access the array elements by generating the random indexes. If array index is out of
bound, then raised the custom exception named ArrayIndexOutOfBounds.

Write a function
public Boolean solution (int a[], int index) that accepts an integer array and index. The function
should return true if index is in the range of the size, false if index is not in range of the size and throw
exception ArrayIndexOutOfBounds.

Input
5

12345

Where, first line represents the size of the array and second line represents the array elements.

Output
Array Index is Out Of Bounds

You might also like