Java Labreports
Java Labreports
1. Assignment Number: 1
2. Problem statement: Write a Java method fact(int n) for computing factorial for small n
values within 20. Output should be displayed in whole integer format. Avoid writing a full
program / class or main() method or error handling for this simple program.
3. Class Diagram:
<No class name for this
program>
-n:int
-fact:long:1
-fact(n:long)
4. Logic:
Class name:<No class name>
Instance variables : n(int) , fact(long)
Method name : long fact()
1
7. Conclusion
- Error message should have been printed when value of n is less than 0.
- It can be done by using recursive function instead of loop to decrease its time complexity.
2
Lab report for assignment 2
1. Assignment Number: 2
3. Class Diagram:
m
+n:int
-max:int:0
-max1:int:0
4. Logic:
Class name : m
3
be 15
7. Conclusion
- Taking n as input.
- Assign max and max1 with 0.
- Checking if n equal to 0.If true then it displays “NA”, otherwise assign max and max1 with
n.
- Continuously taking input n until user enters 0.
- Checking if n greater than max.If true max is assigned to max1 and n assigned to max.
- If false then again we check n less than max and n greater than max1.If true then n is
assigned to max1.
- Then max1 is printed as our output.
-For example if we take two inputs as -1 and 0,then -1 is printed as our second maximum
element which is not correct .The answer should be 0.Here in my program 0 is taken as
terminating input .It is not considering 0 as input.
4
Lab report for assignment 3
1. Assignment Number: 3
2. Problem statement: Write a java program to take integer inputs for base and
exponent, Calculate power value without using Java math function .Negative integer inputs
are allowed.
3. Class Diagram:
po
+b(int)
+e(int)
+res(int)
void main(String args[])
4. Logic:
-If the exponent value is greater than 1 then the result is calculated and the resultant value is
stored in res.
-If the exponent value is negative then e is assigned as –e. Then the result is calculated and
the resultant value is stored in res .Then res is divided by 1 and stored in res itself.(eg. if the
value of b=3 and e=-2,then res=9,therefore res=1/res which is equal to res=1/9,so
res=0.11)
5
from the program
Error handling (for No error handling for this program.
preventing wrong
data processing)
7. Conclusion
We have thus been able to successfully accept base and exponent from user and display the
power value without using any inbuilt function.
6
Lab report for assignment 4
1. Assignment Number: 4
2. Problem statement: Write a Java program to input a number, and display the most
economic data type among byte, short, int and long for accommodating the number.
3. Class Diagram:
dt
+n(long)
4. Logic:
Class: dt
Instance variables: n
Member methods: void main(String args[])
if((byte)(n)==n)
System.out.print("byte");
else if((short)n==n)
System.out.print("short");
else if((int)n==n)
System.out.print("int");
else if((long)n==n)
System.out.print("long");
7
6. Test cases and results:
SL Test Case Expected Observed Status
Result Result
1 n = 17 byte byte Ok
2 n=512 short short Ok
7. Conclusion
Thus, we conclude from the given program is that when we are giving input a particular number, it
displays the most economic data type among byte, short, int and long.
We are successful in printing the correct data type for the variable, for example, if the input is 17 it is
showing “byte” as the output.
8
Lab report for assignment 5
1. Assignment Number: 5
3. Class Diagram:
M
+arr[](double)
+i(int)
+med(double)
+void main(String args[])
4. Logic:
Class: M
Instance variables: arr[](double) ,i(int), med(double)
Member methods: void main(String args[])
9
program
Expected Outputs med (double)
from the program
Error handling (for No error handling for this program.
preventing wrong
data processing)
7. Conclusion
We have thus been able to successfully accept array elements using hasNext() from user and
display the median.
10
Lab report for assignment 6
1. Assignment Number: 6
2. Problem statement: Calculate the area of various shape objects using dynamic time
polymorphism.
3. Class Diagram:
Shape
double area
void computeArea()
void displayShape()
4. Logic:
switch(sheetType)
case 1:
double r=sc.nextDouble()//Taking radius as input
Circle c=new Circle(r)//creating an object c of type circle and passing radius r.
c.computeArea()//computes area of shape circle.
return c.//returning the area.
case 2:
double l=sc.nextDouble()//Taking length as input
double b=sc.nextDouble()//Taking breadth as input
Reactangle rect=new Reactangle(l,b)//creating an object rect of type reacting
and passing l and b.
rect.computeArea()//computes area of shape rectangle
11
return rect.//returning the area
case 3:
double h=sc.nextDouble()//Taking height as input
double base=sc.nextDouble()//Taking base as input
Triangle t=new Triangle(h,base)//creating an object t of type triangle and
passing h and base value..
t.computeArea()//computes area of shape triangle
return t.//returns the computed area.
default:
--------
-----//prints message for invalid input.
2. Data members.
7. Conclusion
From this assignment we learnt about the use of polymorphism and various implementations
of it.
12
Lab report for assignment 7
1. Assignment Number: 7
2. Problem statement:Calculate area of various shape objects and sort them in ascending
order of there areas using polymorphism.
3. Class Diagram:
Shape
Circle
Rectangle
Triangle
Sheets
+ area
+ arr[]
-r
-l
-b
-h
-n
-i
-j
- sheetType
-s
- shape
- type
13
4. Logic:
Member methods : void main(String args[]), static Shape createShape(int n, Scanner x), void
computeArea(), void displayShape(), static void sortShapes(Shape Shapes, int n)
Logic applied in the program: Here we are rectifying the above given program thus the
logic of that portion is explained below:-
The idea is to the sort the shapes according to its area and printing it simultaneously in the
sorted manner(increasing order).
The sortShapes() method is used to sort the shapes in accordance to their area and here we
are swapping the objects of the classes(Circle/Rectangle/Triangle class) and thus the shapes
are getting sorted and the area can be printed as well with the help of their respective objects
which are being swapped to their correct positions.
14
6. Test cases and results:
7. Conclusion
The program is successful in printing the expected result/output. The above program can be
solved in a more optimized way by the use of some in-build functions of Java but this
program does not allow us to use any sort of in-build functions. Only the missing part is
being written.
15
Lab report for assignment 8
1. Assignment Number: 8
2. Problem statement: Write a Java program to evaluate a postfix expression. You may use
stack-based solution with array implementation.
3. Class Diagram:
Test
-s
-c
- val1
- val2
-i
4. Logic:
Class : Test
The idea is to push the operator inside a stack and pop the operators according to their
precedence. This program uses simple implementation of stack for storing and an array is
used to store the expression and traversing the array along with conditions
First we are taking the postfix expression as string.Then removing all the spaces present in
the expression.Creating stack object.Then taking character input as c.Checking whether it is
digit or not.Then takimg two input variables s val1 and val2.Using switch case and applying
desired operation.With the help of pop() operation from stack, we get the evaluated
expression.
16
Inputs for the char c (character)
program
Expected Outputs The computed value
from the program
Error handling (for No error handling for this program.
preventing wrong
data processing)
7. Conclusion
The program is successful in printing the expected result/output. We learnt how to use in-
build stack class.This program uses the in-build stack class for easy implementation.
17
Lab report for assignment 9
1. Assignment Number: 9
2. Problem statement: Write a Java program to input couple of numbers and sort so that
even numbers are in even positions and odd numbers are in odd positions. While displaying
the numbers, replace missing numbers with "X".
3. Class Diagram:
SORT
-n
- idl
- arr[]
- index
4. Logic:
Class : evenOdd
Logic applied in this program: The idea is that at first the input array is sorted and then
inside a new array the final output is been stored.
We are checking for a condition where the input number is even but it is at odd position thus
we shift its position by 1 that is to an even position. Similarly for the odd number we do just
the opposite thing.
Now we stored the numbers after doing the above modifications in a separate array and
finally printing it whenever a number(input value) is been encountered otherwise it will print
‘X’.
18
5. Inputs, Outputs and Error handling:
Inputs for the arr[](int)
program
Expected Outputs arr.get()
from the program
Error handling (for No error handling for the program.
preventing wrong
data processing)
7. Conclusion
The program is successful in printing the expected result/output. The program uses the in-
build function sort of the Array class and this program can be solved in another way by
simply checking whether or not the elements are in their correct position and printing it
otherwise print “X” and print the remaining elements.
19
Lab report for assignment 10
1. Assignment Number: 10
2. Problem statement: Input a number, Calculate the sum of square using interface.
3. Class Diagram:
--
+findSqr(int ) : int
4. Logic: We override the function findSqr() of Number interface from A class, and make it
so that passing a number to findSqr() returns the square value of that number.
7. Conclusion
Thus, we have been able to successfully calculate square of a number using interfaces.
20
Lab report for assignment 10
1. Assignment Number: 10
2. Problem statement: Write a Java program for dealing with different type of forms
3. Class Diagram:
FormGen
+base : String
+display1() : void
+display2() : void
4. Logic: In this program no such logic is implemented. Only two methods have been
declared and subsequent print statements have been written.
7.Conclusion
Thus, we have been able to successfully use interfaces and their overriding functionalities.
21
Lab report for assignment 11
1. Assignment Number: 11
2. Problem statemet: Write a Java program to input n and add n number of integers. In case
of InputMismatchException, display "ERROR".
3. Class Diagram:
Add
--
+main(args :
String[]) : void
4. Logic: Inside the try block, we calculate the sum of the n inputted numbers. If any non-
integer is encountered, an appropriate message is displayed from the catch block.
7. Conclusion
Thus, we have been able to successfully calculate sum of n numbers with adequate error
handling using try-catch blocks.
22
Lab report for assignment 12
1. Assignment Number: 12
2. Problem statement: Complete the below program for displaying as "Running thread":
public class SimpleThread extends Thread {
???
public static void main(String args[]) {
SimpleThread st = new SimpleThread();
st.start();
}
}
3. Class Diagram:
SimpleThread
--
+main(args : String[]) :
void
+run( ) : void
4. Logic: The run() method is defined by us to print the desired output for the running
thread.
7. Conclusion
We have thus successfully used Threading in this program by the proper usage of run()
method.
23
Lab report for assignment 12
1. Assignment Number: 12
3. Class Diagram:
ThreadRun
--
+run( ) : void
4. Logic: We have to write a class ThreadRun which implements Runnable interface and has
run() method in which we just print Runnable. This class is used and instantiated in main
class Demo(defined in question) and the thread is started there itself.
24
SL Test Case Expected Observed Status
Result Result
1 -- Runnable Runnable OK
7. Conclusion
We have thus successfully used the concept of Runnable in a Thread related program.
25
Lab report for assignment 12
1. Assignment Number: 12
2. Problem statement: Complete the below program for displaying as "Running thread":
public class SimpleThread extends Thread {
???
public static void main(String args[]) {
SimpleThread st = new SimpleThread();
}
}
3. Class Diagram:
SimpleThread
--
+void run()
7. Conclusion
We have thus successfully used the concept of Threading via the concept of Inheritance.
26
Lab report for assignment 13
1. Assignment Number: 13
2. Problem statement: Display square root of first 300 natural numbers using multi-
threading. Use 3 thread objects and ensure to log start and completion of all threads including
main thread. Main thread should equally divide problem space among 3 threads: (1,4,7,...),
(2,5,8,...), (3,6,9,...). Please ensure to display source thread name while displaying the
square root value (upto 4 decimal places) for a number. You should not use any sleep()
statement under main or individual threads. Ensure to terminate threads before leaving the
program. You may use Math.sqrt() built-in method for calculating the square root of a
number.
3. Class Diagram:
MyThread
graph
thd : Thread
--
pos : int
+main(args: String[ ]) :
void +run( ) : void
4. Logic: In constructor of class graph which implements Runnable, is instantiated with this
Runnable interface with the thread name passed in parameters. Then, we start this th thread.
In run method, we find square root of 300 numbers passed for this thread. We print that
square root.We print Starting Main Thread, and loop 300 times from i =0 to 299.Name of
thread is printed in main method.
If there is any exception it is handled in catch block. Lastly, Closing main thread is printed.
27
6. Test cases and results:
SL Test Case Expected Result Observed Result Status
1 -- Starting main thread Starting main thread OK
Starting Thread 1 Starting Thread 1
[Thread 1] Number : 1 [Thread 1] Number : 1
Square Root : 1.0000 Square Root : 1.0000
Starting Thread 2 Starting Thread 2
Starting Thread 3 Starting Thread 3
[Thread 1] Number : 4 [Thread 1] Number : 4
Square Root : 2.0000 Square Root : 2.0000
[Thread 2] Number : 2 [Thread 2] Number : 2
Square Root : 1.4142 Square Root : 1.4142
....... .......
Closing Thread 1 Closing Thread 1
...... ......
Closing Thread 2 Closing Thread 2
Closing Thread 3 Closing Thread 3
Closing main thread Closing main thread
7. Conclusion
The join method and some multithreading concepts are required.
28