0% found this document useful (0 votes)
35 views154 pages

212CSE2403 - JP Lab Manual

This document provides information about a Java programming lab manual for an integrated course practical. It includes a table of contents listing 16 experiments covering topics like basic Java programs, object-oriented programming, inheritance, interfaces, exceptions, files, threads, generics, GUI, and networking. It also outlines the course plan, listing objectives, career opportunities, pre-requisites, and mappings of course, program, and program educational outcomes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views154 pages

212CSE2403 - JP Lab Manual

This document provides information about a Java programming lab manual for an integrated course practical. It includes a table of contents listing 16 experiments covering topics like basic Java programs, object-oriented programming, inheritance, interfaces, exceptions, files, threads, generics, GUI, and networking. It also outlines the course plan, listing objectives, career opportunities, pre-requisites, and mappings of course, program, and program educational outcomes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

SCHOOL OF COMPUTING

Department of Computer Science and Engineering

JAVA PROGRAMMING
(Integrated Course
Practical) LabManual
(212CSE2403)
Student Name : ……………………………………………………….

Register Number : ……………………………………………………….

Section : ………………………………………………………..

1
TABLE OF CONTENTS

S.No Topic Page No.

1 Bonafide Certificate

2 Experiment Evaluation Summary

3 Course Plan

4 Introduction

Experiments

5 Basic Java Programs

q Program using Objects and Classes

7 Program using Inheritance

8 Program using Interfaces

9 Program using Array List and String

10 Program using Exception Handling

11 Program using Reading and Writing Files

12 Program using Multithreading

13 Program using Generic Programming

14 Program using Event Handling, Swing and AWT

15 Program using Networking Socket,TCP and UDP

16 Progarm using Java Database Connectivity(JDBC)

15 Additional Experiments

2
SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

BONAFIDE CERTIFICATE

Bonafide record of work done by


of _ in
during even/odd semester in academic year

Staff In-charge Head of the Department

Submitted to the practical Examination held at Kalasalingam University, Krishnankoil on

REGISTER NUMBER

Internal Examiner External Examiner

3
EXPERIMENT EVALUATION SUMMARY

Name: Reg No:

Class: Faculty:

Marks Faculty
S.No Date Experiment
(100) Signature

10

11

12

4
COURSE PLAN

Subject with code JAVA PROGRAMMING - 212CSE2403

Course B.Tech (CSE)

Semester / Sec IV/ALL

Course Category / Course Credits Integrated Course Practical (ICP) / 4 Credits

Course Teachers Dr.Ramalakshmi, D r . A . P a n d i a r a j , Mr.Vignesh,


Mr.Pon suresh, Dr.Jane Rubel Angelina,
Mr.SureshKumar, Dr.Sampradeepraj,
Ms.Vetriselvi,Ms.Kalaiarasi,Ms.Mariashanthi,Mr.S.
Kailasam,Dr.M.Karuppasamy,Mr.M.K.Nagarajan
Dr.Partheeban,Dr.K.Kartheeban,Dr.S.Subhashini,
Ms.Ishvarya,,Ms.Manochitra
Course Coordinator Dr.A.Pandiaraj

Module Coordinator Dr. R.Ramalakshmi

Programme Coordinator Dr. N.C.Brintha

Pre-Requisite:

● Needs to have knowledge on Basic programming Language


● Object Oriented programming
● Fundamental knowledge about Internet and Web Concepts.
Course Description

Java still has its importance and popularity in the software industry, in spite of recent
development of several high level languages. It has an excellent support of high-level as well as
low-level functionality, which makes it suitable for many applications. Emphasis is placed on
event-driven programming methods, including creating and manipulating objects, classes, and
using object-oriented tools such as the class debugger. This course has been approved to satisfy

5
the Comprehensive Articulation Agreement for transferability as a pre-major and/or elective
course requirement. This course provides students with a comprehensive study of the Java
programming language. Classroom lectures stress the strengths of Java, which provide the
students with the means of writing efficient, maintainable, and portable code. The lectures are
supplemented with lab exercises. This course will also help the students during their placement sittings,
as most of the companies test proficiency in programming using Java.

Career Opportunities:

Java is typically used for fairly High-level development. It is used in embedded systems, which
is often listed as a computer engineering position (rather than computer science, or software
engineering.). Java is also used for device drivers and Graphical math utility code for larger projects
and used for development of browsers, instant messengers, server daemons, and network
code. Graduates may work as team members to analyze business requirements, design, develop,
and implement appropriate web solutions to the user community. The graduates of this
program will find employment in both small-size and mid-size business as well in larger
enterprises. Graduates may find jobs that involve developing or designing web pages, and
working with computer programming languages. These skills may be used to supplement a
career choice, or may be used to obtain the following entry-level job titles:

● Software developer
● Programmer
● Network administrator
● Web developer
Course Objectives:

● To understand Object Oriented Programming concepts and characteristics of Java


● To know the principles of packages, inheritance, exceptions and interfaces.
● To develop a java application with threads and generics classes
● To design and build simple Graphical User Interfaces
● To build applications using java programming for real-world applications.
Program Educational Objectives Components (PEOs)

PEO1: The Graduates will be technically competent to excel in IT industry and to pursue higher
studies.
6
PEO2: The Graduates will possess the skills to design and develop economically and technically
feasible computing systems using modern tools and techniques.

PEO3: The Graduates will have effective communication skills, team spirit, ethical principles
and the desire for self learning to succeed in their professional career.

Program Specific Outcomes (PSOs)

PSO1: Problem-Solving Skills: The ability to apply mathematics, science and computer
engineering knowledge to analyze, design and develop cost effective computing solutions for
complex problems with environmental considerations.

PSO2: Professional Skills: The ability to apply modern tools and strategies in software project
development using modern programming environments to deliver a quality product for
business accomplishment.

PSO3: Communication and Team Skill: The ability to exhibit proficiency in oral and written
communication as individual or as part of a team to work effectively with professional
behaviors and ethics.

PSO4: Successful Career and Entrepreneurship: The ability to create a inventive career path by
applying innovative project management techniques to become a successful software
professional, an entrepreneur or zest for higher studies.

Programme Outcomes (POs)

PO1: Ability to apply knowledge of mathematics, science and computer engineering to solve
computational problems.

PO2: Ability to identify, formulates, Analyse and derives conclusions in complex computing
problems.

PO3: Capability to design and develop computing systems to meet the requirement of industry
and society with due consideration for public health, safety and environment.
PO4: Ability to apply the knowledge of design of experiment and data analysis to derive
solutions in complex computing problems.
PO5: Ability to develop and apply modeling, simulation and prediction tools and techniques to
engineering problems.
7
PO6: Ability to assess and understand the professional, legal, security and societal
responsibilities relevant to computer engineering practice.
PO7: Ability to understand the impact of computing solutions in economic, environmental and
societal context for sustainable development.
PO8: Applying ethical principles and commitment to ethics of IT and software profession.
PO9: Ability to work effectively as an individual as well as in teams.
PO10: Ability to communicate effectively with technical community and with society.
PO11: Demonstrating and applying the knowledge of computer engineering and management
principles in software project development and in multidisciplinary areas.
PO12: Understanding the need for technological changes and engage in life-long learning.

Course Outcomes (Cos):

CO1. Understand the object oriented concepts using Java


CO2. Apply Object Oriented Concepts to develop Java Application
CO3. Identify, Formulate and Analyze a Real World Problem and Develop a solution using
Java Programming Concepts
CO4. Ability to Work individually as well as in team to solve problem
CO5. Communicate effectively with technical community during Interviews
PO and PEO Mapping

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PO1
0 1 2

PEO1 S S S S S L L S S

PEO2 L S S S S S S

PEO3 S S S S S S L S

CO and PO Mapping

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 S S S S S M L M S S

8
CO2 S S S S S M M M S S

CO3 S S S S S M M M S S

CO4 S S S S S M M M S S

CO5 S S S S S M M M S S

S- Strong Correlation M- Medium Correlation L – Low Correlation

PSO and PO Mapping

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

PSO1 S S S S

PSO2 S S S M S

PSO3 S M S S S

PSO4 M S M M M S S

CO and PSO Mapping

CO CO CO CO CO CO CO
1 2 3 4 5 6 7
PSO1 S S S S S S S

PSO2 S S S S S S S

PSO3 S S S S S S S

PSO4 M M M M M M M

ABET -CSO:
CSO1 - Analyze a complex computing problem and to apply principles of computing and

other relevant disciplines to identify solutions.

CSO2 – Design, implement, and evaluates a computing-based solution to meet a given set
of computing requirements in the context of the program’s discipline.

CSO3 – Communicate effectively in a variety of professional contexts.

CSO4 – Recognize professional responsibilities and make informed judgments in


14
computing practice based on legal and ethical principles.

CSO5 – Function effectively as a member or leader of a team engaged in activities


appropriate to the program’s discipline.

CSO6 – Apply Computer Science theory and software development fundamentals to produce
computing-based solutions.
ABET- ESO:

ESO1 - Ability to identify, formulate and solve complex engineering problems by


applying principles of Engineering, Science, and Mathematics.

ESO2 - Ability to apply engineering design to produce solutions that meet specified needs
with consideration of public health, safety, and welfare, as well as global, cultural,
social, environmental, and economic factors.

ESO3 - An ability to communicate effectively with a range of audiences.

ESO4 - Ability to recognize ethical and professional responsibilities in engineering


situations and make informed judgments, which must consider the impact of
engineering solutions in global, economic, environmental, and societal contexts.

ESO5 - Ability to function effectively on a team whose members together provide


leadership, create a collaborative and inclusive environment, establish goals, plan
tasks, and meet objectives.

ESO6 - Ability to develop and conduct appropriate experimentation, analyze and


interpret data, and use engineering judgment to draw conclusions.

ESO7 - Ability to acquire and apply new knowledge as needed, using appropriate learning
strategies.

Mapping of Course Outcomes with SO:

CSO1 CSO2 CSO3 CSO4 CSO5 CSO6 ESO1 ESO2 ESO3 ESO4 ESO5 ESO6 ESO7

CO1 S M M S L

CO2 S M S M

CO3 S M M S M L

15
CO4 S L L S M

CO5 S M S

CO6 S M S M

CO7 S M S

List of Experiments:

Experi Cumulati
No. of
ment Name of the Experiment ve No. of
periods
No. periods

1. Basic Java Programs 6 6

2. Program using Objects and Classes 6 12

3. Program using Inheritance 4 16

4. Program using Interfaces 6 22

5. Program using Array List and String 2 24

6. Program using Exception Handling 6 30

7. Program using Reading and Writing Files 3 33

8. Program using Multithreading 3 36

9. Program using Generic Programming 6 42

10. Program using Event Handling, Swing and AWT 6 48

11. Program using Network Socket TCP and UDP 6 54

12 Program using Java Database connectivity (JDBC) 6 60

16
Rubrics for Internal and External Experiment Assessment:

Module Rubrics for assessment Marks (100)

Poor : 0 - 5 (Not able to understand what is given and what is expected)


Normal : 5 - 10 ( Understood what is given but can't decide what is
Efficiency
expected))
of Good : 10 - 15 (Understood what is given and Understood the stated 20
Algorithm expectation)
Very Good : 15 - 20 ( Understood what is given and understood the
stated expectation as well as the hidden expectation)
Extraordinary : 35-40 Marks (With good time and space complexity)
Efficiency
Used efficient algorithms : 25 - 35 40
of program Met problem requirements : 15 - 25
Poor Logic : 0 - 15 Marks
Aesthetic Output : 15 - 20
Output 20
User interactive input and output : 5 - 15
No proper user interactive I/O operation : 0 - 5
Answered for more than 80 % Qs : 16 - 20 Marks
Viva
50% - 80% - 11 - 15 Marks 20
questions 25% - 50 % - 6- 10 Marks
0%-25% - 0 - 5 Marks

Mark Distribution for Regular Experiments:


VIVA VOICE
Efficiency Efficienc
Outp Comm
S.No Experiments of y of Tech
ut
Algorithm program uincati
nical
on

1. 25 25 20 20 10
Basic Java Programs
2. Program using Objects and 25 30 15 20 10
Classes
3. 25 30 15 20 10
Program using Inheritance
4. 30 30 10 20 10
Program using Interfaces
5. 30 30 10 20 10
Program using Array List and String
6. 30 25 15 20 10
Program using Exception Handling
7. Program using Reading and Writing 30 25 15 20 10
Files
8. 25 25 15 25 10
Program using Multithreading
17
9. 30 30 20 10 10
Program using Generic Programming
10. Program using Event Handling, 30 30 20 10 10
Swing and AWT
11 Program using Network Socket TCP 25 30 25 10 10
and UDP
12. Program Using Database 25 30 25 10 10
Connectivity(JDBC)

INTRODUCTION
Java is a general-purpose computer-programming language that is concurrent, class-
based, object-oriented, and specifically designed to have as few implementation dependencies
as possible. It is intended to let application developers "write once, run anywhere"
(WORA), meaning that compiled Java code can run on all platforms that support Java without
the need for recompilation. Java applications are typically compiled to bytecode that can run on
any Java virtual machine (JVM) regardless of computer architecture. As of 2016, Java is one of
the most popular programming languages in use, particularly for client-server web
applications, with a reported 9 million developers. Java was originally developed by James
Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and
released in 1995 as a core component of Sun Microsystems' Java platform. The language derives
much of its syntax from C and C++, but it has fewer low-level facilities than either of them.

The main objective of this course is to identify and apply suitable data structures and
algorithms for problem solving using Java. Also students may need to make time and space
complexity analysis for writing programs efficiently. The laboratory course is integrated with
theory contents; hence students can use their theoretical strength and apply the same in
practical to upgrade their knowledge.
The laboratory contents include the following categories of programs: Basic OOP
concepts, Inheritance and Interfaces, Exception Handling, Threads and Synchronization, File
Handling, Generics, Applets and Event Handlers to solve various classes of problems. The contents
will be dealt in theory classes before being implemented in laboratory. This helps students
in mastering problem solving and also able to provide efficient solution in terms of time and
space.
Being a core course of Computer Science and Engineering, Java Programming course is more

18
useful in qualifying certification courses like Oracle Certified Java Professional (OCJP). Through
this integrated course, student can get more knowledge and be able to solve problems using Java
programming.

19
Ex .No 1 Basic Java Programs
Objective:

To make the students to get familiar in problem decomposition by using functions


in java programming
To know how to use data types, objects, class and their uses in java

Theory:

Variables and Data Types in Java

Variable is a name of memory location. There are three types of variables in java: local, instance
and static. There are two types of data types in java: primitive and non-primitive.

Types of Variable

There are three types of variables in java:

local variable
instance variable
static variable

1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable .
It is not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables in java


class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90;//local variable
}
}
20
The Java.io.BufferedReader class reads text from a character-input stream, buffering characters
so as to provide for the efficient reading of characters, arrays, and lines. Following are the
important points about BufferedReader:

The buffer size may be specified, or the default size may be used.
Each read request made of a Reader causes a corresponding read request to be made of
the underlying character or byte stream.

Class declaration

Following is the declaration for Java.io.BufferedReader class:

public class BufferedReader extends Reader

Field

Following are the fields for Java.io.BufferedReader class:

protected Object lock -- This is the object used to synchronize operations on this stream.

Creating Objects

In Java, you create an object by creating an instance of a class or, in other words, instantiating a
class. Often, you will see a Java object created with a statement like the following, which creates
a new Rectangle object from the Rectangle class given in the previous section:

Rectangle rect = new Rectangle();

ARRAYS

Arrays are generally effective means of storing groups of variables. An array is a


group of variables that share the same name and are ordered sequentially from zero to one
less than the number of variables in the array. The number of variables that can be stored in
an array is called the array's dimension. Each variable in the array is called an element of the
array.

Creating Arrays:

There are three steps to creating an array, declaring it, allocating it and initializing it.

Declaring Arrays:
Like other variables in Java, an array must have a specific type like byte, int, String or double.
Like all other variables in Java an array must be declared. When you declare an array variable
you suffix the type with [] to indicate that this variable is an array. Here are some examples:

21
int k[];
float yt[];
String names[];

In other words you declare an array like you'd declare any other variable except you
append brackets to the end of the variable type.

Allocating Arrays

Declaring an array merely says what it is. It does not create the array. To actually
create the array (or any other object) use the new operator.

k = new int[3];
yt = new float[7];
names = new String[50];

The numbers in the brackets specify the dimension of the array; i.e. how many slots it
has to hold values. With the dimensions above k can hold three ints, yt can hold seven
floats and names can hold fifty Strings.

Initializing Arrays

Individual elements of the array are referenced by the array name and by an integer
which represents their position in the array. You can use array elements wherever you'd use
a similarly typed variable that wasn't part of an array. Here's how we'd store values in the
arrays we've been working with

k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred"; This step is called initializing the array or, more precisely, initializing the
elements of the array.

Two Dimensional Arrays

Declaring, Allocating and Initializing Two Dimensional Arrays

Two dimensional arrays are declared, allocated and initialized much like one
dimensional arrays. However we have to specify two dimensions rather than one, and we
typically use two nested for loops to fill the array. The array examples above are filled with
the sum of their row and column indices. Here's some code that would create and fill such
an array:

class FillArray

22
{
public static void main (String args[])
{int M[][];
M = new int[4][5];
for (int row=0; row < 4; row++)

{
for (int col=0; col < 5; col++)

{
M[row][col] = row+col;
} }
}}

In two-dimensional arrays Array Index Out Of Bounds errors occur whenever you exceed
the maximum column index or row index. Unlike two-dimensional C arrays, two-
dimensional Java arrays are not just one-dimensional arrays indexed in a funny way.

Multidimensional Arrays

You don't have to stop with two dimensional arrays. Java lets you have arrays of three,
four or more dimensions. The syntax for three dimensional arrays is a direct extension of
that for two-dimensional arrays. Here's a program that declares, allocates and initializes a three-
dimensional array:

class Fill3DArray

{
public static void main (String args[])
{int M[][][];
M = new int[4][5][3];
for (int row=0; row < 4; row++)

Title of the Program:

Finding GCD of two numbers

Sample Program:

GCD of a number using For loop

public class GCD {


public static void main(String[] args)
{int n1 = 81, n2 = 153, gcd = 1;
for(int i = 1; i <= n1 && i <= n2; ++i)
{
// Checks if i is factor of both integers
if(n1 % i==0 && n2 % i==0)
23
gcd = i;
}
System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
}

Output:
G.C.D = 9

GCD of a Number using While Loop Statement:

public class GCD {


public static void main(String[] args)
{int n1 = 81, n2 = 153;
while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
System.out.println("G.C.D = " + n1);
}
}

Output:
G.C.D = 9

List of Exercise:

1. Find mean and standard deviation


2. Printing a given pattern (number and character)
3. Find the second and third maximum number in an array
4. Find the ncr and npr
5. Calculate simple and compound interest
6. Solve a series using mathematical functions
7. Apply linear search and binary search to find a number
8. Print all prime numbers in the given range
9. Print the fibonacci series
10. Find sum of the digits
11. Check whether a given number is palindrome or not
12. Check whether a given number is primefactor or not.
13. Check wether a given number is perfect number or not
14. Check whether a given number is armstrong number or not
15.. Check whether a given number is deficient number or not
21
16. Finding GCD of two numbers
17. Apply any one of the sorting algorithm
18. Number conversion from decimal to binary
19. Distance conversion
20. Write a program to complete and exp(e)
21. Write a program to add, subtract and multiply matrices
22. Program to compute row sum, column sum and trace of a matrix
23. Write a java program to implement simple Chatbot like Automatic Teller Machine
24. Create a Word builder game.
25. Develop a java application to implement currency converter (Dollar to INR, EURO to
INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice
versa),time converter (hours to minutes, seconds and vice versa) using packages.

Additional Programs
1. Write a program called Harmonic Sum to compute the sum of a harmonic series, as shown
below, where n=50000. The program shall compute the sum from left-to-right as well as
from the right-to-left. Are the two sums the same? Obtain the absolute difference between
these two sums and explain the difference. Which sum is more accurate?

2. Write a program which prompts user for the number of students in a class (a non- negative
integer), and saves it in an int variable called numStudents. It then prompts user for the
grade of each of the students (integer between 0 to 100) and saves them in an int array called
grades. The program shall then compute and print the average (in double rounded to 2
decimal places) and minimum/maximum (in int).
3. Write a Java program to separate 0s on left side and 1s on right side of an array of 0s and 1s
in random order.
4. Write a Java program to add and remove a specific element from an array.
5. Write a program that prompts user for the mark (between 0-100 in int) of 3 students;
computes the average (in double); and prints the result rounded to 2 decimal places. Your
program needs to perform input validation.
6. Write a program to computer SalesTaxCalculator
7. Write a program to compute income tax for a given gross salary
8. Write a program called CozaLozaWoza which prints the numbers 1 to 110, 11 numbers per
line. The program shall print "Coza" in place of the numbers which are multiples of 3, "Loza"
for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for multiples of 3 and 5, and so on.
The output shall look like:
1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza

9. Write a program that can convert degrees Fahrenheit to degrees Celsius, or vice versa

22
10. Given the size, return a square matrix of numbers in spiral order.
11. Write a program that prints a conversion table from miles to kilometers.
12. Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current month
reading, type of EB connection (i.e domestic or commercial). Compute the bill amount
using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
a. First 100 units - Rs. 1 per unit
b. 101-200 units - Rs. 2.50 per unit
c. 201 -500 units - Rs. 4 per unit
d. > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
e. First 100 units - Rs. 2 per unit
f. 101-200 units - Rs. 4.50 per unit
g. 201 -500 units - Rs. 6 per unit
h. > 501 units - Rs. 7 per unit

13. Develop a java application to implement currency converter (Dollar to INR, EURO to INR,
Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa), time
converter (hours to minutes, seconds and vice versa) using packages.

23
Viva questions

1. What are the data types used in java


2. What is the expansion on JVM?
3. What is inner class?
4. What is polymorphism?
5. What is encapsulation?
6. What is constructor?
7. What is methods
8. What are access specifiers?
9. Define abstraction.
10. Define classes and objects in Java.
11. Explain the syntax of object creation.
12. What is array?
13. What is single dimensional array?
14. What is two dimensional array?
15. What is multi dimensional array?
16. What is objects?

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

24
Ex .No 2 Program Using Object and Classes

Objective

To understand the concepts of objects and class in java

Theory:

OBJECT:

Objects are key to understanding object-oriented technology. Look around right now and you'll
find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. These real-world
observations all translate into the world of object-oriented programming. Software objects are
conceptually similar to real-world objects: they too consist of state and related behavior. An
object stores its state in fields (variables in some programming languages) and exposes its
behavior through methods (functions in some programming languages).

Creating Objects

In Java, you create an object by creating an instance of a class or, in other words, instantiating a
class. Often, you will see a Java object created with a statement like the following, which creates
a new Rectangle object from the Rectangle class given in the previous section:
Rectangle rect = new Rectangle();
CLASS:

In the real world, you'll often find many individual objects all of the same kind. There may be
thousands of other bicycles in existence, all of the same make and model. Each bicycle was built
from the same set of blueprints and therefore contains the same components.

Object is the physical as well as logical entity whereas class is the logical entity only. Object is
an instance of a class. Class is a template or blueprint from which objects are created. So object
is the instance(result) of a class.

Title of the Program

Write the java program to create linked list implementation using classes and objects

import java.util.*;
public class LinkedListExample {
public static void main(String args[]) {

/* Linked List Declaration */


LinkedList<String> linkedlist = new LinkedList<String>();

25
/*add(String Element) is used for adding
* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");

/*Display Linked List Content*/


System.out.println("Linked List Content: " +linkedlist);

/*Add First and Last Element*/


linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after addition: " +linkedlist);

/*This is how to get and set Values*/ Object


firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update by set method: " +firstvar2);

/*Remove first and last element*/


linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);

/* Add to a Position and remove from a position*/


linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
}
}

Output:
Linked List Content: [Item1, Item5, Item3, Item6, Item2]

LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6, Item2, Last Item]

First element: First Item

First element after update by set method: Changed first item

LinkedList after deletion of first and last element: [Item1, Item5, Item3, Item6, Item2]

26
Final Content: [Newly added item, Item1, Item3, Item6, Item2]

List of Experiments

1. Create a class called Employee that includes three pieces of information as


instance variables—a first name (typeString), a last name (typeString) and a
monthly salary (double). Your class should have a constructor that initializes the
three instance variables. Provide a set and a get method for each instance
variable. If the monthly salary is not positive, set it to 0.0. Write a test application
named EmployeeTest that demonstrates class Employee’s capabilities. Create
two Employee objects and display each object’s yearly salary. Then give each
Employee a 10% raise and display each Employee’s yearly salary again.
2. Create a class called Invoice that a hardware store might use to represent an
invoice for an item sold at the store. An Invoice should include four pieces of
information as instance variables‐a part number(type String),a part description(type
String),a quantity of the item being purchased (type int) and a price per item
(double). Your class should have a constructor that initializes the four instance
variables. Provide a set and a get method for each instance variable. In addition,
provide a method named getInvoice Amount that calculates the invoice amount
(i.e., multiplies the quantity by the price per item), then returns the amount as a
double value. If the quantity is not positive, it should be set to 0. If the price per
item is not positive, it should be set to 0.0. Write a test application named
InvoiceTest that demonstrates class Invoice’s capabilities.
3. Create a class called Date that includes three pieces of information as instance
variables—a month (typeint), a day (typeint) and a year (typeint). Your class
should have a constructor that initializes the three instance variables and
assumes that the values provided are correct. Provide a set and a get method for
each instance variable. Provide a method displayDate that displays the month,
day and year separated by forward slashes(/). Write a test application named
DateTest that demonstrates classDate’s capabilities.
4. Create class SavingsAccount. Usea static variable annualInterestRate to store the
annual interest rate for all account holders. Each object of the class contains a private
instance variable savingsBalance indicating the amount the saver currently
has ondeposit. Provide method calculateMonthlyInterest to calculate the monthly
interest by multiplying the savingsBalance by annualInterestRate divided by 12 this
interest should be added to savingsBalance. Provide a static method
modifyInterestRate that sets the annualInterestRate to a new value. Write a
program to test class SavingsAccount. Instantiate two savingsAccount objects,
saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest and print the new
balances for both savers. Then set the annualInterestRate to 5%, calculate the next
month’s interest and print the new balances for both savers.
5. Create a class called Book to represent a book. A Book should include four pieces
of information as instance variables‐a book name, an ISBN number, an author
27
name and a publisher. Your class should have a constructor that initializes the
four instance variables. Provide a mutator method and accessor method (query
method) for each instance variable. Inaddition, provide a method named
getBookInfo that returns the description of the book as a String (the description
should include all the information about the book). You should use this keyword
in member methods and constructor. Write a test application named BookTest to
create an array of object for 30 elements for class Book to demonstrate the class
Book's capabilities.
Program:

28
29
30
31
32
33
34
Viva questions

1. Define array of objects in Java with syntax.


2. Define static in Java.
3. Define Scanner class in Java.
4. Define BurfferedInputReader class in Java.
5. Define collections in Java.

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

35
Ex .No 3 Program Using Inheritance
Objective:

To understand the fundamentals of inheritance


To develop skills on how to use inheritance to simplify development of new classes
To understand the concepts such as overridden function, protected access specifier and
the sequence of constructor and destructor

Theory

Different kinds of objects often have a certain amount in common with each
other. Mountain bikes, road bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also
defines additional features that make them different: tandem bicycles have two seats
and two sets of handlebars; road bikes have drop handlebars; some mountain bikes
have an additional chain ring, giving them a lower gear ratio. Object-oriented
programming allows classes to inherit commonly used state and behavior from other
classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike,
and TandemBike. In the Java programming language, each class is allowed to have one
direct superclass, and each superclass has the potential for an unlimited number of
subclasses:

The syntax for creating a subclass is simple. At the beginning of your class declaration,
use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {


// new fields and methods defining a mountain bike would go here
}

This gives Mountain Bike all the same fields and methods as Bicycle, yet allows its code
to focus exclusively on the features that make it unique. This makes code for your subclasses
easy to read. However, you must take care to properly document the state and behavior
that each superclass defines, since that code will not appear in the source file of each
subclass. Java Inheritance defines a relationship between a superclass and its
36
subclasses. This means that an object of a subclass can be used wherever an object of the
superclass can be used. Class Inheritance in java mechanism is used to build new
classes from existing classes. The inheritance relationship is transitive: if class x extends
class y, then a class z, which extends class x, will also inherit from class y.

Below are the different types of inheritance which is supported by Java.

Single Inheritance.
Multiple Inheritance (Through Interface)
Multilevel Inheritance.
Hierarchical Inheritance.
Hybrid Inheritance (Through Interface)

Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid

Below are Various types of inheritance in Java. We will see each one of them one by one with the
help of examples and flow diagrams.

1) Single Inheritance

Single inheritance is damn easy to understand. When a class extends another one class only
then we call it a single inheritance. The below flow diagram shows that class B extends only one
class which is A. Here A is a parent class of B and B would be a child class of A.

Single Inheritance example program in Java

Class A
{
public void methodA()
{
System.out.println("Base class method");
}}

Class B extends A
{
public void methodB()
{

37
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}}

2) Multiple Inheritance

“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with “multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.

Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance
often leads to problems in the hierarchy. This results in unwanted complexity when further
extending the class.

Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.

3) Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see
in below flow diagram C is subclass or child class of B and B is a child class of A.

38
Multilevel Inheritance example program in Java

Class X
{
public void methodX()
{
System.out.println("Class X method");
}}

Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}}

Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

4) Hierarchical Inheritance
39
In such kind of inheritance one class is inherited by many sub classes. In below example class
B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.

5) Hybrid Inheritance

In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple
inheritance. A typical flow diagram would look like below. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you
heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java.

Title of the Program:

Write a java program to create an abstract class named shape that contains two integers and
an empty method named print Area(). Provide three classes named Rectangle,, Triangle and
Circle such that each one of the classes extends the class shape. Each one of the class contains
only the method print Area() that print the area of the given shape

class Shape
{
//define a length which is public and can be used in square,
//rectangle and circle classes
public int length = 10;
}

40
//inherit the properties of Shape class with the use of extends keyword

class Square extends Shape


{
void area()
{
//calculate area of square
int area = length * length;

//print it on the screen


System.out.println("Area of square : "+area);
}
}

class Rectangle extends Shape


{
void area()
{
//define a breadth
int breadth = 7;
//calculate area of rectangle
int area = length * breadth;
//print on the screen
System.out.println("Area of rectangle : "+area);
}
}

class Circle extends Shape


{
void area()
{
//calculate area of circle using length of the shape class as radius
float area = 3.14f * length * length;
//print on the screen
System.out.println("Area of circle : "+area);
}
}

//make a entry class which contains main method


class InheritanceDemo
{
public static void main(String[] args)
{
//object of child class square
41
Square sq = new Square();
//object of child class rectangle
Rectangle rec = new Rectangle();
//object of child class circle
Circle cir = new Circle();

//call the area methods of all child class to


//get the area of different objects
sq.area();
rec.area();
cir.area();
}
}

Output:

Area of Square: 100

Area of Rectangle: 70

Area of Circle: 314.0

List of Experiments:

1. Develop a java application with Employee class with Emp_name, Emp_id,Address,


Mail_id, Mobile_no as members. Inherit the classes, Programmer,Assistant
Professor, Associate Professor and Professor from employee class. AddBasic Pay
(BP) as the member of all the inherited classes with 97% of BP as DA, 10 % of
BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate pay slips for
the employees with their gross and net salary
2. College admission and degree distribution using inheritance
3. License approval using inheritance

Program:

42
43
44
45
46
47
48
49
Viva questions

1. Define Collections in Java with examples.


2. Define Inheritance in Java.
3. What are the types of inheritances in Java?
4. Explain the syntax of inheriting classes.
5. Compare the types of collections.
6. What are the implications of using public, private and protected access specifier for
declaring class members for a base class
7. Describe the base class access control mechanism
8. What is method overriding
9. Different types of inheritance
10. What are the advantages offered by inheritance
11. Mention the members of base class which can’t be inherited

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

50
Ex .No 4 Program Using Interfaces
Objective:

. • To learn about the concept of interface

Theory

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods
only. The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be
instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.


By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members. In other words, Interface fields are public,
static and final bydefault, and methods are public and abstract.

51
Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Simple example of Java interface


In this example, Printable interface have only one method, its implementation is provided in
the A class.

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}

Output: Hello

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

52
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome

Multiple inheritance is not supported through class in java but it is possible by interface,
why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case
of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
interface Printable
{
void print();
53
}
interface Showable
{
void print();
}
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestTnterface1 obj = new TestTnterface1();
obj.print();
}
}
Hello

As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance

A class implements interface but one interface extends another interface .

interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class Testinterface2 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[]) 54
{
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}

List of Experiments

1. Semester exam mark calculation inheritance and interface(CO2)


2. Area calculation using Interface(CO2)
3. Design a Java interface for ADT Stack. Implement this interface using array.
Provide necessary exception handling in both the implementations.
4. Write a program to perform string operations using ArrayList. Write functions
for the following
a. Append - add at end
b. Insert – add at particular index
c. Search
d. List all string starts with given letter
5. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method print Area () that prints
the area of the given shape.
6. Program to calculate area of different figures using interfaces

Program

55
56
57
58
59
Viva questions

1. Define Interfaces in Java.


2. Define Packages in Java
3. Why multiple inheritance is not supported in Java?
4. Define super keyword and explain its uses.
5. Define Queue data structure.
6. What is the relationship between classes and interface
7. Multiple inheritance is not supported through class in java but it is possible by interface,
why?
8. What is marker or tagged interface?

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

60
Ex .No 5 Program Using Array List and String

Objective:

To write a Java program using Array list and Strings

Theory:
Java Array List

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:

Java ArrayList class can contain duplicate elements.


Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any
element is removed from the array list.

Program:

import java.util.*;
class ArrayList1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Invoking arraylist object
System.out.println(list);
}
}

Sample Output:

[Ravi, Vijay, Ravi, Ajay]


In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. Java String class provides a lot of methods to perform
operations on string such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
61
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output: java
strings
example

List of Experiments:

1. Write a program called PhoneKeyPad, which prompts user for a String (case insensitive),
and converts to a sequence of keypad digits
2. Write a program called CountVowelsDigits, which prompts the user for a String, counts
the number of vowels (a, e, i, o, u, A, E, I, O, U) and digits (0-9) contained in the string,
and prints the counts and the percentages
3. Write a program called ReverseString, which prompts user for a String, and prints the
reverse of the String by extracting and processing each character.
4. Write a Java Program that reads a line of integers, and then displays each integer, and the
sum of all the integers (Use StringTokenizer class of java.util)
5. Write a Java program to return the sum of the digits present in the given string. If there is
no digits the sum return is 0.
6. Write a Java program to return a new string using every characters of even positions from
a given string. ( Java Programming)
7. Write a Java program that checks whether a given string is palindrome or not.
8. Write a Java program to sort a list of names in ascending order.
9. Write a Java program to concatenate a given string with itself of a given number of times.
10. Write a Java program to counts occurrences of a certain character in a given string.

Program:

62
63
64
65
66
67
Viva Questions

1. Define String Class in Java.


2. Compare String Builder and String Tokenizer in Java.
3. Define Array List

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

68
Ex .No 6 Program Using Exception Handling

Objective

To learn about the exception handling concepts


How to implement exception handling in java

Theory

Exception Handling in Java

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.In this page, we will learn about java
exception, its type and the difference between checked and unchecked exceptions.

What is exception

Dictionary Meaning: Exception is an abnormal condition.In java, exception is an event that


disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.
69
Hierarchy of Java Exception classes

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-
time.

2) Unchecked Exception

70
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.


71
1. try
2. catch
3. finally
4. throw
5. throws

Program

public class

JavaExceptionExample{ public static

void main(String args[]){try{

//code that may raise exception

int data=100/0;

}catch(ArithmeticException e){System.out.println(e);}

//rest code of the program

System.out.println("rest of the code...");

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

List of Experiments

1. Write a program that creates a user interface to perform integer divisions. The user
enters two numbers in the textfields, Num1 and Num2. The division of Num1 and
Num2 is displayed in the Result field when the Divide button is clicked. If Num1
or Num2 were not an integer, the program would throw NumberFormatException.
If Num2 were Zero, the program would throw an ArithmeticException.Display
theexception in a message dialog box (co3)
2. Java programs to create an bank account with minimum balance, deposit amount,
withdraw amount and throws LessBalanceException, create a
LessBalanceException class which returns a statement says withdraw amount is
not valid, creates 2 accounts and try to withdraw more money than account and see
which type of exception occurs. (CO3)
72
3. Write a Java program to implement user defined exception handling.
4. Write a Java program that reads a file name from the user, displays information
about whether the file exists, whether the file is readable, or writable, the type of
file and the length of the file in bytes

Program:

73
74
75
76
Viva Questions
What is Exception handling
Types of Exception handling
Advantages of exception handling
What are the Java Exception Handling Keywords?
Difference between checked and unchecked exceptions

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

77
Ex .No 7 Program Using Reading and Writing File
Objective:

To develop a Java application using FIle I/O.

Theory

Java I/O (Input and Output) is used to process the input and produce the output based on
the input. Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations. We can perform file
handling in java by java IO API.

Stream

A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream
because it's like a stream of water that continues to flow.In java, 3 streams are created for us
automatically. All these streams are attached with console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and error message to the console.

System.out.println("simple message");
System.err.println("error message");

Reading and Writing Files

As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination. Here is
a hierarchy of classes to deal with Input and Output streams.

78
FileInputStream

This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.Following constructor takes
a file name as a string to create an input stream object to read the file –

InputStream f= new FileInputStream(“C:/java/hello”);

Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows –

File f=new File(“C:/java/hello”);

InputStream f= new FileInputStream(f)

Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.

79
Sr.No. Method & Description

public void close() throws IOException{}


1
This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

protected void finalize()throws IOException {}

2 This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more references
to this stream. Throws an IOException.

public int read(int r)throws IOException{}

3 This method reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be returned if it's
the end of the file.

public int read(byte[] r) throws IOException{}

4 This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will
be returned.

public int available() throws IOException{}


5
Gives the number of bytes that can be read from this file input stream.
Returns an int.

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the
file −

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
80
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.

Directories in Java

A directory is a File which can contain a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail, check a list of
all the methods which you can call on File object and what are related to directories.

Creating Directories

There are two useful File utility methods, which can be used to create directories −

The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the
directory cannot be created because the entire path does not exist yet.

The mkdirs() method creates both a directory and all the parents of the directory.

Listing Directories

You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows

Checking a File or Directory

You have a Path instance representing a file or directory, but does that file exist on the file
system? Is it readable? Writable? Executable?

Verifying the Existence of a File or Directory

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But
eventually you must access the file system to verify that a particular Path exists, or does not
exist. You can do so with the exists(Path, LinkOption...) and the notExists(Path,
LinkOption...) methods. Note that !Files.exists(path) is not equivalent to Files.notExists(path).
When you are testing a file's existence, three results are possible:

The file is verified to exist.


The file is verified to not exist.
The file's status is unknown. This result can occur when the program does not have access
to the file.

81
If both exists and not Exists return false, the existence of the file cannot be verified.

List of Experiments:

1. Write a 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 is writable, the type of file and the length of the file in bytes.
2. Write a Java program that reads a file and displays the file on the screen, with a
line number before each line.
3. Write a Java program that displays the number of characters, lines and words in a
text file.
4. Write a Java program to illustrate collection classes like (i) Array List, (ii) Iterator,
(iii)Hash map.
5. Convert the content of a given file into the uppercase content of the same file. (co3)

Program:

82
83
84
85
86
Viva Questions

What are the basic methods in File class?


How do you handle directories in Java?
How do you write to a file using FileWriter class?
How do you read from a file using FileReader class?
What is the use of BufferedWriter and BufferedReader classes in Java?
What is the use of PrintWriter class?
What are the differences between FileInputStream/FileOutputStream?
What is a stream?
How you will create a input stream?
What are the automatically created streams in java?
What is an input and output stream?
Is it possible to change directory by using File object?

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

87
Ex .No 8 Program using Multithreading
Objective:

To enhance the understanding of students about the underlying concepts of


multithreading
To implement the concept of threading using java

Theory:

Java is a multi-threaded programming language which means we can develop multi-


threaded program using Java. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the same time making optimal use
of the available resources specially when your computer has multiple CPUs.

By definition, multitasking is when multiple processes share common processing


resources such as a CPU. Multi-threading extends the idea of multitasking into applications
where you can subdivide specific operations within a single application into individual threads.
Each of the threads can run in parallel. The OS divides processing time not only among
different applications, but also among each thread within an application. Multi-threading
enables you to write in a way where multiple activities can proceed concurrently in the same
program.

Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle of the thread−

88
New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.

Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.

Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only
when another thread signals the waiting thread to continue executing.

Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.

Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread then you can achieve this by implementing
a Runnable interface. You will need to follow three basic steps −

Step 1

As a first step, you need to implement a run() method provided by a Runnableinterface.


This method provides an entry point for the thread and you will put your complete business
logic inside this method. Following is a simple syntax of the run() method −public void run( )

Step 2

As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class
that implements the Runnableinterface and threadName is the name given to the new thread.
89
Step 3

Once a Thread object is created, you can start it by calling start() method, which executes
a call to run( ) method. Following is a simple syntax of start() method − void start();

Create a Thread by Extending a Thread Class

The second way to create a thread is to create a new class that extends Thread class using the
following two simple steps. This approach provides more flexibility in handling multiple
threads created using available methods in Thread class.

Step 1

You will need to override run( ) method available in Thread class. This method provides an
entry point for the thread and you will put your complete business logic inside this method.
Following is a simple syntax of run() method −public void run( )

Step 2

Once Thread object is created, you can start it by calling start() method, which executes a call to
run( ) method. Following is a simple syntax of start() method void start( );

Title of the Program:

Java Thread Example by extending Thread class


class Multi extends Thread{
public void
run(){ System.out.println("thread is
running...");
}
public static void main(String
args[]){Multi t1=new Multi();
t1.start();
}
}

Output:thread is running...

Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String


90
args[]){Multi3 m1=new Multi3();

91
Thread t1 =new Thread(m1);
t1.start();
}
}

Output: thread is running..

List of Experiments:

1. Write a java program that implements a multi-threaded application that has threethreads.
First thread generates a random integer every 1 second and if the value is even, second
thread computes the square of the number and prints. If the value is odd, the third thread
will print the value of cube of the number.
2. A program to illustrate the concept of multi-threading that creates three threads. First
thread displays ―Good Morning‖ every one second, the second thread displays ―Hello‖
every two seconds and the third thread displays ―Welcome‖ every three seconds

Program:

92
93
94
95
Viva Questions

1) What is multithreading?
2) What is a difference between a preemptive scheduling and time slicing?
3) What is synchronization?
4) What is the difference between the notify() and notifyall()?
5) What is the use of join()?
6) What is thread?
7) What is difference between wait() and sleep() method?
8) When should we interrupt a thread?

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

96
Ex .No 9 Program Using Generic Programming

Objective
To write a program using Generic Class
Theory

Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types
at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects,
then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to
sort the array elements.
Generic Methods
You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.
The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).
Example
Following example illustrates how we can print an array of different type using a single Generic
method −

public class GenericMethodTest {


// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String args[]) {


// Create arrays of Integer, Double and Character
97
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");


printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}
This will produce the following result −

Output
Array integerArray contains:
12345

Array doubleArray contains:


1.1 2.2 3.3 4.4

Array characterArray contains:


HELLO

Bounded Type Parameters


There may be times when you'll want to restrict the kinds of types that are allowed to be passed
to a type parameter. For example, a method that operates on numbers might only want to accept
instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends
keyword, followed by its upper bound.

Example
Following example illustrates how extends is used in a general sense to mean either "extends"
(as in classes) or "implements" (as in interfaces). This example is Generic method to return the
largest of three Comparable objects −

public class MaximumTest {


// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z)


{T max = x; // assume x is initially the largest

98
if(y.compareTo(max) > 0) {
max = y; // y is the largest so far
}

if(z.compareTo(max) > 0) {
max = z; // z is the largest now
}
return max; // returns the largest object
}

public static void main(String args[])


{ System.out.printf("Max of %d, %d and %d
is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",


6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear",


"apple", "orange", maximum("pear", "apple", "orange"));
}
}
This will produce the following result −

Output
Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

Generic Classes
A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
Example
Following example illustrates how we can define a generic class −

public class Box<T>


{private T t;

99
public void add(T t) {

100
this.t = t;
}

public T get()
{return t;
}

public static void main(String[] args)


{ Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());


System.out.printf("String Value :%s\n", stringBox.get());
}
}
This will produce the following result −

Output
Integer Value :10
String Value :Hello World

List of Experiments:

1. Sorting using generic method


2. Stack using generic class
3. Write a java program to find the maximum value from the given type of elements
using a generic function

Program:

101
102
103
104
Viva Questions

1. Define Generics in Java.


2. Write the syntax of creating Generic class in Java.
3. Write the syntax of creating Generic method in Java.
4. Define Map Collection in Java with its types.
5. Define List and ArrayList Collections in Java.

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

105
Ex .No 10 Program using Event handling, Swing and AWT
Objective

To design a Java program with necessary event handlers, Swing and AWT

Theory

An applet is a small Internet-based program written in Java, a programming language for


the Web, which can be downloaded by any computer. The applet is also able to run in HTML.
The applet is usually embedded in an HTML page on a Web site and can be executed from
within a browser.
Java applets are executed in a sandbox by most web browsers, preventing them from
accessing local data like the clipboard or file system. The code of the applet is downloaded from
a web server, after which the browser either embeds the applet into a web page or opens a new
window showing the applet's user interface.
A Java applet extends the class java.applet.Applet, or in the case of
a Swing applet, javax.swing.JApplet. The class which must override methods from the applet
class to set up a user interface inside itself (Applet) is a descendant of Panel which is a
descendant of Container. As applet inherits from container, it has largely the same user interface
possibilities as an ordinary Java application, including regions with user specific visualization.
The first implementations involved downloading an applet class by class. While classes
are small files, there are often many of them, so applets got a reputation as slow-loading
components. However, since .jars were introduced, an applet is usually delivered as a single file
that has a size similar to an image file (hundreds of kilobytes to several megabytes).
The domain from where the applet executable has been downloaded is the only domain
to which the usual (unsigned) applet is allowed to communicate. This domain can be different
from the domain where the surrounding HTML document is hosted.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.

106
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Ways to run an applet
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
Simple example of Applet
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.d rawString("welcome",150,150);
}
}
Myaplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Java AWT:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java.
Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.

107
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

108
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.

109
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class


Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager
defines the layout manager for the component.
m)
changes the visibility of the component, by default
public void setVisible(boolean status)
false.
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
By extending Frame class (inheritance)
By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.

110
Event Handling
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism has the code which is known as event handler that is
executed when an event occurs.
Components of Event Handling
Event handling has three main components,
Events: An event is a change in state of an object.
Events Source: Event source is an object that generates an event.
Listeners: A listener is an object that listens to the event. A listener gets notified when an
event occurs.
Event Handling provides four types of classes; they are:
1. Event Adapters
2. Event classes
3. Event Sources
4. Event Listeners
1.EventAdapters
In a program, when a listener has many abstract methods to override, it becomes complex
for the programmer to override all of them. For example, for closing a frame, we must override
seven abstract methods of WindowListener, but we need only one method of them.
For reducing complexity, Java provides a class known as "adapters" or adapter class. Adapters
are abstract classes, that are already being overriden.
2. Eventclasses
Every event source generates an event and is named by a Java class. An event is generated when
something changes within a graphical user interface.
For example the event generated by a:
Button is known as an ActionEvent
Checkbox is known as an ItemEvent
All the events are listed in the java.awt.event package.

111
3. EventSources
Event Sources are responsible for generating events and are called components.
The source for an event can be a button, TextField or a Frame etcetera.

4. EventListeners
Events are handled by a special group of interfaces known as "listeners".
Events are supported by a number of Java packages, like java.util, java.awt and java.awt.event.

Important Event Classes and Interface


Event Classes Description Listener Interface
generated when button is pressed, menu-item
ActionEvent ActionListener
is selected, list-item is double clicked
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released and also MouseListener
when it enters or exit a component
generated when input is received from
KeyEvent KeyListener
keyboard
generated when check-box or list item is
ItemEvent ItemListener
clicked
generated when value of textarea or textfield is
TextEvent TextListener
changed
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
generated when window is activated,
WindowEvent deactivated, deiconified, iconified, opened or WindowListener
closed
generated when component is hidden, moved,
ComponentEvent ComponentEventListener
resized or set visible
generated when component is added or
ContainerEvent ContainerListener
removed from container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
generated when component gains or loses
FocusEvent FocusListener
keyboard focus

Steps to handle events:


1. Implement appropriate interface in the class.
2. Register the component with the listener.

Java event handling by implementing ActionListener


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{

112
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent
e){tf.setText("Welcome");
}
public static void main(String
args[]){new AEvent();
}
}
Output:

Java ItemListener Example


import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2; 113
Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50); checkBox2
= new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
} }
Output:

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.

Methods of MouseListener interface


114
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example - 1


import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements
MouseListener{Label l;
MouseListenerExample(){ addM
ouseListener(this); l=new
Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{l.setText("Mouse Released");
}
public static void main(String[] args)
{new MouseListenerExample();
}
}
Output:

115
Example - 2
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements
MouseListener{MouseListenerExample2(){
addMouseListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public static void main(String[] args)


{new MouseListenerExample2();
}
}

Output:

116
java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is
notified against MouseEvent. The MouseMotionListener interface is found in java.awt.event
package. It has two methods.

public abstract void mouseDragged(MouseEvent e);


public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener Example


import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener{MouseMotionListenerExample(){
addMouseMotionListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}

public static void main(String[] args)


{ new MouseMotionListenerExample();
}
}
117
Output:

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package. It has three
methods.

public abstract void keyPressed(KeyEvent e);


public abstract void keyReleased(KeyEvent e);
public abstract void keyTyped(KeyEvent e);

Java KeyListener Example


import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener{Label l;
TextArea area;
KeyListenerExample(){

l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);

add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e)
{l.setText("Key Pressed");
118
}
public void keyReleased(KeyEvent e)
{l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{l.setText("Key Typed");
}

public static void main(String[] args)


{new KeyListenerExample();
}
}
Output:

Java WindowListener Interface


The Java WindowListener is notified whenever you change the state of window. It is
notified against WindowEvent. The WindowListener interface is found in java.awt.event
package. It has the following methods.

public abstract void windowActivated(WindowEvent e);


public abstract void windowClosed(WindowEvent e);
public abstract void windowClosing(WindowEvent e);
public abstract void windowDeactivated(WindowEvent e);
public abstract void windowDeiconified(WindowEvent e);
public abstract void windowIconified(WindowEvent e);
public abstract void windowOpened(WindowEvent e);

Java WindowListener Example


import java.awt.*;
import java.awt.event.WindowEvent;
119
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements
WindowListener{WindowExample(){
addWindowListener(this);

setSize(400,400);
setLayout(null);
setVisible(true);
}

public static void main(String[] args)


{new WindowExample();
}
public void windowActivated(WindowEvent arg0)
{System.out.println("activated");
}
public void windowClosed(WindowEvent arg0)
{System.out.println("closed");
}
public void windowClosing(WindowEvent arg0)
{System.out.println("closing");
dispose();
}
public void windowDeactivated(WindowEvent arg0)
{System.out.println("deactivated");
}
public void windowDeiconified(WindowEvent arg0) {System.out.println("deiconified");
}
public void windowIconified(WindowEvent arg0)
{System.out.println("iconified");
}
public void windowOpened(WindowEvent arg0)
{System.out.println("opened");
}
}

JAVA ADAPTER CLASSES


Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.

120
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes


Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes


Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener

Java MouseAdapter Example


import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends
MouseAdapter{Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public void mouseClicked(MouseEvent e)
{Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args)
{new MouseAdapterExample();

121
}}

List of Experiments:

1. Write a temperature conversion applet that converts from Fahrenheit to Celsius. The
Fahrenheit temperature should be entered from the keyboard (via a JTextField). A JLabel
should be used to display the converted temperature. Use the following formula for the
conversion: Celcius = ((5/9)*(Ferenheit‐32)). Enhance the temperature conversion applet
of Q1 by adding the Kelvin temperature scale. The applet should also allow the user to
make conversions between any two scales. Use the following formula for the conversion
between Kelvin and Celsius (in addition to the formulain Q1): Kelvin = Celcius + 273.15
2. Calculator using AWT controls
3. Authentication check using AWT controls
4. Design a calculator using event-driven programming paradigm of Java with the
following options.
a) Decimal manipulations
b) Scientific manipulations

Program:

122
123
124
125
Viva Questions

1. Explain about Event Handlers in Java.


2. Define Swings in Java.
3. Explain the Mouse Events in Java.
4. Explain the Keyboard Events in Java.
5. Define Frame in Java.

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

126
Ex .No 11 Program using Network Socket

AIM:

To design a java program with network socket TCP and UDP

Theory:
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:

1. IP Address of Server, and


2. Port number.

Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through
this class, we can read and write message. The ServerSocket class is used at server-side. The accept()
method of ServerSocket class blocks the console until the client is connected. After the successful
connection of client, it returns the instance of Socket at server-side.

127
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be
used to create a socket.

Important methods
Method Description

1) public InputStream getInputStream() returns the InputStream attached with this


socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this


socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection between server
and client.

2) public synchronized void closes the server socket.


close()

Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are
using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with the
given port number, it returns an instance of Socket.

128
Example:

ServerSocket ss=new ServerSocket(6666);


Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.

Example:

Socket s=new Socket("localhost",6666);

Sample Code:

MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

129
MyClient.Java

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
List of Experiments:

1. Write a Java program to implement TCP Network Socket


2. Write a Java program to implement UDP Data gram Network Socket
3. Write a Java program to implement SMTP Network Socket
4. Write a Java program to implement POP3 Network Socket

Program:

130
131
132
Additional Experiments

133
134
135
136
Viva Questions
1. Define Network Socket.
2. What is URL Class?
3. Difference between TCP and UDP Socket.
4. What is use of SMTP Socket?
5. Define POP3.
6. List out URL Class Method.

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

137
Ex .No 12 Program using Database Connectivity(JDBC)

AIM:

To design a java program with database Connectivity (JDBC)


Theory:

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers
to connect with the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC
API, we can save, update, delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on
the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC
API. A list of popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
138
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

Why Should We Use JDBC:

Before JDBC, ODBC API was the database API to connect and execute the query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in
Java language).

We can use JDBC API to handle database using Java program and can perform the following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Java Database Connectivity with 5 Steps:


There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

139
1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method:

public static void forName(String className)throws ClassNotFoundException


Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method:

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String password)
throws SQLException

140
3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Statement stmt=con.createStatement();

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException


Example
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method:

public void close()throws SQLException


con.close();

Java Database Connectivity with MySQL

141
To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySql as the database. So we need to know following informations
for the mysql database:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306 is
the port number and sonoo is the database name. We may use any database, in such case,
we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database.
In this example, we are going to use root as the password.

Sample Database Creation:

create database sonoo;


use sonoo;
create table emp(id int(10),name varchar(40),age int(3));
Sample Code:
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","root","ro
ot"); //here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
142
}

List of Experiments:
Write a java program to implement Course Registeration system with Data base Connectivity.
Write a java program to implement Examination System with Database Connectivity.
Write a program to establish the connection between Java program to database.
Write a program to create a database table by using Java program.
Develop an application to perform insert, update, retrieve and delete the record from the
database in JDBC.

Program:

143
Additional Experiments

144
Additional Experiments

145
146
Additional Experiments

147
148
149
Viva Questions
1. Define JDBC.
2. List out the Database driver ?
3. Define Prepared Statement?
4. Define Callable`Statement?
5. How to load Database driver in a Program.

Sl.No Module Max. Marks Marks Obtained


1 Efficiency of Algorithm 10
2 Efficiency of program 10
3 Output 10
4 Technical Skill 10
5 Communication Skill 10
Total 50

Faculty Signature

Result:

150
Additional Experiments

151
152
153
154
Additional Experiments

155
References

1. https://www.tutorialspoint.com/java/
2. http://www.java2novice.com/java-fundamentals/
3. https://newcircle.com/bookshelf/java_fundamentals_tutorial/index
4. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/
5. https://www.quora.com/Why-is-threading-suitable-for-I-O-bound-operation
6. http://www.drdobbs.com/parallel/multithreaded-file-io/220300055
7. https://www.quora.com/Why-is-threading-suitable-for-I-O-bound-operation
8. https://www.mailinator.com/tymaPaulMultithreaded.pdf
9. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.85.7032&rep=rep1&type=pd
f
10. http://www.javatpoint.com/Graphics-in-applet
11. http://www.landofcode.com/java-tutorials/java-graphics.php
12. http://cs.lmu.edu/~ray/notes/javagraphics/
13. https://www.tutorialspoint.com/javaexamples/gui_text.htm
14. http://www.javatpoint.com/event-handling-in-java
15. https://www.tutorialspoint.com/awt/awt_event_handling.html
16. http://way2java.com/awt-events/java-event-handling/
17. http://java-demos.blogspot.in/2013/11/event-handling-in-java.html

134

You might also like