0% found this document useful (0 votes)
25 views

Java

The document discusses Java programs to display default values of data types, find roots of quadratic equations, display the Fibonacci sequence, demonstrate command line arguments, and sort a list of numbers. It provides the aim, description, algorithm and sample output for each program.

Uploaded by

giridhar chikka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Java

The document discusses Java programs to display default values of data types, find roots of quadratic equations, display the Fibonacci sequence, demonstrate command line arguments, and sort a list of numbers. It provides the aim, description, algorithm and sample output for each program.

Uploaded by

giridhar chikka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

1

JAVA LAB MANUAL

EXERCISE 1

AIM: A java program to display the default value of primitive data types of java.

DESCRIPTION:

It's not always necessary to assign a value when a field is declared. Fields that are
declared but not initialized will be set to a reasonable default by the compiler. Generally
speaking, this default will be zero or null, depending on the data type. Relying on such default
values, however, is generally considered bad programming style.

ALGORITHM:
1. Create a class EmployeeDetails
2. Create a method getEmployeeDetails()
Print all the initialized variables
end of method
3. Create a method getCollegeDetails()
Print some information
end of method
end of class
4. Create another class Employee
5. Create main method
Create instance for EmployeeDetails class
Using the instance call the above methods
end of class

OUTPUT:

E:\>javac EmployeeDetails.java
E:\>java EmployeeDetails
0

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


2

JAVA LAB MANUAL

Null
0.0
False

CONCLUSION:
Getting default values is the way to understand memory allocation strategies and maps to
CO2 and attains with PO1, PO2, PO3, PO4, PO12, PSO1, PSO3.

VIVA QUESTIONS:
1. What are the primitive data types?
2. What are default values for different data types?
3. What are the non primitive data types?
4. Why char has 2bytes of storage?
5. What is Unicode?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


3

JAVA LAB MANUAL

EXERCISE 2
AIM: A java program that displays the roots of quadratic equation ax2+bx+c=0 and Calculating
the discriminate D to describe the nature of roots.

DESCRIPTION:
The Quadratic Formula. The quadratic equation

Have the solutions

ALGORITHM:

1. Create a class and give implementation to read(), getDet(), and getRoots()

2. Using sqrt() calculate roots

3. create main class and create an instace to above class

4. Call methods using instance.

OUTPUT:
E:\java 2>javac QuadraticImpl.java
E:\java 2>java QuadraticImpl
enter a,b,c values
121
Roots are equal
r1=r2=-1.0

E:\java 2>javac QuadraticImpl.java


E:\java 2>java QuadraticImpl

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


4

JAVA LAB MANUAL

enter a,b,c values


153
Roots are real and distrinct
r1 = -0.6972243622680054 r2 = -4.302775637731995

E:\java 2>java QuadraticImpl


enter a,b,c values
122
Roots are imaginary

CONCLUSION:
Understands the way to formulate Mathematical functions through programming and
maps to CO2 and attains with PO1, PO2, PO3, PO4, PO12, PSO1, PSO3.
.

VIVA QUESTIONS

1. What is the Scanner class? Explain

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


5

JAVA LAB MANUAL

EXERCISE 3

AIM: A java program to display the Fibonacci sequence

DESCRIPTION:
In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the
numbers in the following integer sequence:

By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent
number is the sum of the previous two.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence
relation

With seed values

Here is a simplest Java Program to generate Fibonacci Series.

ALGORITHM:
1. Create a class Fib()

2. Create a method read()

read n value

end of method

3. Create another method fib(int f1,int f2)

print the first two values of the Fibonacci series

Repeat for i = 0 to n

temp = f1 + f2

print temp

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


6

JAVA LAB MANUAL

f1 = f2

f2 = temp

end of method

end of class

4. Create another class Fibonacci()

5. Create main method()

Create an instance for Fibonacci class

Call the above methods using the above instance

end of class

OUTPUT:
E:\java>javac Fibonacci.java
E:\java>java Fibonacci
enter n
8
011 2 3 5 8 13

CONCLUSION:
Understands the way to use Recursion functions through programming and also
implement Stack Operations and maps to CO2 and attains with PO1,PO2,PO3,PO4, PO12,
PSO1, PSO3.

VIVA QUESTIONS
1. What is the Fibonacci Sequence?
2. What are the control statements in java ?
3. What is the Dynamic Initialization in java
4. Can we use recursion in java?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


7

JAVA LAB MANUAL

EXERCISE 4
AIM: Write a java program to give example for command line arguments

DESCRIPTION:

The java command-line argument is an argument i.e. passed at the time of running the java
program. The arguments passed from the console can be received in the java program and it can
be used as an input. Command line arguments represent the values passed to main() method.
Here, args[] is one dimensional array of String type. So it can store a group of strings, passed to
main() from outside by the user i.e, at the time of running the program.

The prototype of main( ) when it supports command line arguments is as follows:

public static void main(String[] args)

ALGORITHM:

1 Create a class CommandLine

2 Create a method converting(String[] values)

Repeat for I = 0 to n

Convert all the string values to integer type

Print sum

end method

end class

3 Create a class Command

4 Create main method()

Create an instance for the CommandLine class

using instance call the above methods

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


8

JAVA LAB MANUAL

OUTPUT:
E:\java>javac Command.java
E:\java>java Command 20 45 37 19
20 45 37 19
the sum is:121

CONCLUSION:
Implements the usage of arguments passing into Program that renders student to
understand command line arguments and maps to CO2 and attains with PO1,PO2,PO3,PO4,
PO12, PSO1,PSO3.
.

VIVA QUESTIONS:
1. What is command line argument?
2. What is the prototype of main( ) when command line arguments are supported.?
3. Function to convert string to integer?
4. Default type of values which are reading through command line?
5. Can we run java program without String[] args why?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


9

JAVA LAB MANUAL

EXERCISE 5
AIM: Write a java program to sort given list of numbers

DESCRIPTION:
The algorithm works by comparing each item in the list with the item next to it, and
swapping them if required. In other words, the largest element has bubbled to the top of the
array. The algorithm repeats this process until it makes a pass all the way through the list without
swapping any items

ALGORITHM:
1. Create a class EmployeeData
2. Create a method setEmployee()
Print employee details
end of method
3. Create another method sortEmployee()
Sort and print the employee details based on their salaries
end of method
end of class
4. Create another class SortinngEmloyee
5. Create main method()
Create object for the above class
Call all the above methods using the object
end of method
end of class

OUTPUT:
E:\java>javac SortingEmployee.java
E:\java>java SortingEmployee
Enter details:
james e20 50000
Enter details:
peter e30 40000
Enter details:
gosling e22 25000
gosling

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


10

JAVA LAB MANUAL

peter
james

CONCLUSION:
Student Better understand the way of sorting data with text processing into sorted records
and maps to CO2 and attains with PO1,PO2,PO3,PO4, PO12, PSO1,PSO3.

VIVA QUESTIONS:

1. What is sorting? What are the different sorting techniques?


2. How do you find length of an array?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


11

JAVA LAB MANUAL

EXERCISE 6

AIM: Write a java program to search for an element in a given list of elements (Linear Search)

DESCRIPTION:

Linear search is one of the basic search techniques that we've now. Although this is not a
very good search technique, one should understand this concept. Let's consider our aim to search
for a key element in an array of elements. We loop through all the array elements and check for
existence of the key element. Since we go element by element, this search is called as linear
search or sequential search. Search element is called as key element.

ALGORITHM:

1. Import package

2. create class and declare the array of elements

3. declare the method and perform linear search in which key element is compared with each
element in the array

4. if the key element is found then print success otherwise print failure

5. end method

6. end class

7. create another class and declare main method

8. create an object for the first class

9. end class

10. stop

OUTPUT:
E:\java>javac SearchEmployee.java

E:\java>java SearchEmployee

enter details peter 3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


12

JAVA LAB MANUAL

enter details james 2

enter details gosling 1

enter keyId

2 is present at 2 james

CONCLUSION:
Searching concept mitigates for student to get analogy of optimal searching of object in
real time and maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.
.

VIVA QUESTIONS:
1. What is the Searching? Explain Search techniques in java?
2. What is the time complexity for Linear Search? Explain?
3. If element is not present in the given elements then what is time complexity?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


13

JAVA LAB MANUAL

EXERCISE 7

AIM: Write a java program to search for an element in a given list of elements (Binary Search)

DESCRIPTION:

Generally, to find a value in unsorted array, we should look through elements of an array one
by one, until searched value is found. In case of searched value is absent from array, we go
through all elements. In average, complexity of such an algorithm is proportional to the
length of the array. Situation changes significantly, when array is sorted. If we know it,
random access capability can be utilized very efficiently to find searched value quick. Cost
of searching algorithm reduces to binary logarithm of the array length. For reference, log 2 (1
000 000) ≈ 20. It means, that in worst case, algorithm makes 20 steps to find a value in
sorted array of a million elements or to say, that it doesn't present it the array.

Note: Elements should be in sorted order in the given array

ALGORITHM:

1. start

2. import package

3.create a class declare the array of elements

4. declare the method and perform binary search in which the mid value of the array is calculated
and if the key value is less than the mid value then key is searched in the first part of the array
otherwise it is searched in second part of the array

5. print success if key is found otherwise print failure

6. end method

7. end class

8. create another class and declare the main method

9. create a object for the first class and call the method

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


14

JAVA LAB MANUAL

10. end class

11. stop

OUTPUT:

E:\java>javac SearchEmp.java

E:\java>java SearchEmp
enter details
james 3
enter details
peter 1
enter details
gosling 2
Enter key
2
2 found at location 2 gosling

CONCLUSION:
Searching concept mitigates for student to get analogy of optimal searching of object in
real time and maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS
1. What is the Time complexity of Binary Search? Explain?

2. What is the purpose to calculate mid value in Binary search?

3. How we can differentiate binary search with linear search?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


15

JAVA LAB MANUAL

EXERCISE 8

AIM: Write a java program to determine the addition of two matrices.

DESCRIPTION:
This code adds two matrixes you can modify it to add any number of matrices. You
can create a Matrix class and create it's objects and then create an add method which sum the
objects, then you can add any number of matrices by repeatedly calling the method using a loop.

ALGORITHM:

1: start

2: import package

3: create a class and declare the 3 matrices say a[][],b[][],c[][]

4: declare a method and perform the addition on the matrix a and b and assign it to matrix c

5: print the matrix c

6: end class and the method

7: create another class and declare main method

8: create an object and call the method of the first class

9: end class

10: stop

OUTPUT:
E:\java>javac MatrixImpl.java
E:\java>java MatrixImpl
enter m,n
22
enter matrix 1 elements

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


16

JAVA LAB MANUAL

2463
enter matrix 2 elements
7356
matrix 1:
24
63
matrix 2:
73
56
addition of matrices:
sum is
97
11 9

CONCLUSION:
Student able to understand implementation of matrices for mathematical methods using
different real time examples and maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. What is an Array? How do you define two dimensional arrays in java?
2. How we can print two dimensional array as matrix format?
3. What is the transpose of given matrix?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


17

JAVA LAB MANUAL

EXERCISE 9
AIM: Write a java program to determine the multiplication of two matrices

DESCRIPTION:

Let the two matrix to be multiplied be A and B. Let A be a matrix of order d*e - d rows
and e columns and B be the second matrix of order e*f. Note that the number of columns in the
first matrix should be the same as the number of rows in the second matrix. The product matrix
will be of order d*f. Now, our task is to find what numbers go into each of the positions of
matrix C with d rows and f columns. We use an outer loop with loop counter i ranging from 0 to
d. An inner loop has the loop counter j ranging from 0 to f. At any iteration of the loop, i refers to
the row number and j to the column number of the position in matrix C that we are trying to fill.
Now, within the body of the inner loop, we have to write some code which will calculate the
value to be filled. This body will in turn consist of a loop. When we are obtaining the value at
C[i][j], row i of matrix A and column j of matrix B are multiplied element wise.
C[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j] + A[i][2] * B[2][j] + .... A[i][e-1] * B[e-1][j]

Both row i and column j have e elements. An loop is used whose counter k, ranges from 0 to e-1.
Within the loop, A[i][k] and B[k][j] are multiplied and the product obtained is added to the
existing value of C[i][j]. We can also declare a variable sum before the start of the innermost
loop, add the element wise products to this variable and assign the resulting sum to C[i][j].

ALGORITHM:

1. start

2. import package

3. create a class and declare the 3 matrices say a[][],b[][],c[][]

4. declare a method and perform the multiplication on the matrix a and b and assign it to matrix
c

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


18

JAVA LAB MANUAL

5. print the matrix c

6. end class and the method

7. create another class and declare main method

8.create an object and call the method of the first class

9. end class

10. stop

OUT PUT:
E:\java>javac MatrixMul.java
E:\java>java MatrixMul
enter m,n
22
enter matrix 1 elements
4234
enter matrix 2 elements
6234
matrix 1:
42
34
matrix 2:
62
34
multiplication of matrices:
multiplication is
30 16
30 22

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


19

JAVA LAB MANUAL

CONCLUSION:

Student able to understand implementation of matrices for mathematical methods using


different real time examples and maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:

1. What is an Array? Explain Types of Arrays?


2. How do you Initialize Arrays?
3. What is the complexity of matrix multiplication?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


20

JAVA LAB MANUAL

EXERCISE 10
AIM: Write a java program to sort an array of strings.

DESCRIPTION:
Strings in java are immutable in nature. Immutable means we cannot change the String objects.
Strings are collection of characters, used to perform different pattern matching operations. Here
we have compareTo() method to check strings. If two strings are equal then it will return 0 , if
first string is greater than second one then it will return positive number otherwise negative
number
ALGORITHM:
1.start

2. import required package

3.create a class and declare the array to sort

4.create a method and sort the array by using one of the sorting technique and print the new
array that is sorted

5. end method

6. end class

7. create another class and declare the main method

8.create the object for the first class

9. call the method using the object created above

10. end class

11. stop

OUTPUT:
E:\java>javac SortingEmployeeNames.java

E:\java>java SortingEmployeeNames

Enter details:

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


21

JAVA LAB MANUAL

ram e10 60000

Enter details:

krish e20 40000

Enter details:

sai e3 50000

krish

ram

sai

CONCLUSION:

Student able to understand implementation of storing elements into static and dynamic
array allocation and maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS

1. Is array in java a object or primitive?

2. Is java string object is mutable or immutable?

3. What is compareTo() method? what are the values return by this method?

4. What are the methods related to String class?

5. What is charAt(position) method?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


22

JAVA LAB MANUAL

EXERCISE 11

AIM: Write a java program to check whether the given string is palindrome or not.

DESCRIPTION:
Palindrome is the string pattern, which is same as the string when it is reversed. To
reverse the string we have reverse() in StringBuffer class. StringBuffer class objects are
mutable(can be manipulate) where String class objects are immutable.

ALGORITHM:
1. Create a class and write a method to check palindrome
2.Using charAt(int) findout reverse string
3. check reverse string with original string using equals()
4. Create an instace to above class
5. Call method using instance.

OUTPUT:

D:\JAVA\java 2>javac palindrome.java

D:\JAVA\java 2>java palindrome

enter string

madam

string is palindrome

CONCLUSION:

Student able to understand implementation of text processing and its methodologies and
maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


23

JAVA LAB MANUAL

VIVA QUESTIONS:
1. What is palindrome?
2. How to replace characters in strings?
3. What is the use of toString()?
4. What is the meaning of mutable objects?
5. Is StringBuffer object called mutable or immutable?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


24

JAVA LAB MANUAL

EXERCISE 12
AIM: Write a java program for the following
Example for call by value
Example for call by reference.

DESCRIPTION:
Java supports call by value by passing a value and returning the value. Call by reference
is way of passing object into setter method and returning object as type. Steps to call are:

1. Create a object which contains setters and getters.


2. Use the above object into implementation class and pass Object as a parameter into
method and also pass any primitive value into method.
3. Return the value and Object as return types.

ALGORITHM:

1. Read the Object: Object o

Read the value : int i;

2. Pass above into method:

Method(o,i)

3. Return the values and process.


4. End;

INPUT AND OUTPUT:

Javac Calls.java

Java Calls

Madhu CSE1 Vizag Adarshanagar

CONCLUSION:
Able to understand the usage of functions to pass value and address that achieves Method
area in Java Virtual Machine and maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.
Viva-Voce Questions
1. How to pass an object as a parameter into a setter method?
2. What are setters and getters?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


25

JAVA LAB MANUAL

EXERCISE 13
AIM: Write a java program to give the example for “this” operator and also use the ‘this’
keyword as return statement.

DESCRIPTION:

Java supports ‘this’ object in order to process: Current class properties, Current class methods
and Current class Constructors. Bydefault this reference will be created when an object is
created. Refer present class members as follows:

Variablethis.varible_name;

Methodsthis.method_name();

Constructorthis(parameter_list);

ALGORITHM:
1. Create a class and write two constructors
2. Using this(string) pass value to parameterized constructor.
3. Create a method and initialize eid,ename,designation
4. Print details with printEmployeeDetails()
6. using instace set salary and call methods.

OUTPUT:

D:\JAVA\java>javac Employee.java

D:\JAVA\java>javac Salary.java

D:\JAVA\java>javac EmployeeImpl.java

D:\JAVA\java>java EmployeeImpl

lendi

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


26

JAVA LAB MANUAL

enter id,name,designation

e10 james professor

enter basic,da,hra

20000 300 4000

id=e10 name=james designation=professor

totalsalary=24000.0

CONCLUSION:

Illustrating usage of object implementation and analyzing the functionalities of object by


introspecting them. And maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS:

1. What is the use of this object?


2. How to call current class constructor using this?
3. How this reference will be created?
4. what are the members referred by this?
5. can we call present class constructor from any where from the program except through
constructor?why?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


27

JAVA LAB MANUAL

EXERCISE 14

AIM: Write a java program to demonstrate static variables, methods, and blocks.

DESCRIPTION: Static Keyword in Java is used to access the data without creating Object.
Also static creates the single memory allocation for all Objects. Static method can accept only
static variables. Static block has height priority than static methods(even there is main) as well as
instance methods.

ALGORITHM:

1. Write a static block and read userid and passwoed

2. Write a method checkValidity()

Check userid and password with concert arrays

If userid and passwords are available result is success

Otherwise failed

3. call checkValidity() with class name.

OUTPUT:

D:\JAVA\java-1>javac Validity.java

D:\JAVA\java-1>javac Login.java

D:\JAVA\java-1>java Login

enter details

enter username

navya nav

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


28

JAVA LAB MANUAL

enter password

validity is success

D:\JAVA\java-1>java Login

enter details

enter username

navya n

enter password

failed

CONCLUSION:

Student Understands the usage of static in programming, that relates to memory,


instantiation and accessing of data. And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:

1. Which of the static content have highest priority?


2. What is difference between static and initializer block?

3. Can we execute java program using static block without main()? Explain how?

4. Explain priorities of static blocks?

5.How we can call static methods?

6. Why static methods does not access instance variables?

7. What is the difference between static and instance variables?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


29

JAVA LAB MANUAL

EXERCISE 15

AIM: Write a java program to give the example for ‘super’ keyword

DESCRIPTION:
Reusability is very important feature in Inheritance, where accessing base class properties and
methods is needed. Super keyword is such object which do the job, by handling the super class
properties, methods and constructors. Invoking super keyword can be done in following way:
Variablesuper.variable_name;

Methodssuper.method_name();

Constructorsuper(parameter_list);

ALGORITHM:

1. Create a class named Employee

2. Extends Faculty class from Employee class

3. Aceess members of super class using super keyword

super.variablename;

super.methodname();

super(parameter list)

3. Create an instance to sub class called Faculty and access members using instance

OUTPUT:

D:\JAVA\java-1\simple>javac Employee.java

D:\JAVA\java-1\simple>javac Faculty.java

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


30

JAVA LAB MANUAL

D:\JAVA\java-1\simple>javac EmployeeImpl.java

D:\JAVA\java-1\simple>java EmployeeImpl

lendi institute of engg & technology

Enter eId, eName, desg:

e10 james professor

EID=e10 ENAME=james DESG=professor

CONCLUSION:

Parent and child relationship between objects to analyze object oriented features. And
maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS
1. How to call super class constructor?
2. Can I Use super inside static method?
3. What is the use of super?
4. Why should call super class constructor as a first statement in sub class constructor?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


31

JAVA LAB MANUAL

EXERCISE 16

AIM: Write a java program that illustrates simple inheritance

DESCRIPTION:

Inheritance is way to generate “IS-A” relationship between Parent and Child by accessing the
properties and methods. It increases readability and reusability of code. It can be implemented in
many ways like Simple, Multi-level, Hybrid.

ALGORITHM:

1. Create a class named Employee

Declare members like eId,eName,desg and write a constructor

2. Extends Faculty class from Employee class

3. Aceess members of super class using super keyword

super.variablename;

super.methodname();

super(parameter list)

4. Create an instance to sub class called Faculty and access members using instance

OUTPUT:
D:\JAVA\java-1\simple>javac Employee.java

D:\JAVA\java-1\simple>javac Faculty.java

D:\JAVA\java-1\simple>javac EmployeeImpl.java

D:\JAVA\java-1\simple>java EmployeeImpl

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


32

JAVA LAB MANUAL

lendi institute of engg & technology

Enter eId, eName, desg:

e10 james professor

EID=e10 ENAME=james DESG=professor

CONCLUSION:

Java reusability is main feature that implements the readability of the application and
illustrating real time scenarios. And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3
VIVA QUESTIONS:
1. What is reusability?

2. What is the use of extends keyword?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


33

JAVA LAB MANUAL

EXERCISE 17

AIM: Write a java program for multi level inheritance?

DESCRIPTION:

Inheritance is one way of implementing super-sub class relationship, for data usability and
readability. Implementing Multi-level inheritance is better one for Objects whose data will be
accessed by many objects there by increasing readability.

CLASS A

CLAS B

CLASS C

ALGORITHM:

1. Create a class named Employee

2. Extend Faculty class from Employee class

3. Extend Professor class from Faculty class

3. Aceess members of super class using super keyword

super.variablename;

super.methodname();

super(parameter list)

4. Create an instance to sub class called Professor and access members of both Faculty and
Professor using instance

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


34

JAVA LAB MANUAL

OUTPUT:
D:\JAVA\java-1\simple>javac Employee.java

D:\JAVA\java-1\simple>javac Faculty.java

D:\JAVA\java-1\simple>javac Professor.java

D:\JAVA\java-1\simple>javac EmployeeImpl.java

D:\JAVA\java-1\simple>java EmployeeImpl

Lendi Inst of Engineering and Technology CSE Dept

Enter eId, eName, desg:

e10 peter professor

EID=e10 ENAME=peter DESG=professor

CONCLUSION:

Interrelating multiple objects by using the feature of inheritance and enveloping them into
a single real world object .And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. Can java implement multiple inheritance? Explain?
2. What is abstract class?
3. Can we create an instance to abstract class?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


35

JAVA LAB MANUAL

EXERCISE 18

AIM: Write a java program to differentiate method overloading and overriding?

DESCRIPTION:

Polymorphism is foremost concern in java to implement methods behaviour in class and in one
or more classes. Having one or forms for the desire of data sharing. Overloading is the one,
whose methods have same name but different type signatures. Type promotion is supported in
Overloading.

Overriding on the other hand, methods with same name and parameters in more than one class
which are of ‘IS-A’ relationship.

ALGORITHM:

1. Create a class EmployeeDetails

2. Write methods called called showDetails(), showDetails(String)

3.Extend Faculty class from EmployeeDetails

4.Write a showDetails() in Faculty class and override it

5.Create an instance to Faculty class and call members of both classes

OUTPUT:
D:\java>javac MethodOver.java

D:\java>java MethodOver

Peter

e20

31/may/1991

25

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


36

JAVA LAB MANUAL

50000.0

CONCLUSION:

Polymorphic objects play a major role to interpolating multiple features into single object
inorder to inculcate and analyze the nature of object. And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. Can we overload method using return type?
2. What is type promotion in overloading?
3. What is method overriding?
4. Differentiate both method overloading and overriding?
5. What is final keyword?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


37

JAVA LAB MANUAL

EXERCISE 19

AIM: Java program to differentiate method overloading and constructor overloading.

DESCRIPTION:
This program describes the difference between method overloading and constructor loading.
Method overloading is a feature that allows a class to have two or more methods having same
name, if their argument lists are different. Constructor overloading that allows a class to have
more than one constructor having different argument lists. When overload method is called, java
looks for a match between the arguments used to call the method and the method parameters.
Finally it matches and displays the output.

ALGORITHM:

1. Create a class EmployeeDetails

2. Write methods called called showDetails(), showDetails(String) and make method overloading

3. Write two constructors and make constructor overloading-EmployeeDetails(),


EmployeeDetails(int,double)

4. Create an instance and call members called constructors and methods.

OUTPUT:
D:\java>javac MethodOver.java

D:\java>java MethodOver

James

e10

31/may/1991

25

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


38

JAVA LAB MANUAL

50000.0

CONCLUSION:

Polymorphic objects play a major role to interpolating multiple features into single object
inorder to inculcate and analyze the nature of object. And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1.What is method overloading?
2.What are the types of constructors?
3.What is constructor overloading?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


39

JAVA LAB MANUAL

EXERCISE 20

AIM: Write a JAVA program that describes exception handling mechanism.

DESCRIPTION:

Exception is the run time error. It will be raised at run time. The exception handling in java is
one of the powerful mechanism to handle the runtime errors so that normal flow of the
application can be maintained.
Checked exceptions − A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored at
the time of compilation, the programmer should take care of (handle) these exceptions.
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

ALGORITHM:
1. Import required packages.
2. Create a class called ExceptionDemo
3. Read values called sId,sName
4. Check two run time errors called StringIndexOutOfBounds and NullPointerException
5. Place statements in try block
6. Catch runtime errors usind catch block and print message

OUTPUT:
Enter Id and Name:
12KD1A0501
Ravi
The student named RAVI is from CSE Dept

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


40

JAVA LAB MANUAL

Enter Id and Name:


12KD1A0
Raj
Invalid Roll No

CONCLUSION:

Handling errors is major role in application programming to achieve bug free and fixing
errors at runtime. And maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. What is an exception?
2. What is the functionality of catch and finally blocks?
3. What is the difference between throw and throws?
4. What is multiple catch block?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


41

JAVA LAB MANUAL

EXERCISE 21

AIM: Write a JAVA program for example of try and catch block. In this check whether the
given array size is negative or not.

DESCRIPTION:
Program explains exceptions using try and catch block. In the try block array is created. Check
the array size is negative or not. If the array size is positive then it will be display array size
otherwise it throws an error like java.lang.NegativeArraySizeException.

ALGORITHM:

1:start
2: create class1
declare a parameterized constructor in which assign variable msg to str
declare a method ()
read size of array and declre array

then print array


place above two statements in try block as exception may occur if array size is negative
Exception is handled.
declare catch block for negativeArraySizeException and print message

end method()
end class
3.declare main class
give main method as public static void main(String[] args)
create object to class 1
call method declared in class 1 using object.
end main()

end class
4.stop

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


42

JAVA LAB MANUAL

OUTPUT:
Enter the size:
-3
Array Size is Negative..

CONCLUSION:

Handling errors is major role in application programming to achieve bug free and fixing
errors at runtime. And maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. What are the different types of exceptions used in catch block?

2. What is the use of try block?

3. What is the NegativeArraySizeException class?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


43

JAVA LAB MANUAL

EXERCISE 22

AIM: Write a JAVA program to illustrate sub class exception precedence over base class.

DESCRIPTION: In multiple catch blocks exception classes order should be from sub classes to
super classes.
Try
{//body
}
Catch(FileNotFoundException f){}
Catch(EOFException e){}
Catch(IOException i){}
ALGORITHM:

1.start
2.create class 1 extending from Exception base class.
declare a constructor for class1 through which constructor of base class is called.

end class 1.
3.create class 2
write a method and place the statements of exception in try block.
write multiple catch blocks for exceptions occurred, give precedence to subclasses first
and then base class Exception.
print the message using getMessage() method.
end class2.
4.declare main class
give main method as public static void main(String[] args)
create object to class 2
call method declared in class 2 using object.

end main()

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


44

JAVA LAB MANUAL

end class
5. stop

OUTPUT:
lendi cse dept

CONCLUSION:

Handling errors is major role in application programming to achieve bug free and fixing
errors at runtime. And maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. What is an exception?
2. What is the functionality of catch block?
3. What is the use of multi catch block?
4. what is sub class exception precedence over base class explain with example?
5. What is super class of all exception classes?
6. What is difference between checked and unchecked exceptions?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


45

JAVA LAB MANUAL

EXERCISE 23

AIM: Write a JAVA program for creation of user defined exception.

DESCRIPTION: If you are creating your own Exception that is known as custom exception or
user-defined exception. Java custom exceptions are used to customize the exception according to
user need.

By the help of custom exception, you can have your own exception and message.

ALGORITHM:

1.start
2. create a class 1 that extends from Exception base class .
declare a constructor that calls super class constructor.

write a method and place the statements of exception in try block.


throw the exception from try block.
write a catch block that prints message of exception.
end class
3.create main class
give main method as public static void main(String[] args)

create object to class 1and call method in previous class.


4.end main class.
5. stop.

OUTPUT:
Enter employee EID to find:
e7
Employee Missing..

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


46

JAVA LAB MANUAL

CONCLUSION:

Handling errors is major role in application programming to achieve bug free and fixing
errors at runtime. And maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1. What is mean by user defined exception?
2. What is BufferedReader class?
3. How can we access user defined exception?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


47

JAVA LAB MANUAL

EXERCISE 24

AIM: Write a JAVA program to illustrate creation of threads using runnable class.(start method
start each of the newly created thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).

DESCRIPTION:
In this program created a thread using Runnable interface. In the Runnable interface a main
thread and child threads are created, along with a run method is used. In the run method there is a
thread sleep method for children and the children is suspending for 500ms and used join().
Syntax:
Try{Thread.sleep(500)}
Catch(InterruptedException ie){}

ALGORITHM:

1.start
2. create a class1 that implements Runnable interface.
declare a constructor for declaring message.
start the thread using start()

declare run () method in which statements of exception(i.e interrupted exception) are


placed in try block
write for loop for some n times.
print thread name using Thread.currentThread().getMessage()
give sleep(500) for suspending of thread for 500
milliseconds.
end for
write catch block for handling Exception occured.
end method

end class

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


48

JAVA LAB MANUAL

3.create a class main()


in this create two runnable objects (i.e object to class1passing strings to constructor)
then pass this runnable object as parameter to Thread class constructor creating 2 objects
to Thread class.
start threads 1and2 using start ()
end main class
4.stop

OUTPUT:
Breakfast
Lunch
Supper
Dinner
CONCLUSION:

Multi tasking and processing is major part in operating system inorder to share the time
for real time batch processing. And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

VIVA QUESTIONS:
1.What is a Thread?
2.Which method is used to create a thread?
3.What are the stages of thread creation?
4.What is sleep()?
4.Why should we call sleep() with Thread class?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


49

JAVA LAB MANUAL

EXERCISE 25

AIM: Write a JAVA program to create a class MyThread in this class a constructor, call the base
class constructor, using super and starts the thread. The run method of the class starts after this. It
can be observed that both main thread and created child thread are executed concurrently.

DESCRIPTION:
This program create a class called My Thread. In this class a constructor calls the base class
constructor using super and starts the thread. The run method of the class starts after this. Here
we can observed that both main thread and creation of child thread are executed concurrently.

ALGORITHM:

1.start

2.create a class MyThread extending from Thread class


create a constructor
from this call base class constructor using super
write start() to start Thread
declare run() method and write statements of exception in try block
give for loop for repeating of sub Thread n times

print Thread.currentThread().getName()
i.e name of thread
give sleep()method for interruption of other Threads i.e to
run multi threads simultaneously

end try
declare catch block for handling interruptedException occured.
end for
end run()

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


50

JAVA LAB MANUAL

end class
3.create main class
give main method as public static void main(String[] args)
create object to class 1
call method of class1

give for loop for repeating of main Thread n times


print Thread.currentThread().getName()
i.e name of thread
give sleep()method for interruption of other Threads i.e to run multi
threads simultaneously
end try
declare catch block for handling interruptedException occured.
end for
4.end main class.
5.stop.

OUTPUT:
Main Thread Running:main
Running Thread is:Thread-0

CONCLUSION:

Multi tasking and processing is major part in operating system inorder to share the time
for real time batch processing. And maps to CO1, CO2 and attains with
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

VIVA QUESTIONS:

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


51

JAVA LAB MANUAL

1.What is the use of run method?


2.What is the difference between Thread class and Runnable interface?

3.what is the priority of thread?

4.what is prority of main() thread?

5. What is daemon thread?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


52

JAVA LAB MANUAL

EXERCISE 26

AIM: Write a java program to illustrate multiple inheritance using interfaces?

DESCRIPTION: Interfaces are completely abstract classes in Java that provide you with a
uniform way to properly delineate the structure or inner workings of your program from its
publicly available interface, with the consequence being a greater amount of flexibility and
reusable code as well as more control over how you create and interact with other classes. More
precisely, they are a special construct in Java with the additional characteristic that allow you to
perform a kind of multiple inheritance i.e. classes that can be upcast to more than one class; a
technique from which you are severely restricted from undertaking (and with good reason) when
working exclusively with classes. To create an interface in Java, you simply use the
special interface keyword.

Note: Interface consists only abstract methods and static final members.

ALGORITHM:
1 start
2 create a class.
in this class we use number of methods
3 after that create a sub class from super class.
in this also we use methods with diffarent name.
4 after that create an interface like this
interface interfacename
{
//methods;
}
5 after that create a new class from sub class and impliments the methods in interface.
syntax:
class classname extends subclassname impliments methodname

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


53

JAVA LAB MANUAL

{
//statements;
}
6 after that create a main class
in this create an object for subclass.
7 stop

OUTPUT:
D:\java\java 2>javac MultipleInheritance.java

D:\java\java 2>java MultipleInheritance


Enter amout in the account 3000
Name: Dileep Kumar
acc.No: 123456
type : Credit
ballence :3000.0
Name: Dileep Kumar
acc.No: 123456
type : Debit
ballence :3000.0

CONCLUSION:

Parent and child relationship between objects to analyze object oriented features. And
maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.
VIVA QUESTIONS:
1.What is an interface?
2.How can you implement multiple inheritance in java?
3. How can we implement abstract methods?
4.What is the difference between interface and abstract class?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


54

JAVA LAB MANUAL

EXERCISE 27
AIM: Write a java program to create a package called employee and import this package out of
the package?

DESCRIPTION: Packages are used in Java in order to prevent naming conflicts, to control
access, to make searching/locating and usage of classes, interfaces, enumerations and
annotations easier, etc.A Package can be defined as a grouping of related types (classes,
interfaces, enumerations and annotations ) providing access protection and namespace
management.

Some of the existing packages in Java are –

java.lang − bundles the fundamental classes

java.io − classes for input , output functions are bundled in this package

Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes

 java.io − classes for input , output functions are bundled in this package

While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
We have two ways to access members from out of the package:
1. import
2. package.classname
Note: Interface consists only abstract methods and static final members.

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


55

JAVA LAB MANUAL

ALGORITHM:
1 create a package named p1
syntax: package packagename
2 using this syntax to create an implimentation of package
syntax: public class classname impliments classname
3 in this we use more methods
4 after that create an main method and create an object to super class
5 stop

CONCLUSION:

Parent and child relationship between objects to analyze object oriented features. And
maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

OUTPUT:
D:\java\packages>javac -d . Employee.java

D:\java\packages>javac -d . Faculty.java

D:\java\packages>javac -d . FacultyType.java

D:\java\packages>set classpath=%classpath%.;d\java\packages\*.class;

D:\java\packages>javac Total.java

D:\java\packages>java Total
e1
sai

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


56

JAVA LAB MANUAL

professor
full time

VIVA QUESTIONS:
1.What is package?
2.How can you create user defined package?
3.How can compile package?
4.How many ways to access a package?
5. why should we mention public to each member of a package?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


57

JAVA LAB MANUAL

EXERCISE 28

AIM: Write a java program to create a package called employee and implement this package out
of the package?

DESCRIPTION: Packages are used in Java in order to prevent naming conflicts, to control
access, to make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes

 java.io − classes for input , output functions are bundled in this package

ALGORITHM:

1 create a package named mypack


2 import statement placed at after package
3 after that create a class
4 you want to import a class in package
syntax: import java.util.Date;
class MyDate extends Date
{
//statement.
}
5 after that create a main class
6 creqate an object to super class and call methods in super class
7 stop

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


58

JAVA LAB MANUAL

OUTPUT:
D:\java\java 2\packages\pkgs1>javac -d . VehicleDetails.java

D:\java\java 2\packages\pkgs1>javac -d . VehicleName.java

D:\java\java 2\packages\pkgs1>set classpath=%classpath%.;d\j


pkgs1\specs\*.class;

D:\java\java 2\packages\pkgs1>java VehicleName


Enter vehicle Name : car

Enter version of the vehicle : vista


Enter top speed,no of gears,mileage,capacity,horsepower,brak
ehicle
100 2 45 200 50 yes diesel
Name :car
Version :vista
top speed :100.0km
noOfGears :2.0
mileage :45.0km
capacity :200.0km
horsePower :50.0cc
brake :yes
fuelType :diesel

CONCLUSION:

Bundling data through classes and interfaces to make package and implementing java
encapsulation with specifying access handlers. And maps to CO1, CO2 and attains
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3.

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


59

JAVA LAB MANUAL

VIVA QUESTIONS:
1. What is a package?
2. what is access specifier?
3. what is protected keyword?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


60

JAVA LAB MANUAL

EXERCISE 29

AIM: Write a java program to give a simple example for abstract class?

DESCRIPTION:
An abstract class is, conceptually, a class that cannot be instantiated and is usually implemented
as a class that has one or more pure virtual (abstract) functions.
A pure virtual function is one which must be overridden by any concrete (i.e., non-abstract)
derived class. This is indicated in the declaration with the syntax " = 0" in the member function's
declaration. The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface. Attempting to instantiate an object of an
abstract class causes a compilation error. Thus, if a subclass of an ABC needs to be instantiated,
it has to implement each of the virtual functions, which means that it supports the interface
declared by the ABC. Failure to override a pure virtual function in a derived class, then
attempting to instantiate objects of that class, is a compilation error. Classes that can be used to
instantiate objects are called concrete classes.

ALGORITHM:

1 start
2 create an abstract class like this
syntax: abstract class classname
3 In this we create a abstract method
4 After that create a sub class
5 Iin this sub class run the abstract method.
6 After that create a main method and create an object to sub class
7 with the help of object call a abstract method
8 stop

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


61

JAVA LAB MANUAL

CONCLUSION:

Abstracting the data into object needs to hide the functionalities and implementing the
exisiting ones. And maps to CO1, CO2 and attains with PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

OUTPUT:
D:\java\java 2>javac AbstractFans.java

D:\java\java 2>java AbstractFans


Enter no of Units
10
Enter cost per unit
50
Total cost =
500.0

VIVA QUESTIONS:
1. What is an abstract class?
2. What is concrete class?
3. can we create an instance to an abstract class?
4. What are the members of an abstract class?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


62

JAVA LAB MANUAL

EXERCISE 30

AIM: Write a JAVA program that describes the life cycle of an applet.
DESCRIPTION:

An applet is a special Java program that can be embedded in HTML documents. It is


automatically executed by (applet-enabled) web browsers. In Java, non-applet programs are
called applications.

The life cycle of an applet:

init()- Called exactly once in an applet’s life. It is Called when applet is first loaded, which is
after object creation, e.g., when the browser visits the web page for the first time. Used to read
applet parameters, start downloading any other images or media files, etc.

start()-Called at least once. Called when an applet is started or restarted, i.e., whenever the
browser visits the web page.

stop()- Called at least once. Called when the browser leaves the web page.

destroy ()- Called exactly once. Called when the browser unloads the applet. Used to perform
any final clean-up.

ALGORITHM:

1.Import applet and awt packages

2.Create a class and extends it from Applet

3.Give implementation to init(),stop(),stop(),destroy(),paint()

4.Set font to content which is on applet window using-setFont()

5.Print the content on window using-drawString(str,x,y)

6.Embed class file into html file and run it either using appletViewer or browser

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


63

JAVA LAB MANUAL

OUTPUT:
// Create a ColorApplet.html to run applet in browser

<applet code="ColorApplet.class" height="200" width="200">


</applet>

Steps to Compile and Run Applet:

javac ColorApplet.java
appletviewer ColorApplet.html

OR

javac ColorApplet.java
appletviewer ColorApplet.java

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


64

JAVA LAB MANUAL

CONCLUSION:

Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1,C02,CO3,CO4,CO5,CO6 and attains to
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

VIVA QUESTIONS:
1. What is an Applet?
2. What are the stages of applet?
3. What is the use of paint() method?
4. From where paint() is using?
5. what is drawString(String,int,int) method?
6. what is class hierarchy of Applet?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


65

JAVA LAB MANUAL

EXERCISE 30(A)

AIM: Write a JAVA program to create a dialog box and menu.

DESCRIPTION:

Dialog control represents a top-level window with a title and a border used to take some form
of input from the user. This class inherits methods from the following classes:

 java.awt.Window

 java.awt.Component

 java.lang.Object

package: java.awt.Dialog

ALGORITHM:

1.Create a class called MyDialog derived from JDailog class

2.Create a layout using setLayout()

3.Add label using JLabel()

4.Start action using addActionListener()

5.Start init() method

6.Start action using addActionListener()

7.In main function setOperation(), setSize() and setVisibile() are used

8.Display the Dialog box

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


66

JAVA LAB MANUAL

OUTPUT:

CONCLUSION:

Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1,C02,CO3,CO4,CO5,CO6 and attains to
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

VIVA QUESTIONS:
1. what is awt package?

2. why awt components are heavy weight?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


67

JAVA LAB MANUAL

EXERCISE 30(B)

AIM: Write a java program to create a grid layout

DESCRIPTION:
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors:

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.

ALGORITHM:
1.Create a class and extends it from JFrame
2.set border layout to a frame using GridLayout
setLayout(gridlayoutobject);
3.Create 5 buttons using JButton
JButton b1=new JButton("Button1");
JButton b2=new JButton("Button2");
JButton b3=new JButton("Button3");
JButton b4=new JButton("Button4");
JButton b5=new JButton("Button5");

4.Add 5 buttons to 4 directions along with center


add(b1);
add(b2);
add(b3);
. add(b4);

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


68

JAVA LAB MANUAL

add(b5);
5.finally make frame as visible using-
setVisible(true);

OUTPUT:

CONCLUSION:
Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1,C02,CO3,CO4,CO5,CO6 and attains to
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


69

JAVA LAB MANUAL

VIVA QUESTIONS:

1. What is grid layout?

EXERCISE 31

AIM: Write a java program to create a border layout control

DESCRIPTION:

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

ALGORITHM:
1.Create a class and extends it from JFrame
2.set border layout to a frame using BorderLayout
setLayout(borderlayoutobject);
3.Create 5 buttons using JButton
JButton b1=new JButton("Button1");
JButton b2=new JButton("Button2");
JButton b3=new JButton("Button3");
JButton b4=new JButton("Button4");
JButton b5=new JButton("Button5");

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


70

JAVA LAB MANUAL

4.Add 5 buttons to 4 directions along with center

add("North",b1);
add("East",b2);
add("South",b3);
.add("West",b4);
add("Center",b5);
5.Finally make frame as visible using-
setVisible(true);

OUTPUT:

CONCLUSION:

Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1,C02,CO3,CO4,CO5,CO6 and attains to
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


71

JAVA LAB MANUAL

VIVA QUESTIONS:

1. What is border layout?

2. What is the purpose of setHgap()


3. Difference between awt and swing?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


72

JAVA LAB MANUAL

EXERCISE 32

AIM: Write a java program to create a padding layout control

DESCRIPTION:

This program is used to design layouts of user defined. The layout borders are set suing
setLayout method. Then add three fields to the layout like no, name, email id and url using These
fields are added using JButton method. Finally the layout is created.

ALGORITHM

1.Create a class Paddy derived from Applet

2.Start init() method

3.Use BorderLayout as the overall layout

4.Add the table of name, e-mail, and URL using add() method

5.Add the ranking numbers to the left

6.Add control buttons at the bottom

7.Finally Create a Layout

INPUT-OUTPUT:

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


73

JAVA LAB MANUAL

CONCLUSION:

Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1,C02,CO3,CO4,CO5,CO6 and attains to
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

VIVA QUESTIONS:

1. What is padding control layout?

2. What are the different types of layouts are used?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


74

JAVA LAB MANUAL

EXERCISE 33

Aim: Write a java program to create a simple calculator.

DESCRIPTION: This program is used to create a simple calculator having basic arithmetic
operations like addition, subtraction, multiplication, division and modulo division. This
calculator is having buttons and these buttons are created using Button() method. Also this
having text field to display result.

ALGORITHM:

1. Create a class and derived from Applet

2. Create methods and declare variables

3. Add buttons using JButton()

4. Add color to the Layout

5. Perform user defined operation using getActionListener()

6. Create Text field

7. Display the calculator

OUTPUT:

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


75

JAVA LAB MANUAL

CONCLUSION:

Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1,C02,CO3,CO4,CO5,CO6 and attains to
PO1,PO2,PO3,PO11 and PSO1, PSO2

VIVA QUESTIONS:

1. What is the use of ActionListener interface?

2. what is event handling?

3. what is source, event and listener?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


76

JAVA LAB MANUAL

EXERCISE 34

AIM:To write a java program that handles a mouse event.

DESCRIPTION:
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

ALGORITHM:

1. Import awt and applet package


2. Extends a class from Applet and implement from MouseListener and MouseMotionListener
3. Implent all methods of MouseListener and MouseMotionListener

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


77

JAVA LAB MANUAL

4. Embed .class file into html file


5. Run the program either using appletViewer or browser

OUTPUT:

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


78

JAVA LAB MANUAL

CONCLUSION:

Desiging the graphical application to view the real wolrd ideas into application view.
This generates a GUI based implementation for student and can implement stand alone projects
easily using Java Foundation Classes. Applications like Biometric, Eye recognition and Aadhar
card data storage are good scenarios. It maps to CO1, C02, CO3, CO4, CO5, CO6 and attains to
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


79

JAVA LAB MANUAL

VIVA QUESTIONS:

1. How to detect the coordinate of mouse cursor?

2. What is the use of JFrame?

3. What are the methods of MouseEvent class?

4. What is an adapter class?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


80

JAVA LAB MANUAL

EXERCISE 35

AIM :A java program that displays number of characters, lines and words in a text file

DESCRIPTION:

The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream
in the java.io package supports many data such as primitives, object, localized characters, etc.

 InPutStream − The InputStream is used to read data from a source.

 OutPutStream − The OutputStream is used for writing data to a destination.

Byte Streams
 Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream.

Character Streams
 Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads
two bytes at a time and FileWriter writes two bytes at a time.

ALGORITHM:

1.Read a file using FileReader class and pass it to the BufferedReader


2.Read line by line using readLine() method.
3.Count each line and store in a variable
4.Split entire line into tokens using StringTokenizer and calculate word count.
5.Find each line length using length()

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


81

JAVA LAB MANUAL

6.Print the three details

OUTPUT:
D:\JAVA>javac CountLines.java
D:\JAVA>java CountLines
characters:63
words:12
lines:2

CONCLUSION:

Analyzing and accessing text file processing inorder to retrieve the data and handle that
for report generation. All data analytics applications needs to use file streaming strategies It
maps to CO1, C02, CO3, CO4, CO5, CO6 and attains to PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3

VIVA QUESTIONS:

1. What is the use of BufferedReader class?

2. What is the purpose of split method?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


82

JAVA LAB MANUAL

EXERCISE-36
AIM: Write a Java program to demonstrate Java data Base Connectivity.

DESCRIPTION:

Java Database Connectivity (JDBC) is an application programming interface (API) for


the programming language Java, which defines how a client may access a database. It is part of
the Java Standard Edition platform, from Oracle Corporation. Java JDBC is a java API to
connect and execute query with the database. JDBC API uses jdbc drivers to connect with the
database

ALGORITHM:

Install Database Server

Create a user and give privileges to user

Download the database driver

Load the driver

Establish the Connection

Close the connection.

INPUT-OUTPUT:

javac JdbcConnectivity.java

java JdbcConnectivity

Driver Name : oracle.jdbc.driver.OracleDriver


Database Product Name: Oracle 10g Express Edition
Database Version Name: 10.1
Closing Connection…

CONCLUSION:

Creating the database and implementing opetations on that data is very crucial in the real
world applications in order to handle business logic and implementing Model of Application. It
maps to CO1, CO2, CO3, CO4, CO5, CO6 and attains PO1,PO2,PO3,PO4,PO5,PO12,
PSO1,PSO2,PSO3.

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


83

JAVA LAB MANUAL

VIVA VOCE QUESTIONS

1) What is JDBC?
2) What are different types of drivers available?

3) What is Statement and its types?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


84

JAVA LAB MANUAL

EXERCISE-37

AIM: Write a Java program to demonstrate Socket Connection.

DESCRIPTION:

Java Socket programming is used for communication between the applications running
on different JRE. Java Socket programming can be connection-oriented or connection-
less.Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information: IP Address of Server, and Port
number. The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.

ALGORITHM:

Open a socket.

Open an input and output stream to the socket.

Read from and write to the socket according to the server's protocol.

Clean up.

INPUT-OUTPUT:

Javac MyServer.java javac MyClient.java

Java MyServer java MyClient

Message = Hello Server

CONCLUSION:

Creating the client server computing application for connecting different networks and
sharing data between themselves in all web based applications. It maps to CO1, CO2, CO3, CO4,
CO5, CO6 and attains PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


85

JAVA LAB MANUAL

VIVA VOCE QUESTIONS

1) What is Socket?
2) What is InetAddress?
3) hat is the package used to implement Socket Connection?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


86

JAVA LAB MANUAL

EXERCISE-38

AIM: Write a Java program to demonstrate HashMap?

DESCRIPTION:

A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.It contains only unique elements. It may have one null key and
multiple null values. It maintains no order. Sorted order of Keys in the Map can done with
TreeMap Interface.

ALGORITHM:

Create a HashMap Object.

Create a HashMap with generic data object as String.

Input the data from System and add to collection

Iterate the Map

INPUT-OUTPUT

Javac Telephone.java

Java Telephone

{James=9876666666, John=9878867766, Jack=9877777666, Jane=9876666888}

CONCLUSION:

Collecting data objects and doing operations on those data collection like adding,
deleting, searching and iterating that resembles real world data like GPS tracking and
implementing Big data Collection. It maps to CO1, CO2, CO3, CO4, CO5, CO6 and attains
PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


87

JAVA LAB MANUAL

VIVA VOCE QUESTIONS

1) What is Iterator?
2) Difference between Hashtable or HashMap?
3) What is Comparator?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


88

JAVA LAB MANUAL

EXERCISE-39

AIM: Write a Java program to demonstrate Java Reflection?

DESCRIPTION:

Java Reflection is a process of examining or modifying the run time behavior of a class at
run time. The java.lang.Class class provides many methods that can be used to get metadata,
examine and change the run time behavior of a class. The java.lang
and java.lang.reflect packages provide classes for java reflection.

ALGORITHM:

Create object Person with attributes and methods.

Create a Reflection object Instance Class to load Person

Create a Constructor class to getDecalaredConstructors()

And get the length of Constructors array.

Print the data.

INPUT-OUTPUT

javac GetConstructors.java

java GetConstructors

No of Person Constructors are:3

CONCLUSION:

Introspecting object and implementing its behavior is aim of this program. This annotates
the students learning how object behaves int real world entities.. It maps to CO1, CO2 and
attains PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


89

JAVA LAB MANUAL

VIVA VOCE QUESTIONS

1) What is Reflection?
Reflection is used to read a class dynamically to introspect object
2) What is the package used to implement java reflection API?
The package used to implement is : java.lang.reflect.*
3) What is method used to retrieve constructors from Object?
Constructor class using getDeclaredConstructors()

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


90

JAVA LAB MANUAL

EXERCISE-40

AIM: Write a Java program to demonstrate Java ThreadGroup

DESCRIPTION:

Threads are very important in scheduling of Tasks. They can be implemented using either
Runnable interface or Thread Class.

ThreadGroup class is used to group the threads by adding them. Finding the active count
of threads can be found by passing threads as a parameter into group.

ALGORITHM:

Create a thread class Tv that implements Runnable

Implement run() method

Create a main class named ThreadGroupDemo

Instantiate threads for Tv named Thread1,2,3

Add all the threads to ThreadGroup

Find the active count of ThreadGroup

INPUT-OUTPUT:

Javac ThreadGroupDemo.java
Java ThreadGroupDemo
DVD
Remote
Home Theatre
Number of Threads in Group are: 3

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE


91

JAVA LAB MANUAL

CONCLUSION:

Introspecting object and implementing its behavior is aim of this program. This annotates
the students learning how object behaves int real world entities.. It maps to CO1, CO2 and
attains PO1,PO2,PO3,PO4,PO5,PO12, PSO1,PSO2,PSO3

VIVA VOCE QUESTIONS

1) What is difference between Thread and Runnable interface


2) What is use of start() method
3) Define different states of Thread?

LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY – DEPARTMENT OF CSE

You might also like