You are on page 1of 35

MATRUSRI ENGINEERING COLLEGE

(Affiliated to Osmania University & Recognized by AICTE)


Saidabad, Hyderabad

DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING

OOP using JAVA LAB


(PC 353 CS)
LAB MANUAL

B.E. III - SEMESTER


(2021-22)
DEPARTMENT VISION

The Computer Science and Engineering Department aims to produce


competent professionals with strong analytical skills, technical skills, research
aptitude and ethical values.

DEPARTMENT MISSION

M1: To provide hands-on-experience and problem-solving skills by imparting


quality education

M2: To conduct skill-development programmes in emerging technologies to serve


the needs of industry, society and scientific community.

M3: To promote comprehensive education and professional development for


effective teaching-learning processes.

M4: To impart project management skills with an attitude for life-long learning
with ethical values.
BE(CSE) PROGRAMME EDUCATIONAL OBJECTIVES:
 To learn engineering knowledge and problem analysis skills to design and develop solutions
for computer science and engineering problems.
 To address the feature engineering with the usage of modern IT and Software tools.
 To acquire and practice the profession with due consideration to environment issues in
conformance with societal needs and ethical values.
 To manage projects in multidisciplinary environments as a member and as a leader with
effective communications.
 To engage in life-long learning in the context of ever changing technology.

BE (CSE) PROGRAMME OUTCOMES:
Upon the completion of programme, the student will be able

 Engineering knowledge: Apply and integrate the knowledge of computing tocomputer


science and engineering problems.
 Problem Analysis: Identify, formulate and analyze complex engineering problems using
computer science and engineering knowledge.
 Design/Development of solutions: Design and develop components or processes to
engineering problems as per specification with environmental consideration.
 Conduct Investigations of complex problems: Interpret and integrate information to
provide solutions to real world problems.
 Modern tool usage: Select and apply modern engineering and information technology tools
for complex engineering problems
 The engineer and Society: Assess and responsible for societal, health, safety, legal and
cultural issues in professional practice.
 Environment and Sustainability: Understand the impact of computing solutions in the
context of societal, environmental and economical development.
 Ethics: Commit to professional ethics and responsibilities and norms of the engineering
practice.
 Individual and team work: Function as an individual, as a member or leader in
multidisciplinary environment.
 Communication: Acquire effective written and oral communication skills on technical and
general aspects.
 Project management and finance: Apply engineering and management principles to
manage projects in multidisciplinary environments.
 Life-Long learning: Identify the need of self-learning and life-long learning in the broad
context of technological evolution.

BE(CSE) PROGRAM SPECIFIC OUTCOMES:

Upon the completion of programme, the student will be able to

 Familiar with open-ended programming environments to develop software applications.


 Apply the knowledge of Computer System Design, Principles of Algorithms and Computer
Communications to manage projects in multidisciplinary environments.
List of Programs
S. No Name of the Program CO Page
01 Write Java program to illustrate the concept of class with Addressed
1 8
method overloading.
02 Write a Java Program that reads a line of integers, and then 1 8
displays each integer, and the sum of all the integer (Use
String Tokenizer class of java. util)
03 Write a Java program to illustrate the concept of Single level 1 9
and Multi level Inheritance
04 Write a Java program to demonstrate the Interface and 1 10
Abstract Classes
05 Write a Java program to implement the concept of exception 1 11
handling
06 Write a Java program to illustrate the concept of threading 2 12
using Thread Class and runnable Interface.
07 Write a Java program to illustrate the concept of Thread 2 12
synchronization.
08 Write a Java program that correctly implements producer 2 13
consumer problem using the concept of inter thread
09 communication.
Write a Java program to illustrate collection classes like Array 3 13
List, LinkedList, Tree map and Hash map.
10 Write a Java program to illustrate Legacy classes like Vector. 3 15
Hashtable, Dictionary & Enumeration interface.
11 interface
Write a Java program to implement iteration over Collection 3 15
using Iterator interface and ListIterator interface
12 Write Java program that reads a file name from the user, and 3 16
then displays information about whether the file exists,
interface
whether the file is readable, whether the file writable, the type
of file and the length of the file in bytes.
13 Write a java program to illustrate the concept of I/O Streams 3 17
14 Write a Java program to implement serialization concept. 3 17
15 Write a Java applet program to implement Colour and 4 17
Graphics class 4
16 Write a Java applet program for handling mouse & key events 4 18
17 Write a Java applet program to implements Adapter classes. 4 19
18 Write a Java program that works as a simple calculator. Use a 4 20
grid layout to arrange buttons for the digits and for the +, -, *,
% operations. Add a text field to display the result.
19 Write an example for JDBC prepared statement with ResultSet 5 20
20 Write a Java Program to get primary key value (auto-generated 5 21
keys) from inserted queries using JDBC
21 Write a Java Program to create a simple JList 5 22
22 Write a Java Program to create a simple checkbox using 5 22
JCheckBox
23 Write a Java Program to create a checkbox and Item Listener 5 23
24 toit.
(a). Write Servlet application to print current date &time 5 24
(b). Html & Servlet Communication
(c). Auto refresh a page
(d). Demonstrate session tracking
(e). Select record from database
(f). Application for login page
(g). Insert record into database
(h). Count the visits on webpage
(i). Insert teacher record in Database

Beyond the Syllabus:

S. No Name of the Program CO Page


1 Write a Java program that displays the number of characters, Addressed
1 27
lines and
2 words
Write ainJava
a text file. using Interfaces.
program 1 28
3 Write a Java program to illustrate user defined packages 1 28
4 Write a java program to illustrate usage of all String handling 5 29
5 methods an applet that displays a simple message
Develop 4 29

Course Objectives and Course Outcomes

Subject Code Course Objectives


PC353CS To gain programming skills in object oriented programming concepts, java
application using Classes, Inheritance and abstract classes
PC353CS To build software development skills using java programming for real world
applications.
PC353CS To implement frontend and backend of an applications.

PC353CS To implement classical problems using java programming.

PC353CS To develop Event Driven GUI applications using AWT/Swings


Subject Code Course Outcomes
The student will be able to do
PC353CS 1. Develop Java applications using the concepts of Inheritance, interfaces, packages,
access control specifiers.
PC353CS 2. Implement the concepts of Exception Handling in java Applications
PC353CS 3. Read and write data using different Java I/O streams.
PC353CS 4. Create graphical user interfaces and Applets by applying the knowledge of Event
PC353CS 5. Create robust applications using Java standard class libraries and retrieve data from
a database with JDBC
Aim: To develop Applications implementing Object Oriented Programming Concepts using
JAVA.
Structure
 Introduction
 Objectives
 Programming with Java
 PATH and CLASSPATH Setting
 OOP lab concepts
 List of Lab Assignments
Introduction
Welcome to the amazing and dynamic world of Java! Java is a programming language that
was introduced by Sun Microsystems in June 1995. Java is most favoured language for
web enabled application development. It is widely used for developing distributed and
internet based applications.

It is also used in communication programming. It is used for web oriented application


development due to its features such as platform independence and portability. Due to
OOPS support it offers new and powerful way to solve complex problems. It also has a
huge collection of built in class libraries which ease the programming task.

It has the most coveted robustness and built in security measures. Also the programs
become clearer, reliable, and easily maintainable. It is widely accepted and is a well
designed programming language. The students are expected to understand basic concepts
of web enabled programming and be able to develop Java programming skills.

The students are already familiar with object oriented principals through C++
programming, which serves as a good foundation to learn Java.

1
Programming with JAVA

Java Development Kit (JDK)


The JDK comes with a collection of tools that are used for developing and running Java
programs which include:
 appletviewer (for viewing Java applets)
 javac (Java compiler)
 java (Java interpreter)
 javap (Java disassembler)
 javah (for C header files)
 javadoc (for creating HTML documents)
 jdb (Java debugger)

Following table lists these tools and their descriptions.


Tool Description

appletviewer Enables us to run Java applets (without using a Java compatible


browser)
java Java Interpreter, which runs applets and applications by reading and
interpreting byte code files.
javac Java compiler, which translates Java source code to bytecode files that
the interpreter can understand.
javadoc Creates HTML format documentation from Java source code files.
javah Produces header files for use with native methods.
javap Java disassembler, which enables us to convert bytecode files into a
program.
jdb Java debugger, which finds errors in programs.

2
Writing a Program
The easiest way to write a simple program is with a text editor. So, using the text
editor of your choice, create a text file with the following text, and be sure to name the text
file ExampleProgram.java. Java programs are case sensitive, so if you type the code in
yourself, pay particular attention to the capitalization.
Double Slashes
Double slashes (//) are used in the C++ programming language, and tell the compiler
to treat everything from the slashes to the end of the line as text.
C-Style Comments
Instead of double slashes, you can use C-style comments (/* */) to enclose one or more
lines of code to be treated as text.
Doc Comments
To generate documentation for your program, use the doc comments (/** */) to enclose
lines of text for the javadoc tool to find. The javadoc tool locates the doc comments embedded in
source files and uses those comments to generate API documentation

.
//A Simple Example
/** This class displays a text string at
* the console.
*/
class TestProg {
public static void main(String args [ ]){
System.out.println("WELCOME TO JAVA");
}
}
Here is the TestProg.java source code file
Class
• Every java program includes at least one class definition. The class is the fundamental
component of all Java programs.
• A class definition contains all the variables and methods that make the program work. This is
contained in the class body indicated by the opening and closing braces.

3
Braces
• The left brace ( { ) indicates the beginning of a class body, which contains any variables and
methods the class needs.
• The left brace also indicates the beginning of a method body.
• For every left brace that opens a class or method you need a corresponding right brace ( } ) to
close the class or method.
• A right brace always closes its nearest left brace.
main() method
• This line begins the main() method. This is the line at which the program will begin executing.
String args[]
• Declares a parameter named args, which is an array of String. It represents command-line
arguments.
System.out.println
• This line outputs the string “I'm a Simple Program!” followed by a new line on the screen.

Fig: Process of Building and running Java Application programs

Text Editor

Java Source
Code javadoc HTML Files

javac

Java class File javah Header Files

java
jdb

Java Program
Output

4
Java Virtual Machine (JVM)
All language compilers translate source code into machine code for a specific
computer. Java compiler produces an intermediate code known as bytecode for a machine
that does not exist. This machine is called as Java Virtual Machine and it exists only inside
the computer memory. Following figure shows the process of compiling a Java program
into bytecode which is also called as Java Virtual Machine code.

Java Program Java Java Virtual


Compiler Machine
Byte Code
Fig: Process of Compilation
The Java Virtual Machine code is not machine specific. The machine specific code (known as
machine code) is generated by the Java interpreter by acting as an intermediate between the
virtual machine and the real machine as shown in following figure. The interpreter is different
for different machines.

Byte Code Java Machine


Interpreter Code

Fig: Process of converting byte code into machine code


PATH AND CLASSPATH SETTING
To run Java programs you need JDK (Java Development Kit) installed on your
machine. The latest version of JDK you can download from java.sun.com for free. It
is suggested that you should set PATH and CLASSPATH properly before trying to
compile and run your Java programs, otherwise you may not able to compile or run
your program because of improper setting.
PATH Setting
If PATH setting is not proper then whenever you try to compile any program on your
DOS prompt as shown in Figure 5.2, it does not compile your TestProg program.

5
Fig: Compile testProg.java
Instead it gives you some strange message about a “Bad Command”. The machine says “Bad
command” because it recognizes the commands javac or java. So you simply need to tell DOS
that these commands live in Java‟s JDK directory and whenever it doesn‟t recognise a
command like javac, it should also check the Java‟s JDK directory for a possible
interpretation of this command. This problem can be solved in two ways, one by using DOS
prompt, and another by using My Computer on your window screen. Type path at your DOS
prompt as demonstrated in Figure 5.3, you will get a PATH statement like

PATH=C:WINNT\...;C:\ProgramFiles\.....

Here the dots represent all kinds of directory names. This is a list of all the places DOS
looks when it is trying to find out what a particular command means. If your JDK directory
is not on this list, your DOS won‟t understand the JDK‟s commands. So you need to add it
to the list. You can do this by typing.
set path=c:\jdkwhateverItIs\bin;%path%

6
Whatever is the version of JDK, the above command adds your JDK directory to the rest
of the existing path. If you have put your JDK directory somewhere else, alter the directory
name in the command above appropriately to match the actual location. If there is any
spaces in the command above (except between set and path), path will not be set properly.
Now try to run the Java commands again. If it still doesn‟t work, move your *.java files
into the JDK directory and you should be able to work there (or in the bin subdirectory of
the JDK directory). Here is the problem again because you‟ll need to reset your path every
time you turn your machine back on and want to work on the Java programs again. But
there is a way to fix it permanently. You need to alter (edit) your autoexec.bat file, which is
in your main C:\directory. It is suggested to copy this file first to a back up version, then do
the required modifications as told here.

C:\copy autoexec.bat autoexecBACK.bat

This is the file that has all the important settings for making your PC run the way you
want it. One of the settings it makes is the PATH. Now edit the autoexec.bat file and find
the line that sets the path. Add your version of the "set path=C:/jdk.2...." command (the
one you used earlier) after the line that sets the rest of the path in the autoexec.bat file.
Now save the file. Then the next time you open a DOS window (it maybe required to
restart your machine), the PATH should be set correctly. If you made an error in editing
autoexec.bat, things might not work quite right now. In this case, just copy your back up
version of autoexecBACK.bat back into autoexec.bat and try the whole process again.

CLASSPATH Setting
You may also need to set the CLASSPATH variable, which contains all of the directories
on your machine where the Java compiler and the Java run-time environment are to search
for any files it needs, e.g., if you compile or run the Java class TestProg.java, the compiler
needs to know that directory. Your autoexec.bat file or control settings also determine
where the javac compiler looks for the Java code files. For example, if you are writing your
code in the directory c:\jdk1.2\naveen, you would add the following line to your
autoexec.bat file:

CLASSPATH: c:\jdk1.2\naveen

You can list (separated by ;) as many directories as possible in your classpath. One
important thing about "." is that it means that javac will always look in the current
directory for the files it needs. For example, to list the current directory, the naveen
directory, and the diskette drive as places where javac should look, you would have the
following classpath:

CLASSPATH: .;c:\jdk1.2\naveen;a:\
This environmental variable can be set the same way as the PATH above. But there is
one shortcut to avoid the CLASSPATH setting. The javac or Java command has an option
that is (classpath option) that allows you to manually configure the classpath during
compilation/execution. For example, to specify that the compiler must look in the current

7
directory (that is, the "." directory) for the file TestProg.java when compiling it, you would
use the command:

javac -classpath . TestProg.java


In XP/2000/ME machines PATH and CLASSPATH can be set using “My
Computer.”

The process is given as follows:


1. Right click on "My Computer" and Click on Properties.
2. Click on the Advanced tab.
3. Click on the "Environment Variables" button near the bottom.
4. A dialog box comes up with two boxes: In the bottom box, look for "Path" and
highlight that line. Then click on "Edit" .A small dialog box appears. In the
second text field for the value, at the END of the line, add a semicolon then the
path to where your java.exe file is. For example path is like: C:\jdk1.3….\bin
5. Click "OK."
6. Now, in the top box, click on the "New" button.
7. In the first field, enter "classpath" as one word. For the value in the second field,
enter a single period.
This is all you have to do for setting PATH and CLASSPATH. Now you can compile and
run your applications and applets without any problem of PATH and CLASSPATH. PATH
and CLASSPATH setting need to be done only if you are willing to run programs on DOS
prompt. If you write Java programs in some specific editors like EditPlus, JBbuilderfor etc.
then these settings discussed above are editor dependent.

1. Write Java program to illustrate the concept of class with method overloading.

Algorithm:
1. Create a class EmployeeDetails
2. Write methods called called showDetails(), showDetails(String)
3.Create an instance to Faculty class and call members of EmployeeDetails class.

OUTPUT:
Xyz
000
31/may/1991
25
50000.0

2. Write a Java Program that reads a line of integers, and then displays each integer,
and the sum of all the integer (Use String Tokenizer class of java. util)

Algorithm:
1.import util package
2.create a String Tokenizer class

8
3. create a main function
4 Create BufferedReader Object br as follows.
5.BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
6.Declare i, n, sum=0;
7.Read String s
8.Convert string into tokens as StringTokenizer st = new StringTokenizer(s);
9.while(st.hasMoreTokens())
10.Take the token n and convert to integer
11.Display n value
12.Add n to sum
13.Display sum
Output:

3. Write a Java program to illustrate the concept of Single level and Multi level
Inheritance.

Algorithm for Single level :

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:

Enter SId, SName:


000 XYZ
EID=000 ENAME=XYZ

Algorithm for Multi Level:

1. Create a class named Employee


2. Extend Faculty class from Employee class
3. Extend Professor class from Faculty class

9
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

Output:
Enter sId, sName:
000 xyz
SID=000 SNAME=XYZ

4. Write a Java program to demonstrate the Interface and Abstract Classes.

Algorithm for Interface:


1. Create a class income declare iamount as integer
2. Create a function get() to get the values for the variable
3. Create a class expenditure and declare the function get1()
4. Create a derived class netincome that extends income and implements expenditure
5. Declare variables eamounts, namount as float
6. Create a function print() to print the values
7. Create a main class and create an object for netincome
8. Now get the values using n.print().
9. End

Output:
Enter income:1000
Enter Expenditure:200

Income:1000.0
Expenditure:200.0
Net income:800.0

Algorithm for Abstract Class:

1.Create abstract class Figure


2.declare dim1, dim2
3.Figure(double a, double b)
4.Assign a to dim1
5.Assign b to dim2
6.Declare abstract double area();
7.class Rectangle extends Figure
8.Rectangle(double a, double b)
9.Class the super class constructor by passing the parameters a, b
10.double area()

10
11.Display Inside Area for Rectangle
12.Calculate and return dim1 * dim2;
13.class Triangle extends Figure
14.Triangle(double a, double b)
15.Class the super class constructor by passing the parameters a, b
16.double area()
17.Display Inside Area for Triangle
18.Calculate and return dim1 * dim2/2;
19.class AbstractAreas
20.public static void main(String args[])
21.Create Object for the class Rectangle r = new Rectangle(9, 5);
22.Create Object for the class Triangle t = new Triangle(10, 8);
23.Create a reference for Figure figref; // this is OK, no object is created
24.Assign r to figref
25.Call area() using figref and display the result
26Assigntr to figref
27.Call area() using figref and display the result
28.close main()
29.close class

Output:

5. Write a Java program to implement the concept of exception handling.

Algorithm :
Create a class and initialize class members and methods.
2. Read input values a,b,c
3. Compute d=a/(b-c) in try block
4. Provide catch(Exception e) block
5. Display ―Divide by zero error‖ message
6. End

Output:

11
6. Write a Java program to illustrate the concept of threading using Thread Class and
runnable Interface.
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
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

7. Write a Java program to illustrate the concept of Thread synchronization.

Algorithm:
1. Create a class with a synchronized
2. Create one thread and pass the shared class object.
3. Create second thread and pass the shared class object.
4. Create a main tester class and run both the threads

Output:

12
8. Write a Java program that correctly implements producer consumer problem using
the concept of inter thread communication.

Algorithm:

1. Creating a class q and declare variable n as int and declare value set (Boolean) as
false.
2. Create synchronized method in get().
3. Create another synchronized method void put(int n).
4. If (value set) then go to try and catch inside catch call notify this tells
produces that it away put more about in the queue.
5. Create a class producer that implements runnable.
6. Create object q.create a constructor producer where object is passed
7. Create a function run() initialize and declare i=0.
8. Create a class consumer that implements runnable.
9. Create constructor consumer, pass the object and create a function run().
10. Create a class multi2 inside the main function and create object q.

Output:

Stock add:10
Present stock:54
Stock not enough
waiting for stock to come...
Thread stopped.

9. Write Java program to illustrate collection classes like Array List, LinkedList,
Tree map and Hash map.

Algorithms:

ArrayList:
1. import java.util.* package
2. create a class
3. ArrayList al=new ArrayList();
4. add(100) to arraylist;
5. add("abc") to arraylist;
6. add(10.84) to arraylist;
7. add(2,5) to arraylist;
8. remove(10.84) from araylist;
9. print the "Array list‖
10. end

Iterator:
1. import java.util.* package
2. create a class

13
3. ArrayList al=new ArrayList();
4. add(100) to arraylist;
5. add("abc") to arraylist;
6. add(10.84) to arraylist;
7. add(2,5) to arraylist;
8. remove(10.84) from arraylist;
9. use Iterator it=al.iterator() to move ahead in the list;
10. print "List";
11. use ListIterator lit=al.listIterator() to move ahead in list;
12. move until no element found (lit.hasNext())
13. Add ―+‖ to the existing element using set() method;
14. Print "Modified List: "
15. Print "Modified list backwards";
16. Move until first element using hasPrevious() method
17. Print the element
18. end

Hashset:

1. import java.util.* package


2. create a class
3. Create HashSet hs=new HashSet();
4. Add (244) to hashset;
5. Add (21) to hashset;
6. Add ("Xyz") to hashset;
7. remove(21) from hashset;
8. print the Hashset hs;
9. end

Output:

14
10. Write a Java program to illustrate Legacy classes like Vector. Hashtable, Dictionary &
Enumeration interface.

Algorithm:

Hash table:
1. import java.util.* package
2. create a class
3create main()
4. create instance for hashtable
5.use Set st = ht.entrySet()
6. use Iterator itr=st.iterator()
7. start while loop
8. print "itr.getkey()";
9. end main()
10.end class
Output:
a 100
b 200
c 300
d 400
11. Write a Java program to implement iteration over Collection using Iterator interface
and ListIterator interface.

Algorithm:
1. import java.util.* package
2. create a class
3. ArrayList al=new ArrayList();
4. add(100) to arraylist;
5. add("abc") to arraylist;
6. add(10.84) to arraylist;
7. add(2,5) to arraylist;
8. remove(10.84) from arraylist;
9. use Iterator it=al.iterator() to move ahead in the list;
10. print "List";
11. use ListIterator lit=al.listIterator() to move ahead in list;
12. move until no element found (lit.hasNext())
13. Add ―+‖ to the existing element using set() method;
14. Print "Modified List: "
15. Print "Modified list backwards";
16. Move until first element using hasPrevious() method
17. Print the element
18. end

Output:

15
12. Write Java program that reads a file name from the user, and then displays
information about whether the file exists, whether the file is readable, whether the file
writable, the type of file and the length of the file in bytes.

Algorithm:

1. Start the program, import the packages.


2. create an object of ‗fi„ using fileinputstream class
3. if check the file exit then
print ‗file is exit„
else
print ‗file does not exit
4. Print the number of bytes of given files is using fi.length() function
5. End

Output:

16
13. Write a java program to illustrate the concept of I/O Streams.

Algorithm:
1. import io package
2. create a class
3. crate a main() along with throws IOException
4. read in=null,out=null;
5. start try block
6. read in and out variables with text files
7. close try block
8. start finally block
9. if in is not null
10. call in.close()
11.if out is not null
12. call out.close()
13. finally block
14. close main ()
15.close class

Output:
prints the text in text file

14. Write a Java program to implement serialization concept.

Algorithm:

1. Create an ―Emloyee‖ Class which has two member variables ―employeeNumber‖ and
―employeeName‖.
2. Then create an object of ―Emloyee‖ Class, say ―employee1‖ and set values for the
member
variables ―employeeNumber‖ and ―employeeName‖.
3. Serialize this employee object ―employee1‖ and store it into a file
4.Retrieve the object saved into the file

Output:

Objects are stored from the class into the file.

15. Write a Java applet program to implement Colour and Graphics class.

Algorithm:

1.import Applet package


2.import awt package
3.create a class with extends Applet class
4. create a function with one arguments
5.call different functions in Graphics & Colour class

17
6. close a function
7.close a class

Output:

A Rectangle with a color filled in it will be drawn in the browser.

16. Write a Java applet program for handling mouse & key events.

Algorithm:

1. Import the packages of applet, awt, awt.event.


2. Create a classes, methods.
3. Mouse moments, mouse Clicked, mouse Pressed, mouse Released, mouse Entered,
mouse Exited, mouse Dragged events args.
4. g.drawString() application of Graphical User Interface.
5. while rotating mouse event args.
6. The mouse event arguments execution.
7. Printing in the separated Applet viewer window.
8. End

Output:

Key Events:
1. Import the packages of applet, awt, awt.event.
2. Create a classes, methods.
3. Keyboard events like keyTyped, key Pressed, keyReleased.
4. g.drawString() application of Graphical User Interface.
5. The keyboard event arguments execution.
6. Printing in the separated Applet viewer window.
7. End

18
Output:

17. Write a Java applet program to implements Adapter classes.

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

19
18. Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -, *, % operations. Add a text field to
display the result.

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

19. Write an example for JDBC prepared statement with ResultSet

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable

20
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

20. Write a Java Program to get primary key value (auto-generated keys) from
inserted queries using JDBC

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

21
21. Write a Java Program to create a simple JList

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

22. Write a Java Program to create a simple checkbox using JCheckBox

Algorithm:
1. import awt package
2. import awt event package
3. create a class
22
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

23. Write a Java Program to create a checkbox and Item Listener to it.

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

23
24. (a). Write Servlet application to print current date &time
(b). Html & Servlet Communication
(c). Auto refresh a page
(d). Demonstrate session tracking
(e). Select record from database
(f). Application for login page
(g). Insert record into database
(h). Count the visits on webpage
(i). Insert teacher record in Database

Algorithm:
1. import awt package
2. import awt event package
3. create a class
4. create a constructor
5.create a instance for the variable
5.create a Listener
6. call a function
7.close Listener
8.call a different function
9.create a main function
10.call a function
11.close main function
12. close class

Output:

(a)

24
(b)

(c)

(d)

(e)

25
(f)

(g)

(h)

26
(i)

Beyond Syllabus Programs:

1. Write a Java program that displays the number of characters, lines and words in a
text file.

Algorithm:

1. Start the program, import the packages.


2. create an object of ‗fi„ using fileinputstream class
3. compute count=0,word=0,line=1,space=0
4. repeate ‗4„ until file is empty
5. if fi.read() equal to new line then
increment line
else
fi.read() equal to space then
increment word
else
increment char
6. print word,line,char
7. End

Output:

27
2. Write a Java program using Interfaces.

Algorithm:

Declare an Interface:
1.Declare interface printable
2.Declare the method print()
Create the class and call the interface:
3.class IntDemo implements printable
4.Implement the print method
5.public static void main(String args[])
6.Create object for Class IntDemo obj = new IntDemo();
7.Call Print method
8.clopse main()
9.close class

Output:

Hello

3. Write a Java program to illustrate user defined packages.

Algorithm:
Creating the Package:
1.package animals;
2.public interface Animal
3.declare eat() as public
4. declare travel() as public
Importing Package:
5.Import animals.*;
6.public class MammalInt implements Animal
7.Implement eat()
8.Implement travel()
9.public int noOfLegs(){
10. return 0;
11. public static void main(String args[])
12. Create object for the class MammalInt m = new MammalInt();
13. Call eat()
14.Call travel()
15.close main()
16.close class

Output:

28
Mammal eats
Mammal travels

4. Write a java program to illustrate usage of all String handling methods.

Algorithm:
1.create a class
2.create a main()
3. creating string by java string literal
4. converting char array to string
5. creating java string by new keyword
6.print strings

Output:
java
strings
example

5. Develop an applet that displays a simple message.

Algorithm:
1. import java.applet.Applet, java.awt.* packages
2. Include the /*<Applet code="Simple" height=500 width=500> </Applet>*/
3. Create class Simple extends Applet
4. Declare void paint(Graphics g)
5. g.drawString("Hello World",10,20);
6. End

Output:

29

You might also like