0% found this document useful (0 votes)
27 views207 pages

PT FullNote

This document is a comprehensive guide for Bachelor in Computer Engineering students, covering various programming architectures and paradigms including Procedural, Object-Oriented, Event-Oriented, Aspect-Oriented, and Subject-Oriented Programming. It also discusses the Integrated Development Environment (IDE) and Visual Programming, detailing their benefits and components. Additionally, the document includes assignments to reinforce learning and understanding of the topics presented.

Uploaded by

Prekshya Baral
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)
27 views207 pages

PT FullNote

This document is a comprehensive guide for Bachelor in Computer Engineering students, covering various programming architectures and paradigms including Procedural, Object-Oriented, Event-Oriented, Aspect-Oriented, and Subject-Oriented Programming. It also discusses the Integrated Development Environment (IDE) and Visual Programming, detailing their benefits and components. Additionally, the document includes assignments to reinforce learning and understanding of the topics presented.

Uploaded by

Prekshya Baral
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/ 207

Programming

Technology

FOR THE STUDENTS OF BACHELOR IN COMPUTER ENGINEERING

Compiled by: Er. Shiva Ram Dam


TABLE OF CONTENTS

UNIT TOPICS PAGE NO.

INTRODUCTION 1
1

PROGRAMMING ARCHITECTURE 13
2

ELEMENTS OF .NET LANGUAGES 21


3

.NET FRAMEWORK 55
4

WEB & DATABASE PROGRAMMING WITH .NET 65


5

JAVA FRAMEWORK 83
6

JAVA EXCEPTION HANDLING 87


7

APPLETS AND APPLICATION 99


8

EVENT, EVENT HANDLING & SWING 111


9

JAVA SERVER PAGES (JSP)/ SERVER TECHNOLOGY 129


10

DATABASE HANDLING 163


11

12 PROJECT 1: BUILDING CALCULATOR USING SWING 179

13 SOME JAVA PROGRAMS WITH SWING

14 LAB WORKS
1. INTRODUCTION

Chapter 1: Introduction [Credit: 5 hrs]

1.1. Review on Programming Languages


There are mainly two types of programming languages: High Level and Low level programming
languages.

Programmin
g Language

Low-level High-level

Object
Machine Assembly Procedural
oriented

Assignment 1: Classify programming languages and explain in brief.

1.2. Programming Paradigms.


A programming paradigm is a style, or “way,” of programming. It is a method to solve a problem using
tools and techniques that are available to us following some approach. There are lots for programming
language that are known but all of them need to follow some strategy when they are implemented and
this methodology/strategy is paradigm. Apart from varieties of programming language there are lots of
paradigms to fulfill each and every demand.
Some of the programming paradigms are:
i. Procedure oriented programming iv. Aspect oriented programming
ii. Object oriented programming v. Subject oriented programming
iii. Event oriented programming

i) Procedure Oriented Programming


• A computer program is a set of instructions for a computer to perform a specific task. The
traditional programming languages like C, FORTRAN, Pascal, and Basic are Procedural
Programming Languages.
• A procedural program is written as a list of instructions, telling the computer, step-by-step,
what to do: Get two numbers, add them and display the sum.
• The problem is divided into a number of functions. The primary focus of programmer is on
creating functions.
• While developing functions, very little attention is given to data that are being used by various
functions.
• Procedural programming is fine for small projects. It does not model real world problems well.
This is because functions are action oriented and does not really correspond to the elements
of the problems.

Figure: Typical structure of Procedural Oriented Program


Programming Technology © Er. Shiva Ram Dam, 2019 1
1.INTRODUCTION

Features of Procedural/Structured Programming Language:


• Emphasis is on algorithm (step by step description of problem solving) to solve a problem. Each step of
algorithm is converted into corresponding instruction or code in programming language.
• Large program is divided into a number of functions, with each function having a clearly defined
purpose and a clearly defined interface to other functions in the program. The integration of these
functions constitutes a whole program.
• Uses top-down approach in program design. In top-down programming, we conceive the
program as a whole as a process to be decomposed.
• Most of the functions share Global data and these are more vulnerable to accidental changes.
• Data move openly around the system from function to function. Information is passed between
functions using parameters or arguments

Assignment 2 : Enumerate the advantages and disadvantages of POP paradigm.

ii) Object Oriented Programming


• In Object-Oriented Programming, a program is decomposed into a number of entities called
objects.
• Data and the functions that operate on that data are combined into that object. OOP mainly
focus on data rather than procedure.
• It considers data as critical element in the program development and does not allow it to flow
freely around the system.
• It ties data more closely to the functions that operate on it and protects it from accidental
modification from outside functions.

Features of Object Oriented Programming Language


• Emphasis is on the data rather than procedure. It focuses on security of data from
unauthorized modification in the program.
• A program is divided into a number of objects. Each object has its own data and functions.
These functions are called member functions and data are known as member data.
• Data is hidden and cannot be accessed by external functions.
• Follows bottom-up approach in program design. The methodology for constructing an object-
oriented program is to discover the related objects first. Then, appropriate class is formed for
similar objects. These different classes and their objects constitute a program.
• Object may communicate with each other through functions.
• New data and functions can be easily added whenever necessary.

2 Programming Technology © Er. Shiva Ram Dam, 2019


1. INTRODUCTION

• Supports reusability of code. Once a class has been written, created and debugged, it can be
used in a number of programs without modification i.e. a same code can be reused. It is
similar to the way a library functions in a procedural language.
• Supports polymorphism.

Basic Characteristics of Object-oriented Languages


• Class and Objects • Inheritance
• Data abstraction • Reusability
• Encapsulation • Polymorphism and overloading

Assignment 3: Explain the characteristics of Object-oriented languages.

Applications of using OOP:


Main application areas of OOP are:
• User Interface design such as windows, menus.
• Real time systems
• Simulation and modeling
• Object oriented databases
• AI and Expert Systems
• Neural Networks and Parallel processing
• Decision Support and Office Automation System, etc.

Benefits of OOP:
The main advantages are:
• It is easy to model a real system as programming objects in OOP represents real objects. The
objects are processes by their member data and functions. It is easy to analyze the user
requirements.
• With the help of inheritance, we can reuse the existing class to derive a new class such that
redundant code is eliminated and the use of existing class is extended. This saves time and
cost of program,
• In OOP, data can be made private to a class such that only member functions of the class can
access the data. This principle of data hiding helps the programmer to build a secure program
that cannot be invaded by code in other part of the program.
• With the help of polymorphism, the same function or same operator can be used for different
purposes. This helps to manage software complexity easily.
• Large problems can be reduced to smaller and more manageable problems. It is easy to
partition the work in a project based on objects.
• It is possible to have multiple instances of an object to co-exist without any interference i.e.
each object has its own separate member data and function.

Assignment 4:
1. Mention the advantages and disadvantages of OOP paradigm.
2. Differentiate between POP and OOP

Programming Technology © Er. Shiva Ram Dam, 2019 3


1.INTRODUCTION

iii) Event Oriented Programming


An Event is a signal that informs an application that something important has occurred. For example,
when a user clicks control on a form, the form can raise a click event and call a procedure that handle
the event. There are various types of event associated with a form like: Click, Double Click, Close,
Load, Resize, etc.
Event oriented Programming means that the program executes everything as a response to an event,
instead of a top down program where the ordering of the code determines the order of execution.
Program code is based on what happens when the user does something. Events can be mouse
moves, mouse clicks or double-clicks, keystrokes, changes made in textboxes, timing based on a
timer, etc. Note that this is not an exhaustive list of events, just a small sampling. It is quite a bit
different from top-down coding. An event-oriented language implies that an application (the computer
program) waits for an event to occur before taking any action.

Assignment 5:
Mention the features, advantages and disadvantages of EOP

iv) Aspect Oriented Programming


Lets us consider an abstract class Dog. We can inherit its behavior using inheritance concept. Let us
create a derived class Poodle, this inherits Dog. Again let us define another unique behavior
(method) and label as an ObedientDog. Surely, not all Dogs are obedient. So Dog class cannot
contain the Obedience behavior. So, this obedience is an aspect. An aspect is a common feature
that's typically scattered across methods, classes, object hierarchies, or even entire object models.
Aspect-Oriented Programming (AOP) is a new programming concept that was developed due to some
shortcomings of object-oriented programming (OOP). The key unit of modularity in OOP is the class,
whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns
such as transaction management that cut across multiple types and objects. (Such concerns are often
termed crosscutting concerns in AOP literature.)
Although the OOP provides a rich set of tools for abstraction and modularization, it cannot address
the problem with so called cross-cutting concerns. One can think the cross-cutting concerns as
functionality that when implemented, will scatter around the final product in different components.
Since this kind of functionality will cut through the basic functionality of the system, it is hard to model
even with the OOP. Good examples of the cross-cutting concerns are authorization, synchronization,
error handling and transaction management.

AOP tries to address the problem by modularizing the crosscutting functionality into more manageable
modules – aspects. Unlike the OOP, AOP does not replace previous programming paradigms. AOPers
generally say that OOP solves 90% of problems and AOP solves the 10% of problems that OOP isn't
good at. Therefore it can be seen as a complementary to the object-oriented paradigm rather than a
replacement. In aspect-oriented programming the system is divided into a two halves: the base
program and the aspect program. The base program will contain the main functionality of the system
and can be implemented using object-oriented programming. The aspect program will consist of the
cross-cutting functionality that has been modularized away from the base program. This leads to a
4 Programming Technology © Er. Shiva Ram Dam, 2019
1. INTRODUCTION

more concise structure since the functionality of the cross-cutting concerns is contained within well-
defined modules.
There are several frameworks to implement aspect-oriented programming in Java world: Spring and
AspectJ

For further learning:


https://www.youtube.com/watch?v=QdyLsX0nG30&list=PLE37064DE302862F8
https://www.youtube.com/watch?v=aNcTL9e7luM
https://docs.jboss.org/aop/1.0/aspect-framework/userguide/en/html/index.html
https://www.cs.helsinki.fi/u/paakki/laukkanen.pdf
https://flowframework.readthedocs.io/en/stable/TheDefinitiveGuide/PartIII/AspectOrientedProgramming.html

v) Subject Oriented Programming


In computing, SOP is an object-oriented software paradigm in which the state (i.e. fields) and
behavior (i.e. methods) of objects are not seen as intrinsic to the objects themselves, but are provided
by various subjective perceptions (“subjects”) of the objects.

Figure: Many Subjective Views of an Object-Oriented Tree

Programming Technology © Er. Shiva Ram Dam, 2019 5


1.INTRODUCTION

In the real-world, properties of a tree like its height, cell-count, density, leaf-mass, etc. are intrinsic
properties. From the point of view of a bird, a tree may also have measures of relative value for food
or nesting purposes. From the point of view of a tax-assessor, it may have a certain taxable value in a
given year. From the point of view of a woodsman, it might be different.
Subject-oriented programming is an enhancement of object-oriented programming that allows
decentralized class definition. An application developer who needs new operations associated with
classes can implement them him/herself, not by editing existing code for the classes, but as a
separate collection of class definitions called a subject.
SOP allows OO systems to be built by flexible composition of components, which we call “subjects.”
A subject is a collection of classes, defining a particular view of a domain and/or providing a coherent
set of functionality. Without eliminating the advantages of encapsulation, this approach eliminates the
need for class ownership. An application developer can write all the code needed for the application,
irrespective of which classes are involved, without leaving development requirements on others.
The overall goal of subject-oriented programming is to facilitate the development and evolution of
suites of cooperating applications.

1.3. Integrated development environment, components of visual programming


An integrated development environment (IDE) or interactive development environment is a software
application that provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of a source code editor; build automation tools and a
debugger. Several modern IDEs integrate with Intellisense coding features.
Some examples of IDEs are: Microsoft Visual Studio, Eclipse, NetBeans, Delphi, JBuilder, Borland
C++ Builders, FrontPage, Dreamweaver etc.
Benefits of using IDEs
• Faster setup
• Faster development tasks:
• Continual learning:
• Standardization:

For more understanding:


https://www.veracode.com/security/integrated-development-environment
https://searchsoftwarequality.techtarget.com/definition/integrated-development-environment

Visual Programming:
A visual programming language (VPL) is any programming language that lets users
create programs by manipulating program elements graphically rather than by specifying them
textually.
Visual programming lets humans describe processes using illustration. Whereas a typical text-based
programming language makes the programmer think like a computer, a visual programming language
lets the programmer describe the process in terms that make sense to humans.
Examples of visual programming languages include: Alice, GameMaker, Kodu, Lego, Scratch, etc.
A programming language that a visual representation (such as graphics, drawings, animation, buttons
or icons etc.) is known as visual programming.
The term visual programming refers to creating or developing windows based applications or
graphical user interface GUI applications. Different graphical objects are used to create the graphical
user interface. These objects include windows, buttons, list boxes, and menus etc. these objects are
provided by the visual programming languages as built in components.

6 Programming Technology © Er. Shiva Ram Dam, 2019


1. INTRODUCTION

Advantages of VP

Following are the most important advantages of visual programming languages:


• These languages are easy to learn and use.
• These languages provide many built-in objects that can be used in developing the new
programs. New objects can also be created.
• The user-interface can be designed very easily by using mouse. The components are placed
on the main interface component like forms. These components can be resized and moved
easily.
• These languages provide facility to attach code to each interface component. The attached
code is executed when the user interacts with the interface component.
• The users can use the visual applications very easily.

Disadvantages of VP
Following are some disadvantages of visual programming languages:
• These languages require computer with more memory, high storage capacity of hard disk,
and faster processor.
• These languages can only be implemented on graphical operating systems like Linux and
windows.

Components of Graphical Visual Interface


Following are the popular components of Visual programming. There are much more than these.
1. Window: A window sometimes also called a form is the most important of all the visual
interface components. A window plays the role of the canvas in a painting. Without the canvas
there is no painting. Similarly, without the window there is no user interface. The components
that make up the user interface have to be placed in the window and cannot exist independent
of the window. Simply, Forms are the windows which hold the various controls (buttons, text
boxes, etc.) which make up our application.
2. Buttons: A button is used to initiate an action. The text on the button is indictive of the action
that it will initiate. Clicking on a button initiate the action associated with the button.
3. Text boxes: Text box is a control that allows entering text on a form at runtime. Text boxes are
used to accept information from the user. The user interface will display one text for each
piece of information
4. List Boxes or Pop-up Lists: List boxes are used to present the user with the possible options.
The user can select one or more of the listed options.
5. Label: The label is used to place text in a window. Typically label is used to identify controls
that do not have caption properties of their own.
6. Radio button or Option Button: The radio buttons, also referred as option buttons, are used
when the user can select only one of multiple options.
7. Check boxes: A Check box allows the user to select one or more items by checking the check
box/check boxes concerned. The CheckBox control allows the user to set true/false or yes/no
type options.

Programming Technology © Er. Shiva Ram Dam, 2019 7


1.INTRODUCTION

1.4. Application object, main window object, view object, document object
In the early days of Microsoft Foundation Class (MFC), applications were built very mush like the
sample programs. An application had two principal components: application object and window object.
MFC gradually enhanced to MFC 2.0 using document/view architecture and then to MFC 4.0.

An Application object represents the application itself. Its primary job is to create the windows object,
and the window object, in turn, processes messages.
The frame window object is the application's top-level window and usually includes a resizing border,
a caption bar, a system menu, and Minimize, Maximize, and Close buttons. The arrows in the
illustration show the direction of data flow during various application operations.
The view object is a child window sized to fit the frame window and serves as the client area for the
parent. One or more View objects represent views of that data.
The application's data is stored in the document object, which is displayed in the view.

1.5. Document-view architecture and its advantages


The Document/View architecture is the foundation used to create applications based on the Microsoft
Foundation Classes library. It allows us to make logical separation between different parts that
compose a computer program (views and documents). View is what the user sees as part of your
application and the document is where a user would work on.
MFC Document View Architecture is a framework to manage user module data and view of the
module separately. The design it follows is known as model-view architecture. Data part is managed
by model and in MFC, this is known as Document, and display part is managed by view class.

Figure: Document-view Architecture

8 Programming Technology © Er. Shiva Ram Dam, 2019


1. INTRODUCTION

The parts that compose the Document/View architecture are a frame, one or more documents, and
the view. Putting together, these entities make up a usable application.

Document (similar to a bucket that holds user’s data)


Document is the class to manage data part of the objects. Application often derives a class from
CDocument. This deals with saving and retrieving data fields to and from the file stream. MFC often
uses CArchive and serialization process to do the same. Users however have other options like direct
CFile calls to synch the data to file system or query SQL server to do the same. Document module
also deals with the logic to maintain the data and also responsible for managing different attributes of
the data.

View
A view is the platform where the user works to do her job done. View is the class module to display
data of the document. A derived class of CView is often used for this purpose. This display part can be
the display of the document in graphical form or with UI elements or in the form of printable view which
contains formatted text.

Frame
A Frame is a combination of the building blocks, the structure and the borders of an item. A Frame
gives physical presence to a window. MFC framework uses a Frame window or class CFrame to
display window in the screen and thus a CFrame class is always needed in any application which
follows document view architecture.

Key classes of Document/View Architecture.


CDocument It loads, stores, and manages the program's data. It also contains the functions
that are used to access and work with the data.
CView provides the basic framework for output to the view window and the printer, and
communicates with the associated document.
Also acts as intermediary between document and the user.
the view renders an image of the document on the screen and interprets user
input as operations upon the document.
CFrameView Supports objects that provides the frame around one or more views of a
document.
CDocTemplate is the class that binds together the frame, view, document, and a set of
application resources.
uses two document template classes: CSingleDocTemplate for SDI applications
and CMultiDocTemplate for MDI applications.
An SDI application uses the main frame window to display its document. Only
one document can be open at a time.
An MDI application uses the main frame window as a workspace in which the
user can open multiple document frame windows.

Reference: http://findbestvideos.blogspot.com/2009/11/documentview-fumdamentals.html
https://docs.microsoft.com/en-us/cpp/mfc/document-view-architecture?view=vs-2019

Programming Technology © Er. Shiva Ram Dam, 2019 9


1.INTRODUCTION

Advantages of Document/view Architecture:


This design may look complex for a small dialog based application. However this actually helps when
dealing with a large application where there are multiple data objects and different view of the objects.
This design decouples data from view.
Following are the advantages:
• Data managing part may go separate changes where display part can remain unchanged.
Again there can be display part to change where data manage part can remain same. For
both the cases this design fits well.
• When a user updates one of the views, that view object calls CDocument::UpdateAllViews.
That function notifies all of the document's views, and each view updates itself using the latest
data from the document. The single call to UpdateAllViews synchronizes the different views.
This scenario would be difficult to code without the separation of data from view, particularly if
the views stored the data themselves.

Limitations of Doc/View Architecture ( Alternatives to the Doc/View Architecture)


MFC applications normally use the document/view architecture to manage information, file formats,
and the visual representation of data to users. For the majority of desktop applications, the
document/view architecture is an appropriate and efficient application architecture. This architecture
separates data from viewing and, in most cases, simplifies your application and reduces redundant
code.
However, the document/view architecture is not appropriate for some situations. Consider these
examples:
• If you are porting an application written in C for Windows, you might want to complete your port
before adding document/view support to your application.
• If you are writing a lightweight utility, you might find that you can do without the document/view
architecture.
• If your original code already mixes data management with data viewing, moving the code to the
document/view model is not worth the effort because you must separate the two.

While the document/view model is a good default and useful in many applications, some applications
need to bypass it. The point of the document/view architecture is to separate data from viewing. In
most cases, this simplifies your application and reduces redundant code. As an example of when this
is not the case, consider porting an application written in C for Windows. If your original code already
mixes data management with data viewing, moving the code to the document/view model is harder
because you must separate the two. You might prefer to leave the code as it is.
There are many approaches to bypassing the document/view architecture, of which the following are
only a few:
• Treat the document as an unused appendage and implement your data management code in
the view class. Overhead for the document is relatively low, as described below.
• Treat both document and view as unused appendages. Put your data management and
drawing code in the frame window rather than the view. This is close to the C language
programming model.
• Override the parts of the MFC framework that create the document and view to eliminate
creating them at all.

10 Programming Technology © Er. Shiva Ram Dam, 2019


1. INTRODUCTION

1.6. Virtual machines and runtime environments


Virtual machines:
A virtual machine (VM) is a software program or operating system that not only exhibits the behavior
of a separate computer, but is also capable of performing tasks such as running applications and
programs like a separate computer. A virtual machine, usually known as a guest is created within
another computing environment referred as a "host." Multiple virtual machines can exist within a single
host at one time.
A virtual machine is also known as a guest.
Depending on their use and level of correspondence to any physical computer, virtual machines can
be divided into two categories:
1. System Virtual Machines: A system platform that supports the sharing of the host computer's
physical resources between multiple virtual machines, each running with its own copy of the
operating system. The virtualization technique is provided by a software layer known as a
hypervisor, which can run either on bare hardware or on top of an operating system. Eg:
VirtualBox
2. Process Virtual Machine: Designed to provide a platform-independent programming
environment that masks the information of the underlying hardware or operating system and
allows program execution to take place in the same way on any given platform.

Some of the advantages of a virtual machine include:


• Allows multiple operating system environments on a single physical computer without any
intervention
• Virtual machines are widely available and are easy to manage and maintain.
• Offers application provisioning and disaster recovery options

Some of the drawbacks of virtual machines include:


• They are not as efficient as a physical computer because the hardware resources are
distributed in an indirect way.
• Multiple VMs running on a single physical machine can deliver unstable performance
Reference: https://www.desktop-virtualization.com/glossary/virtual-machine/

Runtime environments
A runtime environment is the execution environment provided to an application or software by the
operating system. In a runtime environment, the application can send instructions or commands to the
processor and access other system resources such as RAM, which otherwise is not possible as most
programming languages used are high level languages.
The runtime environment provides a state for the target machine to have access to resources such as
software libraries, system variables and environment variables, and provide all necessary services
and support to the processes involved in the execution of the application or program. In certain
software or applications such as Adobe Flash Player or Microsoft PowerPoint Viewer the runtime
environment is available to end users as well.
Software developers need a runtime environment to test their software's functioning. As a result, all
software development applications include a runtime environment component which allows the testing
of the application during execution. Tracking bugs or debugging for any errors are done in most
applications with the help of runtime environments. Runtime execution continues even if the
application or program crashes. Most runtime environments are capable of reporting of why an
application or program crashed. One of the more popular runtime environments is Java, which helps
Java applets and applications to be executed in any machine which has a Java runtime environment
installed.

Programming Technology © Er. Shiva Ram Dam, 2019 11


1.INTRODUCTION

Exam Questions:
1. What is Document-View architecture? Explain event-oriented programming, subject-oriented and
aspect-oriented programming. [2018 Spring]
2. Define AOP. What are the differences between POP and OOP? [2018 Fall]
3. What is IDE? What are the components of Visual programming? [2017 Fall]
4. What is an IDE and how does it work? Discuss the key features in Visual Studio .NET [2017
spring]
5. Describe the features of four different language paradigms and give one example language for
each category. [2017 spring]
6. Describe the features of Procedure, Event and Object Programming? [2016 Fall]
7. Define EOP and AOP. Explain virtual machine and run time environments. [2016 Spring]
8. Describe the features of AOP and SOP. [2015 spring]
9. Explain Document/view architecture? What are the four key classes used in this architecture.
[2015 spring]
10. What do you mean by IDE? What are the differences between EOP and OOP? [2015 Fall]
11. Differentiate between OOP and EOP. [2014 spring]
12. What are the advantages of DVA? Explain in brief about the components of Visual programming.
[2014 Spring]
13. Explain about the significance of AOP and SOP with example. [2014 fall]
14. Explain DV architecture with its advantages. [2013 spring]
15. Write short notes:
a) Virtual machine Vs Runtime Machine [2018 Fall]
b) Document view Architecture and its advantages [2017 Fall]
c) Doc-View Architecture [2016 Fall, Spring]
d) Window object. [2015 fall]
e) Components of Visual programming [2014 fall]
f) Event oriented language [2013 spring]

***End of Chapter***

12 Programming Technology © Er. Shiva Ram Dam, 2019


2. PROGRAMMING ARCHITECTURE

2. Programming Architecture [Credit: 3 hrs]


Programming Architecture is both the process and the product of planning, designing and constructing
programs or software. It’s a design pattern that is followed in software development. Software
architecture refers to the fundamental structures of a software system and the discipline of creating
such structures and systems. Each structure comprises software elements, relations among them,
and properties of both elements and relations.
In software engineering, a design pattern is a general reusable solution to a commonly occurring
problem within a given context in software design. A design pattern is not a finished design that can
be transformed directly into source or machine code. It is a description or template for how to solve a
problem that can be used in many different situations. Object-oriented design patterns typically show
relationships and Interactions between classes or objects, without specifying the final application
classes or objects that are involved. One of these design patterns is Model-View-Controller (MVC).
The programming language Smalltalk first defined the MVC concept it in the 1970’s. Since that time,
the MVC design idiom has become commonplace, especially in object oriented systems.

2.1. MVC
MVC is a software architecture pattern which allows us to split a software application into three
interconnected parts. These parts are Model, View, and Controller, in short, they are often known as
MVC. Most of the languages like Java, PHP, Python, C# etc use this pattern to develop the
applications. In Java, it is known as Spring - MVC Framework, in PHP it is known as cake PHP and so
on. By using the same concept, Microsoft introduced a framework called ASP.Net MVC.

Figure: MVC architecture


Model:
Model is a data and business logic. Model represents shape of the data and business logic. It
maintains the data of the application. Model objects retrieve and store model state in a database.
When a View is designed generally we attach a Model to it. The view requests the data from Model
and the Model responds to this request.

View:
View is a user interface. View display data using model to the user and also enables them to modify
the data.

Controller:
Controller is a request handler. Controller handles the user request. Typically, user interact with View,
which in-turn raises appropriate URL request, this request will be handled by a controller. The
controller renders the appropriate view with the model data as a response.

Programming Technology © Er. Shiva Ram Dam, 2019 13


2. PROGRAMMING ARCHITECTURE

Request/Response in MVC Architecture

As per the above figure, when the user enters a URL in the browser, it goes to the server and calls
appropriate controller. Then, the Controller uses the appropriate View and Model and creates the
response and sends it back to the user.

Advantages of MVC
1) Faster development process: MVC supports rapid and parallel development. With MVC, one
programmer can work on the view while other can work on the controller to create business logic
of the web application. The application developed using MVC can be three times faster than
application developed using other development patterns.
2) Ability to provide multiple views: In the MVC Model, you can create multiple views for a model.
Code duplication is very limited in MVC because it separates data and business logic from the
display.
3) Support for asynchronous technique: MVC also supports asynchronous technique, which helps
developers to develop an application that loads very fast.
4) Modification does not affect the entire model: Modification does not affect the entire model
because model part does not depend on the views part. Therefore, any changes in the Model will
not affect the entire architecture.
5) MVC model returns the data without formatting: MVC pattern returns data without applying any
formatting so the same components can be used and called for use with any interface.
6) SEO friendly Development platform: Using this platform, it is very easy to develop SEO-friendly
URLs to generate more visits from a specific application.

Disadvantages of MVC
1) Increased complexity
2) Inefficiency of data access in view
3) Difficulty of using MVC with modern user interface.
4) Need multiple programmers for parallel development
5) Knowledge on multiple technologies is required.
6) Developer must have knowledge of client side code and html code.

2.2. Client-server traditional model


Client-Server Architecture is a shared architecture system where loads of client-server are divided.
The client-server architecture is a centralized resource system where server holds all the resources.
The server receives numerous performances at its edge for sharing resources to its clients when
requested. Client and server may be on the same or in a network. The server is profoundly stable and
scalable to return answers to clients. This Architecture is Service Oriented which means client service
will not be interrupted. Client-Server Architecture subdues network traffic by responding to the
14 Programming Technology © Er. Shiva Ram Dam, 2019
2. PROGRAMMING ARCHITECTURE

inquiries of the clients rather than a complete file transfer. It restores the file server with the database
server.

A client–server architecture divides an application into two parts, ‘client’ and ‘server’. Such an
application is implemented on a computer network, which connects the client to the server. The server
part of that architecture provides the central functionality: i.e., any number of clients can connect to the
server and request that it performs a task. The server accepts these requests, performs the required
task and returns any results to the client, as appropriate.

Figure: Client–Server model

Types of Server:
There are two types of servers: Iterative and concurrent.
1. Iterative Server
This is the simplest form of server where a server process serves one client and after
completing first request then it takes request from another client. Meanwhile another client
keeps waiting.

2. Concurrent server
This type of server runs multiple concurrent processes to serve many requests at a time.
Because one process may take longer and another client cannot wait for so long.

2.3. N-tier architecture


2.3.1) 2-tier Client Server Architecture
The Two-tier architecture is divided into two parts:
1. Client Application (Client Tier)
2. Database (Data Tier)

Client system handles both Presentation and Application layers and Server system handles Database
layer. It is also known as client server application. The communication takes place between the Client
and the Server. Client directly interacts with the server. Client system sends the request to the Server
system and the Server system processes the request and sends back the data to the Client System.
The server does not call on another application in order to provide part of the service.

Programming Technology © Er. Shiva Ram Dam, 2019 15


2. PROGRAMMING ARCHITECTURE

Pros:
1. Easy to maintain and modification is bit easy.
2. Communication is faster.

Cons:
1. In 2-tier architecture, application performance will be degraded upon increasing the users.
2. Cost-ineffective

Advantages Disadvantage
Development • Simple structure Complex application rules difficult
to implement in database server –
Issues: •Easy to setup and maintain
requires more code for the client

Complex application rules difficult


to implement in client and have
poor performance

Changes to business logic not


automatically enforced by a
server

changes require new client side


software to be distributed and
installed
Performance: Adequate performance for low to Inadequate performance for
medium volume environments medium to high volume
environments, since database
server is required to perform
• Business logic and database are
business logic. This slows down
physically close, which provides database operations on database
higher performance server.

16 Programming Technology © Er. Shiva Ram Dam, 2019


2. PROGRAMMING ARCHITECTURE

2.3.1) 3-tier Architecture


The Three-tier architecture is divided into three parts:
1. Presentation layer (Client Tier)
2. Application layer (Business Tier)
3. Database layer (Data Tier)

Client system handles Presentation layer, Application server handles Application layer and Server
system handles Database layer.

In this architecture, one more software sits in between client and server. This middle software is called
middleware. Middleware are used to perform all the security checks and load balancing in case of
heavy load. A middleware takes all requests from the client and after doing required authentication it
passes that request to the server. Then server does required processing and sends response back to
the middleware and finally middleware passes this response back to the client.
Middle tier is also called as business logic tier or service tired. In the simple client-server solution the
client was handling the business logic and that makes the client “thick”. A thick client means that it
requires heavy traffic with the server, thus making it difficult to use over slower network connections
like Internet and Wireless (LTE, 3G, or Wi-Fi).
By introducing the middle layer, the client is only handling presentation logic. This means that only
little communication is needed between the client and the middle tier making the client “thin” or
“thinner”. An example of a thin client is an Internet browser that allows you to see and provide
information fast and almost with no delay.

Pros:
1. High performance. Lightweight persistent objects.
2. Scability: each tier cab scale horizontally.
3. Performance: because the presentation tier can cache requests, network utilization is
minimized, aand the load is reduced on the Application and Data tiers.
4. High degree of flexibility in deployment platform and configuration
5. Better re-use
6. Improve data integrity
7. Improved security: client cannot directly access to database.
8. Easy to maintain and modification is bit easy, won’t affect other modules
9. Application performance is good.

Cons:
1. Increases complexity/effort

Programming Technology © Er. Shiva Ram Dam, 2019 17


2. PROGRAMMING ARCHITECTURE

3-tier Pros and Cons:

N-tier Architecture:
Another layer is N-Tier application. N-Tier application AKA Distributed application. It is similar to three
tier architecture but number of application servers are increased and represented in individual tiers in
order to distribute the business logic so that the logic will be distributed.

Figure: N-tier architecture

As more users access the system, a three-tier solution might not be sufficient, we might need to scale
up. In N-tier architecture, we can add as many middle tiers (running on each own server) as needed to
ensure good performance (N-tier or multiple-tier). Security is also the best in the N-tier architecture
because the middle layer protects the database tier. There is one major drawback to the N-tier
architecture and that is the additional tiers increase the complexity and cost of the installation.
In software engineering, multi-tier architecture (often referred to as n-tier architecture) is client-server
architecture in which, the presentation, the application processing and the data management are
logically separate processes. For example, an application that uses middleware to service data
requests between a user and a database employs multi-tier architecture. The most widespread use of
"multi-tier architecture" refers to three-tier architecture.
An example of N-tier architecture is web-based application. A web-based application might consist of
the following tiers.
1. Tier 1: a client tier presentation implemented by a web browser.
2. Tier 2: a middle-tier distribution mechanism implemented by a web server.
3. Tier 3: a middle-tier service implemented by a set of server side scripts.
4. Tier 4: a data-tier storage mechanism implemented by a relational database.

Reference: https://www.softwaretestingmaterial.com/software-architecture/
http://www.softwaretestingclass.com/what-is-difference-between-two-tier-and-three-tier-
architecture/

18 Programming Technology © Er. Shiva Ram Dam, 2019


2. PROGRAMMING ARCHITECTURE

2.4. Comparison among 2-tier, 3-tier and N-tier architecture


1-tier 2-tier 3-tier
Benefits Very simple Good Security Exceptional security
Inexpensive More Scalable Faster execution
No Server needed Faster execution Thin client
Very scalable
Issues Poor security More costly Very costly
Multi user issues More complex Very complex
Thin client
Users Usually 1(or few) 2-100 50-2000(+)

2.5. Thin and Thick clients

Fat-Client/Fat-Server:
Client does most of the processing. User Interface and all data processing / Business logic are done
on client. The Data Service Layer is the actual Database Server, which handles the storage or
services the data.

Advantages of Thick clients:


• Lower server requirements
• Working offline
• Better multimedia performance
• More flexibility
• Using existing infrastructure
• Higher server capacity

Thin-Client/Fat-Server:
Client has less processing, usually UI & UI-Centric Business Objects. The Data-Centric Business
Objects, which handles the data access code, resides on the Data Service Layer or Database Server
Advantages:
• Cost saving and less work load
• Simplified management
• Enhanced security

References:
https://www.profolus.com/topics/thick-client-vs-thin-client-advantages-and-disadvantages/
https://www.webopedia.com/DidYouKnow/Hardware_Software/thin_client.asp

Programming Technology © Er. Shiva Ram Dam, 2019 19


2. PROGRAMMING ARCHITECTURE

Exam questions
1. What is tier in software? Explain about MVC and 3-tier. [2018 Spring]
2. Illustrate MVC with diagram? What are the differences between 2-tier and 3-tier architecture of
software development? [2018 Fall]
3. Differentiate between: [2017 fall]
a) Thin and Thick client
b) 2-tier, 3-tier and N-tier architecture.
4. What is the difference between 3-layer architecture and MVC architecture? [2017 spring]
5. What do you mean by Thick and Thin client? Explain N-tier architecture. [2016 fall]
6. What is MVC architecture? Explain pros and cons of 2-tier and 3-tier architecture. [2016
spring]
7. Write merits and demerits of MVC. What is the difference between 2-tier and 3-tier architecture?
[2015 spring]
8. Write merits and demerits of MVC. Why is MVC a three tier architecture? [2015 fall]
9. What is MVC architecture? How MVC processes the request and response? [2014 spring]
10. What is client-server model? Describe the relationship between Model, view and controller in MVC
architecture. [2014 fall]
11. What is MVC architecture? Explain pros and cons of 2-tie, 3-tier and N-tier architecture.
[2013 spring]

20 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

3. Elements of .NET languages [Credit: 4 hrs]

3.1. Introduction to C# language


C# is a simple & powerful object-oriented programming language developed by Microsoft. C# can be
used to create various types of applications, such as web, windows, console applications or other
types of applications using Visual studio.

Integrated Development Environment (IDE) for C#


Microsoft provides the following development tools for C# programming −
• Visual Studio 2010 (VS)
• Visual C# 2010 Express (VCE)
• Visual Web Developer

C# program Structure:
A C# program consists of the following parts:
• Namespace declaration
• A class
• Class methods
• Class attributes
• A Main() method
• Statements and Expressions
• Comments
Let us look at a simple code that prints the words "Hello World" –
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

When this code is compiled and executed, it produces the following result −

Hello World

Let us look at the various parts of the given program −


• The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has multiple using statements.
• The next line has the namespace declaration. A namespace is a collection of classes.
The HelloWorldApplication namespace contains the class HelloWorld.

Programming Technology © Er. Shiva Ram Dam, 2019 21


3. ELEMENTS OF .NET LANGUAGES

• The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods
define the behavior of the class. However, the HelloWorld class has only one method Main().
• The next line defines the Main method, which is the entry point for all C# programs.
The Main method states what the class does when executed.
• The next line /*...*/ is ignored by the compiler and it is put to addcomments in the program.
• The Main method specifies its behavior with the statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the Systemnamespace. This statement
causes the message "Hello, World!" to be displayed on the screen.
• The last line Console.ReadKey() makes the program wait for a key press and it prevents the
screen from running and closing quickly when the program is launched from Visual Studio
.NET.

Compiling and Executing the Program in Visual Studio


If you are using Visual Studio.Net for compiling and executing C# programs, take the following steps

• Start Visual Studio.
• On the menu bar, choose File -> New -> Project.
• Choose Visual C# from templates, and then choose Windows.
• Choose Console Application.
• Specify a name for your project and click OK button.
• This creates a new project in Solution Explorer.
• Write code in the Code Editor.
• Click the Run button or press F5 key to execute the project. A Command Prompt window
appears that contains the line Hello World.

Compiling and Executing the Program in cmd


You can compile a C# program by using the command-line instead of the Visual Studio IDE −
• Open a text editor and add the above-mentioned code.
• Save the file as helloworld.cs , File name should be the class name in the program.
• Open the command prompt tool and go to the directory where you saved the file.
• Type the path of the .NET framework as:
path =C:\Windows\Microsoft.NET\Framework\v4.0.30319
To check type csc
• Type csc helloworld.cs and press enter to compile your code.
• If there are no errors in your code, the command prompt takes you to the next line and
generates helloworld.exe executable file.
• Type helloworld to execute your program.
• You can see the output Hello World printed on the screen.

22 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

3.2. Introduction and Datatype, Identifiers, Variables and constants


C# Keywords
Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as
identifiers. However, if you want to use these keywords as identifiers, you may prefix the keyword
with the @ character.
In C#, some identifiers have special meaning in context of code, such as get and set are called
contextual keywords.
The following table lists the reserved keywords and contextual keywords in C# −
Reserved Keywords

abstract as base bool break byte case catch char

checked class const continue decimal default delegate do double

else enum event explicit extern false finally fixed float

in interface
for foreach goto if implicit in (generic int
modifier)

internal is lock long namespace new null object operator

out private protected public readonly ref


out (generic override params
modifier)

return sbyte sealed short sizeof stackalloc static string struct

switch this throw true try typeof uint ulong unchecked

unsafe ushort using virtual void volatile while

Contextual Keywords

add alias ascending descending dynamic from get global group

partial partial
into join let orderby remove select set
(type) (method)

Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The
basic rules for naming classes in C# are as follows −
• A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9)
or underscore. The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' /
and \. However, an underscore ( _ ) can be used.
• It should not be a C# keyword.

Variables:
Variables are specific names given to locations in the memory for storing and dealing with data.

Syntax for variable declaration:


<data_type> <variable_names>;

Example:
char s, ch;

Programming Technology © Er. Shiva Ram Dam, 2019 23


3. ELEMENTS OF .NET LANGUAGES

int a, b, c;
float pi, sal;
double percent;

Syntax for variable initialization:


<data_type> <variable_name> = value;
Example:
char ch = 'g';
int x = 6, roll = 42;
byte b = 22;
double pi = 3.14159;
float salary = 20000.00;

Constants:
Constants are fields whose values are set at compile time and can never be changed.
General syntax:
const <datatype> <identifier> = value;

Example:
public const double PI= 3.141;

Literals:
Literals are primitive pieces of data put into the program.
Eg: int a=20, b=30;
char ch=’A’;
string str=”Ramesh”

Here, 20, 30, ‘A’ and ”Ramesh” are literals.

C# datatype:
Datatype refers to what kind of data can be stored in the variable. In C#, variables are categorized into
the following types:
1. Value types
2. Reference types
3. Pointer types

1. Value types
A data type is a value type if it holds a data value within its own memory space. It means variables of
these data types directly contain their values. They are derived from the class System.ValueType.
Some examples are int, char, and float.
For example, consider integer variable int i = 100;

The system stores 100 in the memory space allocated for the variable 'i'. The following image
illustrates how 100 is stored at some hypothetical location in the memory (0x239110) for 'i':

24 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

The following table lists the available value types in C# 2010 −

Type Represents Range

bool Boolean value True or False

byte 8-bit unsigned integer 0 to 255

char 16-bit Unicode character U +0000 to U +ffff

decimal 128-bit precise decimal values


(-7.9 x 1028 to 7.9 x 1028) / 100 to
with 28-29 significant digits
28

double 64-bit double-precision floating (+/-)5.0 x 10-324 to (+/-)1.7 x 10308


point type

float 32-bit single-precision floating


point type -3.4 x 1038 to + 3.4 x 1038

int 32-bit signed integer type -2,147,483,648 to 2,147,483,647

long 64-bit signed integer type -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

sbyte 8-bit signed integer type -128 to 127

short 16-bit signed integer type -32,768 to 32,767

uint 32-bit unsigned integer type 0 to 4,294,967,295

ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615

ushort 16-bit unsigned integer type 0 to 65,535

2. Reference types
Reference type is another form of the variable that does not hold the actual value or data, instead, it
possesses a reference to any memory location that is assigned with a variable. This refers to a
memory location.
For example, consider following string variable:

string s = "Hello World!!";

The following image shows how the system allocates the memory for the above string
variable.

Programming Technology © Er. Shiva Ram Dam, 2019 25


3. ELEMENTS OF .NET LANGUAGES

As you can see in the above image, the system selects a random location in memory (0x803200) for
the variable 's'. The value of a variable s is 0x600000 which is the memory address of the actual data
value. Thus, reference type stores the address of the location where the actual value is stored instead
of value itself.
The following data types are of reference type:

• String
• All arrays, even if their elements are value types
• Class
• Delegates

3. Pointer types
Pointer type variables store the memory address of another type. Pointers in C# have the same
capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is −

type* identifier;

For example,

char* cptr;
int* iptr;

C# - Type Conversion
Type conversion is converting one type of data to another type. It is also known as Type Casting. In
C#, type casting has two forms −
• Implicit type conversion − These conversions are performed by C# in a type-safe manner. For
example, conversions from smaller to larger integral types and conversions from derived classes
to base classes.

using System;
namespace Teaching_CSharp
{
class Program
{
static void Main(string[] args)
{
double b = 12.45;
int x = 10;
b = b + x;
Console.WriteLine(b);
Console.ReadKey();
}
}
}

26 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

Output:
22.45

• Explicit type conversion − These conversions are done explicitly by users using the pre-defined
functions. Explicit conversions require a cast operator.
The following example shows an explicit type conversion –
using System;
namespace TypeConversionApplication {
class ExplicitConversion {
static void Main(string[] args) {
double d = 5673.74;
int i;
// cast double to int.
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result −
5673

C# Type Conversion Methods


C# provides the following built-in type conversion methods −

Sr.No. Methods & Description

1 ToBoolean
Converts a type to a Boolean value, where possible.

2 ToByte
Converts a type to a byte.

3 ToChar
Converts a type to a single Unicode character, where possible.

4 ToDateTime
Converts a type (integer or string type) to date-time structures.

5 ToDecimal
Converts a floating point or integer type to a decimal type.

6 ToDouble
Converts a type to a double type.

7 ToInt16
Converts a type to a 16-bit integer.

8 ToInt32

Programming Technology © Er. Shiva Ram Dam, 2019 27


3. ELEMENTS OF .NET LANGUAGES

Converts a type to a 32-bit integer.

9 ToInt64
Converts a type to a 64-bit integer.

10 ToSbyte
Converts a type to a signed byte type.

11 ToSingle
Converts a type to a small floating point number.

12 ToString
Converts a type to a string.

13 ToType
Converts a type to a specified type.

14 ToUInt16
Converts a type to an unsigned int type.

15 ToUInt32
Converts a type to an unsigned long type.

16 ToUInt64
Converts a type to an unsigned big integer.

The following example converts various value types to string type −

using System;
namespace TypeConversionApplication {
class StringConversion {
static void Main(string[] args) {
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result −

75
53.005
2345.7652
True

28 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

Operators in C#
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

1. Arithmetic Operators
These are the operators that perform mathematical operations. Following table shows all the
arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20 then −
Show Examples

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2

% Modulus Operator and remainder of after an integer division B%A=0

++ Increment operator increases integer value by one A++ = 11

-- Decrement operator decreases integer value by one A-- = 9

2. Relational Operators
These operators perform basic comparisons. Following table shows all the relational operators
supported by C#.

Operator Description Example

== Checks if the values of two operands are equal. If yes then (A == B)


condition becomes true.

!= Checks if the values of two operands are equal not equal. If (A != B)


values are not equal then condition becomes true.

> Checks if the value of left operand is greater than the value of (A > B)
right operand, if yes then condition becomes true.

< Checks if the value of left operand is less than the value of right (A < B)
operand, if yes then condition becomes true.

>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand, if yes then condition becomes true.

Programming Technology © Er. Shiva Ram Dam, 2019 29


3. ELEMENTS OF .NET LANGUAGES

<= Checks if the value of left operand is less than or equal to the (A <= B)
value of right operand, if yes then condition becomes true.

3. Logical Operators
These operators perform logical operations. Following table shows all the logical operators supported
by C#.

Operator Description Example

&& Called Logical AND operator. Returns True if both (A>0) &&( B>0)
conditions are true.

|| Called Logical OR Operator Returns True if any one of (A>0) || ( B>0)


conditions are true..

! Called Logical NOT Operator. Use to reverses the logical !(A >0)
state of its operand. If a condition is true then Logical NOT
operator will make false.

4. Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as
follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60
and variable B holds 13, then –

Operator Description Example

& Binary AND Operator copies a bit to the result (A & B) = 12, which is 0000

30 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

if it exists in both operands. 1100

| Binary OR Operator copies a bit if it exists in (A | B) = 61, which is 0011


either operand. 1101

^ Binary XOR Operator copies the bit if it is set (A ^ B) = 49, which is 0011
in one operand but not both. 0001

~ (~A ) = -61, which is 1100


Binary Ones Complement Operator is unary
0011 in 2's complement due
and has the effect of 'flipping' bits.
to a signed binary number.

<< Binary Left Shift Operator. The left operands


A << 2 = 240, which is 1111
value is moved left by the number of bits
0000
specified by the right operand.

>> Binary Right Shift Operator. The left operands


A >> 2 = 15, which is 0000
value is moved right by the number of bits
1111
specified by the right operand.

5. Assignment Operators
There are following assignment operators supported by C# −

Operator Description Example

= Simple assignment operator, Assigns values from right C = A + B assigns


side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right operand to C += A is equivalent


the left operand and assign the result to left operand to C = C + A

-= Subtract AND assignment operator, It subtracts right


C -= A is equivalent
operand from the left operand and assign the result to
to C = C - A
left operand

*= Multiply AND assignment operator, It multiplies right


C *= A is equivalent
operand with the left operand and assign the result to left
to C = C * A
operand

/= Divide AND assignment operator, It divides left operand


C /= A is equivalent
with the right operand and assign the result to left
to C = C / A
operand

%= Modulus AND assignment operator, It takes modulus C %= A is equivalent


using two operands and assign the result to left operand to C = C % A

<<= Left shift AND assignment operator C <<= 2 is same as C


= C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C


= C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C


=C&2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C

Programming Technology © Er. Shiva Ram Dam, 2019 31


3. ELEMENTS OF .NET LANGUAGES

=C^2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C =


C|2

6. Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? : supported by C#.

Operator Description Example

sizeof() Returns the size of a data type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);

& Returns the address of an &a; returns actual address of the variable.
variable.

* Pointer to a variable. *a; creates pointer named 'a' to a variable.

?: age>25 ? 50000 : 30000


Conditional Expression If Condition is true ? Then value X : Otherwise
value Y

is Determines whether an object if( Ford is Car) // checks if Ford is an object of


is of a certain type. the Car class.

as Cast without raising an Object obj = new StringReader("Hello");


exception if the cast fails. StringReader r = obj as StringReader;

3.3. C# statements, objects and classes, Array and Strings


C# - Decision Making statements
Conditional statements are those that execute certain program statements only when a
certain condition within a program has been fulfilled. And optionally, other statements are
executed if condition is found false.
C# provides following types of decision making statements:

Sr.No. Statement & Description

1 if statement
An if statement consists of a boolean expression followed by one or more statements.
Example:
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 10;
if (a >0)
Console.WriteLine("Positive no");

32 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

Console.ReadLine();
}
}
}

2 if...else statement
An if statement can be followed by an optional else statement, which executes when
the boolean expression is false.
Example:
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 10;
if (a >0)
Console.WriteLine("Positive no");
else
Console.WriteLine("Not positive");
Console.ReadLine();
}
}
}

3 if else ladder
This climbs down the ladder of if else until the condition is found true. If none of the
condition is True, the statement inside the else block is executed.
Sample program:
namespace Basic_Understanding
{
class Program
{
static void Main(string[] args)
{
int a = 10;
if (a >0)
Console.WriteLine("Positive no");
else if (a<0)
Console.WriteLine("negative no");
else
Console.WriteLine("zero");
Console.ReadLine();
}
}
}

4 nested if statements
We can use one if or else if statement inside another if or else ifstatement(s). This is
nested if statement.
Example:
namespace Basic_Understanding
{
class Program
{
static void Main(string[] args)
{
int a = 0;

Programming Technology © Er. Shiva Ram Dam, 2019 33


3. ELEMENTS OF .NET LANGUAGES

if (a >0)
Console.WriteLine("Positive no");
else
{
if (a<0)
Console.WriteLine("negative no");
else
Console.WriteLine("zero");
}
Console.ReadLine();
}
}
}

5 switch statement
A switch statement allows a variable to be tested for equality against a list of values.
Sample program:
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
char grade = 'B';
switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Very Good!");
break;
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}

34 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

C# - Looping statements
Looping is the process of repeating a block of statements until a desired number of times. C#
provides following types of loop to handle looping requirements. Click the following links to check
their detail.

Sr.No. Loop Type & Description

1 while loop
It repeats a statement or a group of statements while a given condition is true. It tests the
condition before executing the loop body.
Sample program:
using System;
namespace Basic_Understanding
{
class Program
{
static void Main(string[] args)
{
int n=1;
while (n <= 5)
{
Console.WriteLine(n);
n++;
}
Console.ReadLine();
}
}
}

2 for loop
It executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Sample program:
using System;
namespace Basic_Understanding
{
class Program
{
static void Main(string[] args)
{
int c, n=1;
for (c=1;c<=5;c++)
{
Console.WriteLine(n);
n++;
}
Console.ReadLine();
}
}
}

3 do...while loop
It is similar to a while statement, except that it tests the condition at the end of the loop
body
Sample program:

using System;

Programming Technology © Er. Shiva Ram Dam, 2019 35


3. ELEMENTS OF .NET LANGUAGES

namespace Basic_Understanding
{
class Program
{
static void Main(string[] args)
{
int n=1;
do
{
Console.WriteLine(n);
n++;
}while(n <= 5);

Console.ReadLine();
}
}
}

4 foreach loop
The foreach loop is used to iterate over the elements of the collection. The collection may
be an array or a list. It executes for each element present in the array.
Syntax:
foreach(data_type var_name in collection_variable)
{
// statements to be executed
}

Sample program:
// C# program to illustrate the use of foreach loop
using System;
class Test {
static public void Main()
{
Console.WriteLine("Print array:");

// creating an array
int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };

// foreach loop begin


// it will run till the last element of the array
foreach(int items in a_array)
{
Console.WriteLine(items);
}
}
}

Output:
Print array:
1
2
3
4
5
6

36 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

5 nested loops
We can use one or more loop inside any another while, for or do..while loop. This is called
nesting of loops.

Difference between for and foreach loop:

• for loop executes a statement or a block of statement until the given condition is false.
Whereas foreach loop executes a statement or a block of statements for each element present in
the array and there is no need to define the minimum or maximum limit.
• In for loop, we iterate the array in both forward and backward directions, e.g from index 0 to 9 and
from index 9 to 0. But in the foreach loop, we iterate an array only in the forward direction, not in a
backward direction.
• In terms of a variable declaration, foreach loop has five variable declarations whereas for loop
only have three variable declarations.
• The foreach loop copies the array and put this copy into the new array for operation. Whereas for
loop doesn't do.

Array

An array as a collection of variables of the same type stored at contiguous memory locations.
For Eg:
int[] n = new int[5] //creates an array of 5 blocks starting from n[0] to n[4].

There are 3 types of arrays in C# programming:


1. Single Dimensional Array
2. Multidimensional Array
3. Jagged Array

1. Single Dimensional Array


1-D array declaration:

datatype[] arrayName;

For eg:
int[] n = {1,2,3,4,5}; //compile time initialization
int[] n = new int[5]; // declaration for run time initialization
int[] n = new int[5] {1,2,3,4,5}; //compile time initialization
Sample program:
// program to accept any five integers and display the third element
namespace Basic_Understanding
Programming Technology © Er. Shiva Ram Dam, 2019 37
3. ELEMENTS OF .NET LANGUAGES

{
class Program
{
static void Main(string[] args)
{
int i;
int[] n = new int[5];
Console.WriteLine("Enter any five integers:");
for (i = 0; i < 5; i++)
{
n[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Third element is:{0}", n[2]);
Console.ReadKey();
}
}
}

2. Multidimensional Array
The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or
three dimensional. The data is stored in tabular form (row * column) which is also known as matrix.
To create multidimensional array, we need to use comma inside the square brackets.

int[,] arr=new int[2,3]; //declaration of 2D array


int[,,] arr=new int[2,3,4]; //declaration of 3D array
int[,] arr = { { 1, 2 }, { 5, 6 }, { 8, 9 } };
//compile time initialization of 3 x 2 matrix
int[,] arr = new int[2,3]= { { 1, 2}, { 5, 6 }, { 8, 9 } };
// compile time initialization

Sample program:

// program to accept 2x3 matrix and display them


using System;
namespace Basic_Understanding
{
class Program
{
static void Main(string[] args)
{
int i,j;
int[,] n = new int[2,3];
Console.WriteLine("Enter the 2 x3 matrix:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
n[i, j] = Convert.ToInt32(Console.ReadLine());
}
}

Console.WriteLine("The matrix elements are:");


for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
Console.Write(n[i, j] + " ");
}
Console.WriteLine();
}

38 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

Console.ReadKey();
}
}
}

3. Jagged Array
In C#, jagged array is also known as "array of arrays" because its elements are arrays. The
element size of jagged array can be different.
General way of jagged array declaration is:

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,86,87,88}};

Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers {92,93,94}
and scores[1] is an array of 4 integers {86,86,87,88}.

Sample program:
using System;

namespace Basic_Understanding Output:


{
class Program
{
static void Main(string[] args)
{
int i, j;
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{
new int[]{0,0},
new int[]{1,2,6,5},
new int[]{2,4},
new int[]{ 3, 6 },
new int[]{ 4, 8,10 }
};

/* output each array element's value */


for (i = 0; i < 5; i++)
{
for (j = 0; j < a[i].Length; j++)
{
Console.Write(a[i][j]+" ");
}
Console.WriteLine(); // this is for new line
}
Console.ReadKey();
}
}
}

String:
In C#, we can use strings as array of characters. However, more common practice is to use
the string keyword to declare a string variable. The string keyword is an alias for
the System.String class.
We can create string object using one of the following methods −
• By assigning a string literal to a String variable
• By using a String class constructor
• By using the string concatenation operator (+)
• By retrieving a property or calling a method that returns a string

Programming Technology © Er. Shiva Ram Dam, 2019 39


3. ELEMENTS OF .NET LANGUAGES

Sample program:
using System;
namespace Basic_Understanding
{
class Program
{
Output:
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Pooja";
lname = "Sharma";

char[] letters = { 'H', 'e', 'l', 'l', 'o' };


string[] s_array = { "Hello", "From", "Pooja" };

string fullname = fname + lname;


Console.WriteLine("Full Name: {0}", fullname);

//by using string constructor { 'H', 'e', 'l', 'l','o' };


string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);

//methods returning string { "Hello", "From", "Pooja"};


string message = String.Join(" ", s_array);
Console.WriteLine("Message: {0}", message);
Console.ReadKey();
}
}
}

Classes and Objects


In C#, class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc. A class definition starts with the keyword class followed by the class
name; and the class body enclosed by a pair of curly braces.
The general format for class declaration is:

<access specifier> class class_name


{

<access specifier> <data type> variable1; //member variables


... ... ...

<access specifier> <return type> method1(parameter_list) // member methods


{
... ...
}
}

In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words,
object is an entity that has state and behavior. Here, state means data and behavior means
functionality. Object is a runtime entity, it is created at runtime. Object is an instance of a class. All the
members of the class can be accessed through object.
To create object we use new keyword. For eg:
Student s1 = new Student(); //creating an object of class Student

Sample Program:

40 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

//program to accept two numbers and display the sum


using System;
namespace Basic_Understanding
{
class Program
{
public int x, y, z; //member variables
public void getdata() //member function1
{
Console.WriteLine("Enter two integers:");
x = Convert.ToInt32(Console.ReadLine());
y = Convert.ToInt32(Console.ReadLine());
}
public void showdata() //member function2
{
z = x + y;
Console.WriteLine("Sum is:" + z);
}
}

class Test
{
static void Main(string[] args)
{
Program ob1=new Program(); //object creation
ob1.getdata();
ob1.showdata();
Console.ReadKey();
}
}
}

3.4. System collection, Delegates and Events, Indexes, Attributes, Versioning


System collection
Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements and
accessing a list of items on the basis of an index etc.

Below table show various commonly used classes of System.Collection namespace:

S.No. Class & Description and Useage

1 ArrayList
It represents ordered collection of an object that can be indexed individually.
It is basically an alternative to an array. However, unlike array you can add and
remove items from a list at a specified position using an index and the array
resizes itself automatically. It also allows dynamic memory allocation, adding,
searching and sorting items in the list.

2 Hashtable
It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can

Programming Technology © Er. Shiva Ram Dam, 2019 41


3. ELEMENTS OF .NET LANGUAGES

identify a useful key value. Each item in the hash table has a key/value pair. The
key is used to access the items in the collection.

3 SortedList
It uses a key as well as an index to access the items in a list.
A sorted list is a combination of an array and a hash table. It contains a list of items
that can be accessed using a key or an index. If you access items using an index,
it is an ArrayList, and if you access items using a key , it is a Hashtable. The
collection of items is always sorted by the key value.

4 Stack
It represents a last-in, first out collection of object.
It is used when you need a last-in, first-out access of items. When you add an item
in the list, it is called pushing the item and when you remove it, it is
called popping the item.

5 Queue
It represents a first-in, first out collection of object.
It is used when you need a first-in, first-out access of items. When you add an item
in the list, it is called enqueue and when you remove an item, it is called deque.

6 BitArray
It represents an array of the binary representation using the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits in
advance. You can access items from the BitArray collection by using an integer
index, which starts from zero.

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections?view=netframework-4.8

1. Sample Program for ArrayList:

using System;
using System.Collections;

namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();

Console.WriteLine("Adding some numbers:");


al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);

Console.WriteLine("Capacity: {0} ", al.Capacity);


Console.WriteLine("Count: {0}", al.Count);

Console.Write("Content: ");

42 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

foreach (int i in al)


{
Console.Write(i + " ");
}

Console.WriteLine();
Console.Write("Sorted Content: ");

al.Sort();
// al.Reverse(); //to reverse the arrayList
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}

Output:

2. Sample Program for HashTable:


using System;
using System.Collections;

namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();

ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add("VI", "Four");
ht.Add("V", "Five");

string str1 = (string)ht[2];


string str2 = (string)ht["V"];

Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadKey();
}
}
}
Output:

Difference between Array and ArrayList:

Programming Technology © Er. Shiva Ram Dam, 2019 43


3. ELEMENTS OF .NET LANGUAGES

Array ArrayList
Array uses the Vector array to store the
ArrayList uses the LinkedList to store the elements.
elements

Size of the Array must be defined until


No need to specify the storage size.
redim used( vb)
Array is a specific data type storage ArrayList can be stored everything as object.
No need to do the type casting Every time type casting has to be done.

It will not lead to Runtime exception It leads to the Run time error exception.

Element cannot be inserted or deleted


Elements can be inserted and deleted.
in between.

There is no built in members to do ArrayList has many methods to do operation like Sort,
ascending or descending. Insert, Remove, BinarySeacrh,etc..

Delegates
A delegate is like a pointer to a function. It is a reference type data type and it holds the reference of a
method. All the delegates are implicitly derived from System.Delegate class.
A delegate can be declared using delegate keyword followed by a function signature as shown
below.

Syntax:
<access modifier> delegate <return type> <delegate_name>(<parameters>)
Example:
public delegate void Print(int value);

Sample Program:

using System;
delegate int Calculator(int n); //declaring delegate Calculator()

public class DelegateExample


{
static int number = 100;
public static int add(int n)
{
number = number + n;
return number;
}
public static int mul(int n)
{
number = number * n;
return number;
}
public static int getNumber()
{
return number;
}

public static void Main(string[] args)


{
Calculator c1 = new Calculator(add); //instantiating delegate
Calculator c2 = new Calculator(mul);
c1(20); //calling method using delegate
Console.WriteLine("After c1 delegate, Number is: " + getNumber());

44 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

c2(3);
Console.WriteLine("After c2 delegate, Number is: " + getNumber());
Console.ReadKey();
}
}

Output:

Events
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such
as system generated notifications.

Let us design a form as below:


using System;
using System.Windows.Forms;

namespace Learning_Events_in_CSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
label1.Text = "Button Clicked";
}
}
}

Output is obtained as: (after button is clicked)

Indexers
An Indexer is a special type of property that allows a class or structure to be accessed the same way
as array for its internal collection. It is same as property except that it defined with this keyword with
square bracket and parameters.
An indexer allows an object to be indexed such as an array. When you define an indexer for a class,
this class behaves similar to a virtual array. You can then access the instance of this class using the
array access operator ([ ]).
Refer: https://www.tutorialsteacher.com/csharp/csharp-indexer
https://www.geeksforgeeks.org/c-sharp-indexers/

https://www.tutorialspoint.com/csharp/csharp_indexers

Sample program:

Programming Technology © Er. Shiva Ram Dam, 2019 45


3. ELEMENTS OF .NET LANGUAGES

using System;

namespace Test_Program_for_teaching
{
public class StringDataStore
{
public string[] strArr = new string[5]; // internal data storage

public string this[int index]


{
get
{
if (index < 0 && index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10
objects");
return strArr[index];
}

set
{
if (index < 0 && index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10
objects");
strArr[index] = value;
}
}
}

public class Program


{
public static void Main()
{
StringDataStore st = new StringDataStore();
st[0] = "One";
st[1] = "Two";
st[2] = "Three";
st[3] = "Four";

for (int i = 0; i < 5; i++)


Console.WriteLine(st[i]);
Console.ReadKey();
}
}
}

Output:

Attributes
An attribute is a declarative tag that is used to convey information to runtime about the behaviors of
various elements like classes, methods, structures, enumerators, assemblies etc. in your program.
You can add declarative information to a program by using an attribute. A declarative tag is depicted
by square ([ ]) brackets placed above the element it is used for.

46 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

Attributes are used for adding metadata, such as compiler instruction and other information such as
comments, description, methods and classes to a program. The .Net Framework provides two types
of attributes: the pre-defined attributes and custom built attributes.
Sample program:
using System;
namespace Test_Program_for_teaching
{
class Program
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]

static void OldMethod()


{
Console.WriteLine("It is the old method");
}
static void NewMethod() {
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}
}

When you try to compile the program, the compiler gives an error message stating –
Don’t use OldMethod, use NewMethod instead

Refer: https://www.tutorialspoint.com/csharp/csharp_attributes.htm

Versioning
Whenever a new .NET assembly is created in the .Net environment, a file named AssemblyInfo is
created that contains attributes used to define the version of the assembly during compilation. All
versioning of assemblies that use the common language runtime is done at the assembly level. The
AssemblyVersion attribute assigns the version number of the assembly, and this is embedded in the
manifest. Version information for an assembly consists of the following four values : a major and minor
version number, and two further optional build and revision numbers.
Major Version
This is the internal version of the product and is assigned by the application team. It should not
change during the development cycle of a product release
Minor Version
This should only change when there is a small changes to existing features. It is assigned by the
application team, and it should not be changed during the development cycle of a product release.
Build Number
Typically incremented automatically as part of every build performed on the Build Server. Using
the build number in conjunction with the source number allows you to identify what was built and
how. This allows each build to be tracked and tested.
Revision

Programming Technology © Er. Shiva Ram Dam, 2019 47


3. ELEMENTS OF .NET LANGUAGES

This is the number taken from source control to identify what was actually built. This is set to zero
for the initial release of any major or minor version of the solution.

3.5. .NET libraries, I/O, Namespace system, Windows forms


.NET libraries
.NET Framework Class Library is the collection of classes, namespaces, interfaces and value types
that are used for .NET applications.
It contains thousands of classes that support the following functions:
o Base and user-defined data types
o Support for exceptions handling
o input/output and stream operations
o Communications with the underlying system
o Access to data
o Ability to create Windows-based GUI applications
o Ability to create web-client and server applications
o Support for creating web services

Following are the commonly used namespaces that contains useful classes and interfaces and
defined in Framework Class Library.

Namespaces Description

System It includes all common datatypes, string values, arrays


and methods for data conversion.

System.Data, These are used to access a database, perform


System.Data.Common, commands on a database and retrieve database.
System.Data.OleDb,
System.Data.SqlClient,
System.Data.SqlTypes

System.IO, These are used to access, read and write files.


System.DirectoryServices,
System.IO.IsolatedStorage

48 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

System.Windows.Forms, These namespaces are used to create Windows-based


System.Windows.Forms.Design applications using Windows user interface components.

IO namespace
In the .NET Framework, the System.IO namespace defines classes for reading and writing files and
data streams. The System.IO namespace, which resides in the mscorlib.dll assembly, provides
classes for working with the system I/O and with streams.
The main functionality of the System.IO namespaces in .NET includes the following features:
1. Accessing Buffer: The .NET Framework defines classes for reading and writing bytes,
multibytes, binary data, strings, and character data with the help of StreamReader.
2. File and Directory Operations: The classes in the System.IO namespaces provide
functionality for creation, deletion, and manipulation of files and directories.
3. Performance Optimization: The MemoryStream and the BufferStream classes enhance the
performance of read/write operations by storing data in memory.

Windows Forms
Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net Framework.
Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs.
It is also termed as the WinForms. The applications which are developed by using Windows Forms or
WinForms are known as the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms Applications not web applications.
WinForms applications can contain the different type of controls like labels, list boxes, dialogboxes,
activeX controls, etc.

The Windows Forms Namespaces


The Windows Forms API consists of hundreds of types (e.g., classes, interfaces, structures, enums,
and delegates), most of which are organized within various namespaces of the
System.Windows.Forms.dll assembly.
The System.Windows.Forms namespace is the logical hierarchical container of classes that we use to
build rich client applications—the windows, buttons, drop-down lists, and labels that make up the UIs .
Some of the major classes in the System.Windows.Forms are:

Sample Program:
using System;
using System.Collections.Generic;
using System.Linq;

Programming Technology © Er. Shiva Ram Dam, 2019 49


3. ELEMENTS OF .NET LANGUAGES

using System.Text;
using System.Windows.Forms; // The minimum required windows forms namespaces.
namespace SimpleWinFormsApp
{
// This is the application object.
class Program
{
static void Main(string[] args)
{
Application.Run(new MainWindow());
}
}
// This is the main window.
class MainWindow : Form {}
}

This code represents the absolute simplest Windows Forms application and will produce following
output.

Windows Form Programming:


1. Design a form and write visual C# program that accepts two numbers in two different textboxes
and displays the sum in another textbox when an ADD button is clicked.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Learning_Programming_in_WindowsForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnAdd_Click(object sender, EventArgs e)


{
int a = Convert.ToInt32(txtFirstNo.Text);
int b = Convert.ToInt32(txtSecondNo.Text);

50 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

int sum = a + b;
txtSum.Text = Convert.ToString(sum);
}
}
}
2. Design a form and write visual C# program that accepts your name, address, photo, Gender,
DOB and College and displays a message “Data Saved” in a message box when you click SAVE
button and also the data in a ListBox in the form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Learning_Programming_in_WindowsForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnSave_Click(object sender, EventArgs e)


{
lbxData.Items.Add("Data Saved are:");
lbxData.Items.Add(txtName.Text);
lbxData.Items.Add(txtAddress.Text);
lbxData.Items.Add(txtClass.Text);
lbxData.Items.Add(txtCollege.Text);
if(rbtMale.Checked ==true)
lbxData.Items.Add("Male");
else if(rbtFemale.Checked == true)
lbxData.Items.Add("Female");
}
}
}

3. Design a form and write visual C# program that accepts any three numbers and displays the
largest among them.

Programming Technology © Er. Shiva Ram Dam, 2019 51


3. ELEMENTS OF .NET LANGUAGES

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Learning_Programming_in_WindowsForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnCheck_Click(object sender, EventArgs e)


{
int a = Convert.ToInt32(txtFirstNo.Text);
int b = Convert.ToInt32(txtSecondNo.Text);
int c= Convert.ToInt32(txtSecondNo.Text);
if ((a>b) && (a>c))
txtLargestNo.Text = Convert.ToString(a);
else if ((b> a) && (b > c))
txtLargestNo.Text = Convert.ToString(b);
else
txtLargestNo.Text = Convert.ToString(c);
}
}
}

4. Design a form and write a Visual C# program that accepts a positive integer and displays the
factorial of that number.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;

52 Programming Technology © Er. Shiva Ram Dam, 2019


3. ELEMENTS OF .NET LANGUAGES

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Learning_Programming_in_WindowsForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFind_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(txtInputNo.Text);
int f = 1;
while (n > 0)
{
f = f * n;
n = n - 1;
}
txtFactorial.Text = Convert.ToString(f);
}
}
}

For more learning:


http://www.csharp-examples.net/
https://www.guru99.com/c-sharp-windows-forms-application.html
https://www.geeksforgeeks.org/csharp-programming-language/

Exam questions:
1. What is .net framework? Explain the basic C# program structure with suitable example program
and explain each line in detail. [2018 spring]
2. What is jagged array? Demonstrate the C# collection class with the help of Hash Table. [2018
spring]
3. Define Namespace and Versioning in C#. How does C# solve the real world problem? [2018 fall]
4. What are arrays in strings? How are they implemented in C#? Illustrate with an example. [2017
fall]
5. WAP to create a class Student. This class must possess general attributes of the students as well
as marks in 5 subjects. Illustrate different methods to take input and show the output, the different
attributes of the class. [2017 fall]
6. Describe some notable distinguishing features of C#. Discuss relationship between C# and .NET
framework. [2017 spring]
7. What is jagged array in C#.net? What is Delegate in C# and uses of delegates? [2017 spring]
8. What is delegate in C#? Illustrate with a meaningful example. [2016 fall]
9. How dot net application is created? Explain each process in brief. [2016 fall]
10. Define Delegate. Differentiate between simple array and ArrayList? Explain with example. [2016
spring]
11. What are keywords and identifiers? Explain different datatypes used in C#. [2015 spring]
12. WAP in C# to input the names of N cities and display them in alphabetical order. [2015 fall]

Programming Technology © Er. Shiva Ram Dam, 2019 53


3. ELEMENTS OF .NET LANGUAGES

13. What do you mean by versioning, namespace and delegates? WAP to calculate factorial using
recursive function. [2015 fall]
14. How does C# support encapsulating the method. Explain with an example. [2014 spring]
15. What are the C# collection classes? Define the term: Class, Object, Event and Delegate. [2014
spring]
16. Introduce C# programming with the help of its basic data types, literals, constants, operators and
variables. [2013 spring]
17. How Namespace system works in C# programming. Write a C# program to demonstrate the
concept of object and class. [2013 spring]

54 Programming Technology © Er. Shiva Ram Dam, 2019


4. DOT NET FRAMEWORK

Chapter 4: .NET Framework [Credit: 4 hrs]

4.1 Concept of .NET Framework


• The .NET framework is a programming infrastructure created by Microsoft for building,
deploying, and running applications and services that use .NET technologies, such
as desktop applications and Web services.
• It provides a controlled programming environment where software can be developed, installed
and executed on Windows-based operating systems.
• Microsoft started development of the.NET Framework in the late 1990s, originally under the
name of Next Generation Windows Services (NGWS).
• .NET framework supports many languages like: Visual C#.Net, Visual Basic.Net, Visual
J#.Net, Visual C++.Net, COBOL.Net, PERL.Net, VBScript.Net, JScript.Net, PHP.Net, Small
Talk.Net, Python.Net, Visual F#.Net and many more.
• The latest version of .NET framework is 4.7.1

Features of .NET Framework:


• .NET Framework is a software development framework.
• It includes library and runtime environment.
• Framework Class Library (FCL) provides interface, database connectivity, cryptography, web
development and many more.
• .Net programs are executed in CLR.
• It provides language interoperability.

Objectives of .NET Framework:


1. To provide a very high degree of language interoperability
2. To provide a runtime environment that completely manages code execution
3. To provide a very simple software deployment and versioning model
4. To provide high-level code security through code access security and strong type checking
5. To provide a consistent object-oriented programming model
6. To simplify Web application development

Advantages of .NET
• Object-oriented programming
• Language independence
• Efficient data access
• Code sharing
• Support for services

Programming Technology © Er. Shiva Ram Dam, 2019 55


4. DOT NET FRAMEWORK

The .NET Architecture:


.NET is tiered, modular, and hierarchal and consists of two major parts:

CLS

Framework
Class
Library

CLR

1. Common Language Runtime


The common language runtime is the bottom tier, the least abstracted, and closest to the
native environment. It is runtime engine, which provides necessary services while executing
.NET program.
• It provides runtime environment.
• It runs all the .Net programs.
• It lies just above the Operating System.
• CLR provides memory management and thread management.
• It allocates the memory for scope and deallocates the memory.

2. Framework Base Class Library


• All Microsoft’s pre-defined libraries are Framework Class Library.
• The .NET Framework class library is a comprehensive, object-oriented collection of
reusable types that we can use to develop applications.
• The .NET Framework class library includes ADO.NET, ASP.NET, and Windows Forms.
• It accesses the library classes and methods.
• It is also called as Base Class Library.
• It is common for all types of application.

Key terms in .Net Framework:


1. Common Type System (CTS)
This is a standardized agreed set of basic data types. This system provides a way for
language interoperability.

2. Common Language Specification (CLS)


The CLS is a common platform that integrates code and components from multiple .NET
programming languages. It is a subset of CTS.

56 Programming Technology © Er. Shiva Ram Dam, 2019


4. DOT NET FRAMEWORK

3. Microsoft Intermediate Language (MSIL) Code:


MSIL is the intermediate language which is first converted before converting to binary code.

4. The Just-In-Time (JIT) compilation


The JIT compiler converts IL into its native machine code. The name JIT is because it
compiles portion of code as and when required at run time.

5. .NET Base Classes


Base Class Library (BCL) is common Library for all Libraries. The .NET Base Classes is a
library or extensive set of functions for all services supported by the framework. The services
can be windows creation/ displaying of form handling, internet or web services, database
accessing or file handling.

6. Assemblies
It is the unit in which compiled managed code is stored. It contains IL and metadata. Metadata
gives details of the assembly, properties and methods stored in it, security information, etc.
The area of assembly where metadata is stored is called Manifest.

7. Garbage collection
The Garbage Collector frees the application from the responsibility of freeing memory when
no longer required. CLR calls garbage collector to handle memory efficiently.

8. Managed and Unmanaged code


The managed code (also called safe code) is one which is designed to run on .Net
environment. These are used in .NET programming.
The code, which is developed outside .NET, Framework is known as unmanaged code.
Applications that do not run under the control of the CLR are said to be unmanaged, and
certain languages such as C++ can be used to write such applications.

9. ADO.net
It stands for ActiveX Data Objects. It is used for database connectivity between our
application and database like MS SQL Server, Oracle, MS-Access, etc. It mainly consists of
classes that can be used to connect, retrieve, insert and delete data.

10. ASP.Net
This is used for developing web-based applications, which are made to run on any browser
such as Internet Explorer, Chrome or Firefox.

11. WinForms
This is used for developing Forms-based applications, which would run on an end user
machine. Notepad is an example of a client-based application.

12. XML
XML stands for Extensible Markup Language. These are designed to store and transport data
in web application.

Programming Technology © Er. Shiva Ram Dam, 2019 57


4. DOT NET FRAMEWORK

4.2 Common Type System (CTS)


This is a standardized agreed set of basic data types. This system provides a way for language
interoperability. Language interoperability means that an object implemented in one language can call
an object implemented in another language. In more general we can say that an application can be
developed in two or more languages supported by .NET Framework. To make use of language
interoperability feature, the developers have to follow CTS.
The CTS defines how types are declared, used and managed in the runtime. It is important for
language Interoperability. The CTS performs the following functions:
• Establishes a common framework that enables cross-language integration, type-safety, and
high performance code execution.
• Provides an object-oriented model.
• Defines rules that languages must follow, so that different languages can interact with each
other.

4.3 Common Language Specification (CLS)


To fully interact with other objects regardless of the language they were implemented in, objects
must follow some implementation rules. For this reason, a set of language features has been
defined, called the CLS. The CLS rules define a subset of the CTS i.e. all the rules that apply to
the CTS apply to the CLS. The CLS help enhance and ensure language interoperability by
defining a set of features to the developers.

4.4 Framework Class Library:


The Framework class library (FCL) is a comprehensive collection of reusable types including classes,
interfaces and data types included in the .NET Framework to provide access to system functionality.
The .NET FCL forms the base on which applications, controls and components are built in .NET. It
can be used for developing applications such as console applications, Windows GUI
applications, ASP.NET applications, Windows and Web services, workflow-enabled applications,
service oriented applications using Windows Communication, XML Web services, etc.

4.5 Base Class library


• It is a library of classes, interfaces, and value types.

• This library system functionality and is the foundation of .NET Framework applications,
components, and controls are built.

• The .NET base class library exists in order to encapsulate a huge number of common
functions and makes them easily accessible to the developer.

• It provides the functionality like ADO.NET, XML, Threading, IO, Security, Diagnostics,
Resources, Globalization, collections etc.

• It serves as the main point of interaction between developer and runtime.

The .Net base class library provides namespaces which are frequently used, some of them are as
follows:

Namespaces Description
System It contains fundamental classes and base classes that define
commonly-used value and reference data types, events and event
handlers, interfaces, attributes and processing exceptions.

58 Programming Technology © Er. Shiva Ram Dam, 2019


4. DOT NET FRAMEWORK

System.Activities It contains all the classes necessary to create and work with activities in
Windows Workflow Foundation.
System.Collections It contains types that define various standard, specialized and generic
collection objects.
System.Configuration It contains types that define various standard, specialized and generic
collection objects.
System.Data It contains classes for accessing and managing data from diverse
sources.
System.Deployment It contains types that define support deployment of ClickOnce
application.
System.EnterpriseServices It contains types that define the com+services architechture, which
provides an infrastructure for enterprise application.
System.Globalization It contains classes that define culture-related information, including
language, country/region, calenders in use, currency.
System.IO It contains types that support input and output, including the ability to
read and write data to streams either synchronously or asynchronously.
System.Linq It contains types that support queries which is used Language-
Integrated Query (LINQ). It includes types that represent queries as
objects in expression trees.
System.Management It contains a type that provides access to management information and
management events about the system, devices and applications
instrumented to the Windows Management Instrumentation (WMI)
infrastructure.
System.Net It contains classes that provide a simple programming interface for a
number of network protocols.
System.Printing It contains types that support printing. It provides access to the
properties of print system objects.
System.Runtime It contains types that support an application’s interaction with the
common language runtime.
System.Security It contains classes that represent the .Net framework security system
and permissions.
System.Windows It contains types used in Windows Presentation Foundation (WPF)
application, including animation clients, user interface controls, data
binding.

4.6 Common Language Runtime (CLR)


The Common Language Runtime (CLR) is an Execution Environment. It works as a layer between
Operating Systems and the applications written in .Net languages that conforms to the Common
Language Specification (CLS).
The main function of Common Language Runtime (CLR) is to convert the Managed Code into native
code and then execute the Program. The Managed Code compiled only when it is needed, i.e. it
converts the appropriate instructions when each function is called. The Common Language Runtime
(CLR)’s Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on
demand at application run time.

Programming Technology © Er. Shiva Ram Dam, 2019 59


4. DOT NET FRAMEWORK

Components of CLR:
Class Loader Used to load all classes at run time.
JIT The Just In Time (JIT) compiler will convert MSIL code into native code.
Code Manager It manages the code at run time.
Garbage Collector It manages the memory. Collects all unused objects and deallocate them
to reduce memory.
Thread Support It supports multithreading of our application.
Exception Handler It handles exceptions at run time.
Security manger It manages security.
Memory Manager Allocate and deallocate memory.

CLR as facilitator:
The CLR acts as a facilitator in two ways as mentioned below:
1. Run-time environment Setup:
CLR compiles application into the runtime, compiles the IL code into native code, executes
the code.
2. Run-time services
- Memory management
- Type safety
- Enforce security
- Exception management
- Thread support
- Debugging support

Just-in-time (JIT) Execution Process:

• The source code is compiled to .exe or .dll by the language compilers.


• The JIT Compiler processes the CIL instructions into machine code specific for an environment.
Program portability is ensured by utilizing CIL instructions in the source code.

60 Programming Technology © Er. Shiva Ram Dam, 2019


4. DOT NET FRAMEWORK

• The JIT compiler compiles only those methods called at runtime. It also keeps track of any
variable or parameter passed through methods and enforces type-safety in the runtime
environment of the .NET Framework.
Garbage collection:
Garbage collection is the process of removing unwanted resources when they are no longer required.
Examples of garbage collection are:
• A File handle which is no longer required. If the application has finished all operations on a
file, then the file handle may no longer be required.
• The database connection is no longer required. If the application has finished all operations
on a database, then the database connection may no longer be required.

One of the most important features of managed code is the concept of garbage collection. This is the
.NET method of making sure that the memory used by an application is freed up completely when the
application is no longer in use. Prior to .NET, this was mostly the responsibility of programmers, and a
few simple errors in code could result in large blocks of memory mysteriously disappearing as a result
of being allocated to the wrong place in memory. That usually meant a progressive slowdown of our
computer followed by a system crash.
.NET garbage collection works by periodically inspecting the memory of our computer and removing
anything from it that is no longer needed. There is no set time frame for this; it might happen
thousands of times a second, once every few seconds, or whenever, but we can be assured that it will
happen.

How garbage collection works?


Automatic memory management is made possible by Garbage Collection in .NET Framework. When
a class object is created at runtime, certain memory space is allocated to it in the heap memory.
However, after all the actions related to the object are completed in the program, the memory space
allocated to it is a waste as it cannot be used. In this case, garbage collection is very useful as it
automatically releases the memory space after it is no longer required.
Garbage Collection occurs if at least one of multiple conditions is satisfied. These conditions are given
as follows:
• If the system has low physical memory, then garbage collection is necessary.
• If the memory allocated to various objects in the heap memory exceeds a pre-set threshold,
then garbage collection occurs.
• If the GC.Collect method is called, then garbage collection occurs. However, this method is only
called under unusual situations as normally garbage collector runs automatically.

Phases of garbage collection:


There are mainly 3 phases in garbage collection. Details about these are given as follows:

Programming Technology © Er. Shiva Ram Dam, 2019 61


4. DOT NET FRAMEWORK

1. Marking Phase: A list of all the live objects is created during the marking phase. This is done by
following the references from all the root objects. All of the objects that are not on the list of live
objects are potentially deleted from the heap memory.
2. Relocating Phase: The references of all the objects that were on the list of all the live objects
are updated in the relocating phase so that they point to the new location where the objects will
be relocated to in the compacting phase.
3. Compacting Phase: The heap gets compacted in the compacting phase as the space occupied
by the dead objects is released and the live objects remaining are moved. All the live objects
that remain after the garbage collection are moved towards the older end of the heap memory in
their original order.

Exception Handling:
Exceptions are errors which occur when the application is executed.
Examples of exceptions are:
• If an application tries to open a file on the local machine, but the file is not present.
• If the application tries to fetch some records from a database, but the connection to the
database is not valid.

4.7 Intermediate Language


MSIL is the intermediate language which is first converted before converting to binary code. When we
compile our .NET code, it is first converted into intermediate code known as MSIL code which is then
interpreted by the CLR. MSIL is further converted into native code by JIT.

4.8 Assemblies, Class Libraries and Namespace


When we compile an application, the CIL code created is stored in an assembly. Assemblies include both
executable application files that we can run directly from Windows without the need for any other programs
(these have a .exe file extension) and libraries (which have a .dll extension) for use by other applications.
In addition to containing CIL, assemblies also include meta information (that is, information about the
information contained in the assembly, also known as metadata) and optional resources (additional
data used by the CIL, such as sound files and pictures). The meta information enables assemblies to
be fully self-descriptive. We need no other information to use an assembly, meaning we avoid
situations such as failing to add required data to the system registry and so on, which was often a
problem when developing with other platforms.
This means that deploying applications is often as simple as copying the files into a directory on a
remote computer. Because no additional information is required on the target systems, we can just run
an executable file from this directory (assuming the .NET CLR is installed).

Assemblies:
• Assembly is a basic element of packaging in .NET which consists of IL code, metadata and
any other files or information that an application needs to run.

62 Programming Technology © Er. Shiva Ram Dam, 2019


4. DOT NET FRAMEWORK

• Assemblies can be static or dynamic.


• Static assemblies can include .NET types (interfaces and classes) as well as required
resources for the assembly. Static assemblies are stored on disk.
• Dynamic assemblies are one which run directly from memory and are not saved to disk before
execution.

Class Libraries:
The .NET Framework class library is a library of classes, interfaces, and value types that provide
access to system functionality.

Namespace:
• Namespaces is a logical group of related classes that can be used by any other language
targeting the Microsoft .Net framework.
• It is more used for logical organization of our classes.
• Namespaces are a way of grouping type names and reducing the chance of name collisions.
• Programmers can also create their own Namespaces in .Net languages.
• System is root namespace and provides classes for all system services.
• For example, the Button type is contained in the System.Windows.Forms namespace.

Creating a .Net application


Summary of steps required to create a .NET application
1. Application code is written using a .NET-compatible language such as C#.
2. That code is compiled into CIL, which is stored in an assembly.

3. When this code is executed (either in its own right if it is an executable or when it is used from other code),
it must first be compiled into native code using a JIT compiler.

Programming Technology © Er. Shiva Ram Dam, 2019 63


4. DOT NET FRAMEWORK

4. The native code is executed in the context of the managed CLR, along with any other running applications
or processes.

4.9 Windows Presentation Foundation (WPF)


WPF is a graphical system for rendering user interfaces. It provides great flexibility in how we can lay
out and interact with our applications. The advantages of WPF for our application are its rich data
binding and visualization support and its design flexibility and styling.
WPF enables us to create an application that is more usable to our audience. It gives us the power to
design an application that would previously take extremely long development cycles and a calculus
genius to implement.
WPF’s graphics capabilities make it the perfect choice for data visualization. Take, for instance, the
standard drop-down list (or combo box). Its current use is to enable the user to choose a single item
from a list of items. For this example, suppose we want the user to select a car model for purchase.
The standard way of displaying this choice is to display a drop-down list of car model names from
which users can choose.

4.10 Windows Communication Foundation (WCF)


WCF is a Microsoft platform for building distributed and interoperable application systems that can talk
to each other. WCF focuses on connecting XML to programs that are built using development
languages supported by Microsoft, such as VB.NET and C#. To support this cross-language
communication, WCF uses the extensible Simple Object Access Protocol (SOAP).
SOAP is a method of transferring messages, or small amounts of information, over the Internet. SOAP
messages are formatted in XML and are typically sent using HTTP (hypertext transfer protocol).

Here, the first endpoint will transport a message in XML format over HTTP protocol and the second
endpoint will transport the message in binary format over TCP protocol. Here, we don’t need to
change the service code to configure these endpoints. This is done by the WCF.

64 Programming Technology © Er. Shiva Ram Dam, 2019


4. DOT NET FRAMEWORK

Exam Questions:
1. Define Common Language Runtime, Common Types System, Windows Communication
Foundation and garbage collection. [PU 2019 Spring]
2. How does garbage collection work in C#? Explain the phases of garbage collection. [PU 2019
Spring]
3. Define Common Language Runtime and Framework Class Library. Write the advantages of CLR.
[2018 spring]
4. Explain about WPF and CTF. What are the advantages of .net framework? [2018 fall]
5. What are WCF and WPF? Describe about the different base classes used in .NET framework.
[2017 fall]
6. Discuss the relationship between C# and .net framework. [2017 spring]
7. How .net application is created? Explain each process in brief. [2016 Fall]
8. Explain .NET framework with suitable diagram. How JIT compilation helps improve the runtime
performance of computer program? [2016 spring]
9. Discuss the merits of JIT compilation. Also, explain the process of garbage collection. [2015
spring]
10. What is JIT? How does it work in Dot Net framework? Explain with a block diagram. [2014 spring]
11. Explain the .net framework with its advantages. How JIT helps to improve the runtime
performance of computer program? [2013 spring]
12. Write short notes on:
a. Garbage collection [2017 fall]
b. CLR and CTS [2017 spring

Programming Technology © Er. Shiva Ram Dam, 2019 65


5. WEB AND DATABASE PROGRAMMING WITH .NET

Chapter 5: Web and Database programming with .NET [Credit: 3 hrs]

5.1. Active Server Pages (ASP)


ASP (aka Classic ASP) was introduced in 1998 as Microsoft's first server side scripting language.
Classic ASP pages have the file extension .asp and are normally written in VBScript.
Active Server Pages (ASP) is a server-side scripting technology that can be used to create dynamic
and interactive Web applications. An ASP page is an HTML page that contains server-side scripts that
are processed by the Web server before being sent to the user's browser. We can combine ASP with
Extensible Markup Language (XML), Component Object Model (COM), and Hypertext Markup
Language (HTML) to create powerful interactive Web sites.
Server-side scripts run when a browser requests an .asp file from the Web server. ASP is called by
the Web server, which processes the requested file from top to bottom and executes any script
commands. It then formats a standard Web page and sends it to the browser.
An example of classical asp page saved with .asp extension: This example displays the words "Hello
World" when run with Internet Information Services (IIS) server.
<%@ Language=VBScript %>
<html> <head> <title>Example 1</title> </head>
<body>
<% FirstVar = "Hello world!" %>
<%=FirstVar%>
</body>
</html>
For IIS installation; https://www.itnota.com/install-iis-windows/
Reference Video https://www.youtube.com/watch?v=nkus5mXuaFo

5.2. ASP.net
ASP.NET was released in 2002 as a successor to Classic ASP. ASP.NET pages have the
extension .aspx and are normally written in C# (C sharp). ASP.NET 4.6 is the latest official version of
ASP.NET.
ASP.Net is a web development platform provided by Microsoft. It is used for creating web-based
applications.
The first version of ASP.Net deployed was 1.0. The most recent version of ASP.Net is version 4.6.
ASP.Net is designed to work with the HTTP protocol. This is the standard protocol used across all
web applications.
ASP.Net applications can also be written in a variety of .Net languages. These include C#, VB.Net,
and J#.

Difference between ASP and ASP.NET:

S.NO. ASP ASP.NET

1 ASP is the interpreted language. ASP.NET is the compiled language.

2 ASP uses ADO (ActiveX Data Objects) ASP.NET uses ADO.NET to connect and work
technology to connect and work with with database.
databases.

3 ASP is partially object oriented. ASP.NET is fully object oriented.

Programming Technology © Er. Shiva Ram Dam, 2019 65


5. WEB AND DATABASE PROGRAMMING WITH .NET

S.NO. ASP ASP.NET

4 ASP Pages have the file ASP.NET Pages have the file extension .aspx.
extension .asp.

5 ASP doesn’t have the concept of ASP.NET inherits the class written in code behind.
inheritance.

6 ASP pages use scripting language. ASP.NET use full-fledged programming language.

7 Error handling is very poor in ASP. Error handling is very good in ASP.NET.

8 ASP has maximum four in-built ASP.NET has more than 2000 in-built classes.
classes i.e. Request, Response,
Session and Application.

ASP.NET Architecture and its Components


ASP.Net is a framework which is used to develop a Web-based application. The basic architecture of
the ASP.Net framework is as shown below.

Fig: ASP.NET Architecture Diagram

The architecture of the.Net framework is based on the following key components


1. Language – A variety of languages exists for .net framework. They are VB.net and C#. These
can be used to develop web applications.
2. Library - The .NET Framework includes a set of standard class libraries. The most common
library used for web applications in .net is the Web library. The web library has all the
necessary components used to develop.Net web-based applications.
3. Common Language Runtime - The Common Language Infrastructure or CLI is a platform.
.Net programs are executed on this platform. The CLR is used for performing key activities.
Activities include Exception handling and Garbage collection.

Seven key pillars of ASP.net

1. ASP.NET is integrated with the .NET Framework


The .NET Framework is divided into an almost painstaking collection of functional parts, with
tens of thousands of types (the .NET term for classes, structures, interfaces, and other core
programming ingredients).

2. ASP.NET is Compiled, Not Interpreted


ASP.NET applications, like all .NET applications, are always compiled. In fact, it’s impossible to
execute C# or Visual Basic code without it being compiled first.

66 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

3. ASP.NET is Multilanguage
No matter what language you use, the code is compiled into MSIL. MSIL is a stepping stone for
every managed application.

4. ASP.NET is Hosted by the Common Language Runtime


Perhaps the most important aspect of the ASP.NET engine is that it runs inside the runtime
environment of the CLR. The whole of the .NET Framework—that is, all namespaces,
applications, and classes—is referred to as managed code. Some benefits of CLR are:
Automatic memory management and garbage collection, Type safety, Extensible metadata,
Structured error handling, Multithreading, etc.

5. ASP.NET is Object-Oriented
ASP.NET is truly object oriented. Not only does your code have full access to all objects in the
.NET Framework, but you can also exploit all the conventions of an OOP (object-oriented
programming) environment.

6. ASP.NET supports all Browsers


ASP.NET addresses the problem of cross browser compatibility in a remarkably intelligent way.
Although you can retrieve information about the client browser and its capabilities in an
ASP.NET page, ASP.NET actually encourages developers to ignore these considerations and
use a rich suite of web server controls. These server controls render their markup adaptively by
taking the client’s capabilities into account.

7. ASP.NET is Easy to Deploy and Configure


Every installation of the .NET Framework provides the same core classes. As a result,
deploying an ASP.NET application is relatively simple. For no-frills deployment, you simply
need to copy all the files to a virtual directory on a production server (using an FTP program or
even a command-line command like XCOPY).

ASP.net File Types


ASP.NET development uses specific file types depending on the resource used. The following list
provides a good representation of the file types that you may encounter during ASP.NET
development:
File Type Description
.aspx Active Server Page Extended. These are ASP.NET webpages. They contain the user
interface and optionally the underlying application code. Users navigate/request to
one of these pages to start web application.
.ascx Active Server Control Extension. These are ASP.NET user controls. Basically, ASCX
files make it easy to use the same code across multiple ASP.NET web pages.
.c.config A configuration file (typically Web.Config) containing XML elements that represent
settings for ASP.NET features.
.asax ASP.NET Server Application file. This is the global application file (typically
Global.asax). We can use this file to define global variables.
.cs These are code-behind files that contain C# code.

ASP.NET Application Directories


The asp.net application folder contains list of specified folders that we can use of specific type of files
or content in each folder. The root folder structure is as following:
Directory Description
App_Browsers contains browser definitions stored in xml files. These xml files define the
capabilities of client side browsers for different rendering actions.
App_Code contains source code files like .cs or .vb that are dynamically compiled for
use in your application. These source code files are usually separate
components or a data access library

Programming Technology © Er. Shiva Ram Dam, 2019 67


5. WEB AND DATABASE PROGRAMMING WITH .NET

App_GlobalResources contains global resources that are accessible to every page in the web
application.
App_LocalResources serves the same purpose as app_globalresources, except that these
resources are accessible to a specific page only.
App_WebReferences stores references to web services that the web application uses. These
references can be remote code routines that a web application can call over
a network/Internet.
App_Data Stores data, including SQL Server Express database files, mdf files, xml file
and so on.
App_Themes contains collection of files like .skin and .css files that are used for
application look and feel appearance.
Bin contains all the precompiled .Net assemblies like DLLs that the ASP.NET
web application uses.

Compilation of ASP.net webpage


ASP.NET applications, like all .NET applications, are always compiled. In fact, it’s impossible to
execute C# or Visual Basic code without it being compiled first. .NET applications actually go through
two stages of compilation.
In the first stage, the C# code is compiled into an intermediate language called Microsoft Intermediate
Language (MSIL), or just IL. This first step is the fundamental reason that .NET can be language-
interdependent. Essentially, all .NET languages (including C#, Visual Basic, and many more) are
compiled into virtually identical IL code. This first compilation step may happen automatically when the
page is first requested. The compiled file with IL code is an assembly.
The second level of compilation happens just before the page is actually executed. At this point, the IL
code is compiled into low-level native machine code. This stage is known as just in time (JIT)
compilation, and it takes place in the same way for all .NET applications (including Windows
Applications, for example). Figure below shows this two-step compilation process. .NET compilation is
decoupled into two steps in order to offer developers the most convenience and the best portability.
Before a compiler can create low-level machine code, it needs to know what type of operating system
and hardware platform the application will run on (for example, 32-bit or 64-bit Windows). By having
two compile stages, we can create a compiled assembly with .NET code and still distribute this to
more than one platform.

Fig: Compilation of asp.net web page

JIT compilation probably wouldn’t be that useful if it needed to be performed every time a user
requested a web page from our site. Fortunately, ASP.NET applications don’t need to be compiled
every time a web page is requested. Instead, the IL code is created once and regenerated only when
the source is modified. Similarly, the native machine code files are cached in a system directory that
has a path.

68 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

5.3. ASP.net page life cycle.


When a page is requested, it is loaded into the server memory, processed, and sent to the browser.
Then it is unloaded from the memory. At each of these steps, methods and events are available,
which could be overridden according to the need of the application. In other words, you can write
your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the
page, except the directives, are part of this control tree. You can see the control tree by adding
trace= "true" to the page directive. We will cover page directives and tracing under 'directives' and
'event handling'.
The page life cycle phases are:
• Initialization
• Instantiation of the controls on the page
• Restoration and maintenance of the state
• Execution of the event handler codes
• Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any
stage of the page life cycle. It also helps in writing custom controls and initializing them at right time,
populate their properties with view-state data and run control behavior code.
Following are the different stages of an ASP.NET page:

1. Page request - When ASP.NET gets a page request, it decides whether to parse and compile
the page, or there would be a cached version of the page; accordingly the response is sent.
2. Starting of page life cycle - At this stage, the Request and Response objects are set. If the
request is an old request or post back, the IsPostBack property of the page is set to true. The
UICulture property of the page is also set.
3. Page initialization - At this stage, the controls on the page are assigned unique ID by setting
the UniqueID property and the themes are applied. For a new request, postback data is
loaded and the control properties are restored to the view-state values.
4. Page load - At this stage, control properties are set using the view state and control state
values.
5. Validation - Validate method of the validation control is called and on its successful execution,
the IsValid property of the page is set to true.
6. Postback event handling - If the request is a postback (old request), the related event handler
is invoked.

Programming Technology © Er. Shiva Ram Dam, 2019 69


5. WEB AND DATABASE PROGRAMMING WITH .NET

7. Page rendering - At this stage, view state for the page and all controls are saved. The page
calls the Render method for each control and the output of rendering is written to the
OutputStream class of the Response property of page.
8. Unload - The rendered page is sent to the client and page properties, such as Response and
Request, are unloaded and all cleanup done.

5.4. Server controls in ASP.net


Server Controls are the tags that are understood by the server. The runat = “Server” attribute is
always used for server control in ASP.net. There are basically three types of server controls.
1. HTML Server Controls - Traditional HTML tags
2. Web Server Controls - New ASP. NET tags
3. Validation Server Controls - For input validation

1. HTML Server Controls


• ASP.NET provides a way to work with HTML Server controls on the server side; programming
with a set of controls collectively is called HTML Controls.
• These controls are basically the original HTML controls but enhanced to enable server side
processing.
• For example, consider the HTML input control:

Features:
a) They generate their own interface.
b) They retain their state
c) They fire server-side events.

2. Web Server Controls


• These are similar to to the HTML sever controls, but they provide a richer object model with a
variety of properties for styles and formatting details.
• The syntax for creating a Web server control is:
<asp:control_name id= “some_id” runat =”server”/>
Eg:
<asp:button id="Button1" runat="server" text="SUBMIT" >

• Some of the web server controls are: Button, DataList, DropdownList, HyperLink, etc.
Features:
a) They provide a rich user interface.
b) They provide a consistent object model.
c) They tailor their output automatically.
d) They provide high-level features.

70 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

3. ASP.NET Validation Server Controls


• After you create a web form, you should make sure that mandatory fields of the form elements
such as login name and password are not left blank; data inserted is correct and is within the
specified range. Validation is the method of scrutinizing (observing) that the user has entered
the correct values in input fields.
• A Validation server control is used to validate the data of an input control. If the data does not
pass validation, it will display an error message to the user.
• Some of the validation server control are CompareValidator, RangeValidator,
CustomValidator, RequiredFieldValidator, etc.
• The syntax for creating a Validation server control is:
<asp:regularexpressionvalidator id="some_ID" runat="server">
Eg:
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtUsername"
ErrorMessage="cannot be empty" ForeColor="Red">
</asp:RequiredFieldValidator>

Sample Program:
Write a server side program to design a webpage as below. The Username cannot be left empty and
Email should be in proper format. Password should be of 10 digits. Re-password should be matching
with previous password. Make use of HTML, Web and Validation server controls as shown in the
figure.

Default.aspx Page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs"
Inherits="Server_Controls_Example_in_ASP.RegistrationMain" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Account Creation</title>
</head>
<body>
<h1>Create Account</h1>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Username</td>
<td><asp:TextBox ID="txtUsername" runat="server"></asp:TextBox></td>
<td ><asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="txtUsername" ErrorMessage="cannot be empty"
ForeColor="Red"></asp:RequiredFieldValidator></td>
</tr>

Programming Technology © Er. Shiva Ram Dam, 2019 71


5. WEB AND DATABASE PROGRAMMING WITH .NET

<tr>
<td>Email</td>
<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server" ControlToValidate="txtEmail" ErrorMessage="valid email required"
ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>Password</td>
<td><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator3"
runat="server" ControlToValidate="txtPassword" ErrorMessage="10 digits required"
MaximumValue="9999999999" MinimumValue="1000000000" Type="Integer"
ForeColor="Red"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><asp:TextBox ID="txtConfirm" runat="server"></asp:TextBox></td>
<td><asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="txtPassword" ControlToValidate="txtConfirm" ErrorMessage="must match
input password" ForeColor="Red"></asp:CompareValidator></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click"
Text="Save" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>

Output

If Username field is left blank then it is handled by the control name as RequiredFieldValidation
control.

If Password is not matching,

72 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

5.5. Steps involved in connecting to a SQL database using asp.net


Step Step Procedure Visual Repressentation
No.
1. Open your ASP.NET project. Create a
WinForm application

2. If you want a SQL Server database, you


can add the page (SQL Server
database). Add+New item (Ctrl+Shift+A).
Here, you can select Visual C# and
choose SQL Server database.
Afterwards, click "OK" button.

3. A new confirmation window appears for


placing the .mdf file into your project
folder. Accept it.

4. Go to the Server Explorer. You should


see the RegisterDataBase.mdf file in it.

Programming Technology © Er. Shiva Ram Dam, 2019 73


5. WEB AND DATABASE PROGRAMMING WITH .NET

5. Add New Table into your database.

6. Open the new table and you can fill the


data, which is like (studentname,
password) and afterwards, you click the
Update .

7. Here, the database and data are added.

8. Now, you can add SQL Data Source.


Drag and drop method. Here, click
Configure Data Source

74 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

9. Now, you can choose your database and


click NEXT button.
Select the ConnectionString and Click
NEXT button
Specify columns from a table or view and
afterwards, click Next button.
Test Query.

10.
Reference: https://www.c-sharpcorner.com/article/how-to-connect-sql-database-in-asp-net-using-c-sharp-and-insert-and-view-the-data-usi/

5.6. Data Access


ADO.NET Architecture
The .NET Framework includes its own data access technology: ADO.NET. ADO.NET consists of
managed classes that allow .NET applications to connect to data sources (usually relational
databases), execute commands, and manage disconnected data. The small miracle of ADO.NET is
that it allows us to write more or less the same data access code in web applications that we write for
client-server desktop applications, or even single-user applications that connect to a local database.
The figure below represents the ADO.NET architecture:

Figure: The ADO.NET architecture

ADO.NET consists of a set of Objects that expose data access services to the .NET environment. It is
a data access technology from Microsoft .Net Framework, which provides communication between
relational and non relational systems through a common set of components.
The two key components of ADO.NET are DataSet and Data Providers.
1. DataSet class provides mechanisms for managing data when it is disconnected from the data
source.

Programming Technology © Er. Shiva Ram Dam, 2019 75


5. WEB AND DATABASE PROGRAMMING WITH .NET

2. The Data Provider is a set of ADO.NET classes that allows us to access a specific database,
execute SQL commands, and retrieve data. It acts as a bridge between our application and a data
source. The various types of DataProvider are:
a. SQL Server .NET data provider
b. OLE DB .NET data provider
c. ODBC .NET data provider
d. Oracle .NET data provider

The classes that make up a data provider are:


S. No. Objects Descritption
1. Connection Used to establish a connection to data source.
2. Command Used to execute SQL commands and stored procedures.

3. Data Reader Used to retrieve data from a data source in a read-only and
forward-only mode.
This acts as bridge between dataset and data source to load the
4. Data Adapter dataset.
When changes are made to the dataset, the changes in the
database are actually done by the data adapter.

1. Connection Class
• This is the object that allows you to establish a connection with the data source.
• Depending on the actual .NET Data Provider involved, connection objects automatically pool
physical databases connections for us.
• Examples of connection objects are: OleDbConnection, SqlConnection, OracleConnection
and OdbcConnection.
• When the connection is established, SQL Commands may be executed, with the help of the
Connection Object, to retrieve or manipulate data in the Database. Once the Database activity
is over, connection should be closed and releases the resources.
• To use the connection code, we must import the System.Data.SqlClient namespace.
• Sql Server connection string is (for Windows authentication) :

string connectionString = "Data Source=ServerName ; Initial Catalog=DatabaseName ;


Integrated Security=SSPI ” ;
Eg:
string cs = "Data Source=myDatabase ; Initial Catalog=localhost ;
Integrated Security=SSPI ” ;

76 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

• Sql Server connection string is (for SQL server authentication) :


string connectionString = "Data Source=ServerName ; Initial Catalog=DatabaseName ;
User ID=UserName ; Password=Password ” ;
Eg:
string cs = "Data Source=myDatabase ; Initial Catalog=localhost ;
User ID=sa ; Password=pokhara ” ;

Testing Connection:
Once we’ve chosen our connection string, managing the connection is easy—we simply use the
Open() and Close() methods.
We can use the following code in the Page.Load event handler to test a connection and write its
status to a label. To use the connection code, we must import the System.Data.SqlClient
namespace.
// Default.aspx.cs
{
// Create the Connection object.
string cs = "Data Source=localhost; database=myDatabase; integrated security=SSPI";
// we can write database instead of initial catalog
SqlConnection con = new SqlConnection(cs);

try // Try to open the connection.


{
con.Open();
// gives server version
Label1.Text = "<b>Server Version:</b> " + con.ServerVersion;
// gives the status

Label1.Text += "<br /><b>Connection Is:</b> " + con.State.ToString();


}

catch (Exception err) // Handle an error by displaying the information.


{
Label1.Text = "Error reading the database. " + err.Message;
}

finally
{
// Either way, make sure the connection is properly closed.
// Even if the connection wasn't opened successfully,
// calling Close() won't cause an error.
con.Close();
Label1.Text += "<br /><b>Now Connection Is:</b> " +con.State.ToString();
}
}

If the connection is successful, you should get the message as:

Refer: https://www.guru99.com/insert-update-delete-asp-net.html

Programming Technology © Er. Shiva Ram Dam, 2019 77


5. WEB AND DATABASE PROGRAMMING WITH .NET

2. Command Class
The Command class allows us to execute any type of SQL statement.
Although we can use a Command class to perform data definition tasks (such as creating and
altering databases, tables, and indexes), we’re much more likely to perform data manipulation
tasks (such as retrieving and updating the records in a table).

Command Basics
Before we can use a command, we need to:
• choose the command type,
• set the command text, and
• bind the command to a connection.
We can perform this work by setting the corresponding properties (CommandType, CommandText,
and Connection), or we can pass the information we need as constructor arguments.
The command text can be a SQL statement, a stored procedure, or the name of a table. It all depends
on the type of command we’re using. Three types of commands exist.

Table: Values for the Command Type Enumeration


Example:
Here is how we would create a Command object that represents a query.

SqlCommand cmd = new SqlCommand();


cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM info";

CommandType.Text is the default. So we may not specify it, and write the above code simply as:

SqlCommand cmd = new SqlCommand("Select * from info", con);

Alternatively, to use stored procedure:

SqlCommand cmd = new SqlCommand("Select * from info", con);


cmd.CommandType = System.Data.CommandType.StoredProcedure;

78 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

These examples simply define a Command object; they don’t actually execute it. The Command
object provides three methods that we can use to perform the command, depending on whether we
want to retrieve a full result set, retrieve a single value, or just execute a non-query command.

Table: Command Methods

3. Data Reader Class


DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results
from the Data Source, which do not update the data. A DataReader allows us to read the data
returned by a SELECT command one record at a time, in a forward-only, read-only stream. This is
sometimes called a firehose cursor. Using a DataReader is the simplest way to get to our data, but it
lacks the sorting and relational abilities of the disconnected DataSet.

4. Data Adapter Class


The DataAdapters are bridges between data sets and data sources. The DataAdapters take care
of all connection details for the data set, populates it with data, and updates the data source.
The DataReader uses the Connection object to access the data directly, without having to use a
DataAdapter. The DataSet requires DataAdapter to access and update the actual source of the data.

Figure: Dataset, data adapter, and data source interaction (scheme)

Programming Technology © Er. Shiva Ram Dam, 2019 79


5. WEB AND DATABASE PROGRAMMING WITH .NET

Fundamental ADO.net classes


ADO.NET has two types of objects: connection-based and content-based.
1. Connection-based objects:
• These are the data provider objects such as Connection, Command, DataReader, and
DataAdapter.
• They allow us to connect to a database, execute SQL statements, move through a read-only
result set, and fill a DataSet.

2. Content-based objects:
• These objects are really just “packages” for data.
• They include the DataSet, DataColumn, DataRow, DataRelation, and several others .
• They are completely independent of the type of data source and are found in the System.Data
namespace.

Table: The ADO.NET Namespace

5.9. Database Access without ADO.NET


In ASP.NET, there are a few ways to get information out of a database without directly using the
ADO.NET classes. Depending on our needs, we may be able to use one or more of these approaches
to supplement your database code (or to avoid writing it altogether). The options for database access
without ADO.NET include the following:

1. The SqlDataSource control:


The SqlDataSource control allows us to define queries declaratively. We can connect the
SqlDataSource to rich controls such as the GridView, and give our pages the ability to edit
and update data without requiring any ADO.NET code.

80 Programming Technology © Er. Shiva Ram Dam, 2019


5. WEB AND DATABASE PROGRAMMING WITH .NET

2. LINQ to Entities:
With LINQ to Entities, we define a query using C# code (or the LinqDataSource control) and
the appropriate database logic is generated automatically. LINQ to Entities supports updates,
generates secure and well-written SQL statements, and provides some customizability. LINQ
to Entities is the successor of LINQ to SQL. Unlike the SqlDataSource control, LINQ to SQL
only works with SQL Server and is completely independent of ADO.NET
3. Profiles:
The profiles feature allows you to store user-specific blocks of data in a database without
writing ADO.NET code.

Sample Program 1:
A database dbBook has a table called tbBookInfo having attributes bookId, bookname, authorname,
publisher and price. Using ADO.net and ASP.net, WAP to read all the records from the table and
display them.
//Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace Data_Connection_Teaching
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "Data Source=localhost; database=dbBook; integrated
security=SSPI";
SqlConnection con = new SqlConnection(cs);

try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbBookInfo", con);
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();

}
catch
{
Console.WriteLine("Error");
}
finally
{
con.Close();
}
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)


{

}
}
}
Refer: https://www.guru99.com/insert-update-delete-asp-net.html
Programming Technology © Er. Shiva Ram Dam, 2019 81
5. WEB AND DATABASE PROGRAMMING WITH .NET

Exam Questions:
1. Is it necessary to create the connection string while connecting to database from .NET
applications? Why/why not? Write a simple asp.net program in order to demonstrate the
connectivity to the database server. (Consider Database name=Authors, Username=root and
Password=BeCe_PT). [2018 spring]
2. Discuss the steps involved in connecting to a SQL database using asp.net. [2018 fall]
3. What package is used to connect database with .net? Explain the syntax of the connection
mechanism. [2017 fall]
4. Describe the steps involved in establishing database connectivity in asp.net with code snippets.
[2017 spring]
5. How to make database connectivity in asp.net? Explain with example. [2016 fall]
6. What is ASP.net? Describe about ASP.net page life cycle. [2016 spring]
7. A database dbBook has a table called tbBookInfo having attributes bookId, bookname,
authorname, publisher and price. Using ADO.net and ASP.net, WAP to read all the records from
the table and display them. [2015 spring]
8. What is ASP? WAP to display data from database with ASP. [2015 fall]
9. What is dynamic web programming? Make comparison between ASP and ASP.net. [2014 spring]
10. What is server control in ASP.net? Explain ASP.net page life cycle. [2013 spring]
11. Write short notes on:
a. ASP.net [2015 fall]

82 Programming Technology © Er. Shiva Ram Dam, 2019


6. JAVA FRAMEWORK

Chapter 6: Java Framework [Credit: 2 hrs]

Introduction to Java language


Java programming language was originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995 as core component of Sun Microsystems’ (currently a subsidiary
of Oracle Corporation)' Java platform. The goal was to provide a simpler and platform-independent
alternative to C++.
Java is one of the most popular and widely used programming language and platform. A platform is an
environment that helps to develop and run programs written in any programming language.
Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to
gaming consoles, cell phones to the Internet, Java is used in every nook and corner.

Java Environment
The programming environment of Java consists of three components mainly:
1. JDK
2. JRE
3. JVM

6.1. Java Development Kit (JDK)


JDK (Java Development Kit) is a software development kit to develop applications in Java. When
we download JDK, JRE is also downloaded, and don't need to download it separately. In addition
to JRE, JDK also contains number of development tools (compilers, JavaDoc, Java Debugger etc).

• Java Developer Kit contains tools that are needed to develop the Java programs, and JRE
to run the programs.
• The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer,
etc. Compiler converts java code into byte code.
• Java application launcher opens a JRE, loads the class, and invokes its main method.
• We need JDK, if at all we want to write our own programs, and to compile the program.
• For running java programs, JRE is sufficient.
• JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes (like util,
math, lang, awt,swing etc)+runtime libraries.
• JDK is mainly targeted for java development. i.e. we can create a Java file (with the help of
Java packages), compile a Java file and run a java file.

Programming Technology © Er. Shiva Ram Dam, 2019 83


6. JAVA FRAMEWORK

6.2. Java Runtime Environment (JRE)


JRE (Java Runtime Environment) is a software package that contains Java class libraries, JVM,
and other supporting files. It does not contain any development tools such as compiler, debugger,
etc. JRE is needed to run applications written in Java programming. JRE is the superset of JVM. If
we want to run any java program, we need to have JRE installed in the system.

6.3. Java Virtual Machine (JVM)


JVM (Java Virtual Machine) is an abstract machine that enables our computer to run a Java
program.
When we run the Java program, Java compiler first compiles your Java code to bytecode. Then,
the JVM translates bytecode into native machine code (set of instructions that a computer's CPU
executes directly).
Java is a platform-independent language. It's because when we write Java code, it's ultimately
written for JVM but not our physical machine (computer). Since JVM executes the Java bytecode,
which is platform independent, Java is platform-independent.

The Java Virtual Machine provides a platform-independent way of executing code; programmers
can concentrate on writing software, without having to be concerned with how or where it will run.
But, note that JVM itself not a platform independent. It only helps Java to be executed on the
platform-independent way. When JVM has to interpret the byte codes to machine language, then it
has to use some native or operating system specific language to interact with the system. One has
to be very clear on platform independent concept. Even there are many JVMs written on Java,
however they too have little bit of code specific to the operating systems.
As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file
consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the
byte code into the machine code depending upon the underlying operating system and hardware
combination. It is responsible for all the things like garbage collection, array bounds checking,
etc.JVM is platform dependent.
The JVM is called “virtual” because it provides a machine interface that does not depend on the
underlying operating system and machine hardware architecture. This independence from
hardware and operating system is a cornerstone of the write-once run-anywhere value of Java
programs.
There are different JVM implementations are there. These may differ in things like performance,
reliability, speed, etc. These implementations will differ in those areas where Java specification
doesn’t mention how to implement the features, like how the garbage collection process works is
JVM dependent, Java spec doesn’t define any specific way to do this.

Figure: Relationship between JVM, JRE, and JDK

84 Programming Technology © Er. Shiva Ram Dam, 2019


6. JAVA FRAMEWORK

Difference between JRE, JDK and JVM


In short here are few differences between JRE, JDK and JVM:
1. JRE and JDK come as installer while JVM are bundled with them.
2. JRE only contain environment to execute java program but doesn’t contain other tool for
compiling java program.
3. JVM comes along with both JDK and JRE and created when we execute Java program by
giving “java” command.

Just in Time Compiler (JIT)


Initially Java has been accused of poor performance because it both compiles and interprets
instruction. Since compilation or Java file to class file is independent of execution of Java program.
Here compilation word is used for byte code to machine instruction translation.
JIT are advanced part of Java Virtual machine which optimize byte code to machine instruction
conversion part by compiling similar byte codes at same time and thus reducing overall execution
time. JIT is part of Java Virtual Machine and also performs several other optimizations such as in-
lining function.

Some Basic Java Console Programs:


1. WAP in Java to print “Hello World”.
class Hello{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

➔ The first line defines a class called Hello. If this class is declared public, any other classes
can access it.
➔ The second line is the entry point of our Java program.
• Public means any one can access it.
• Static means this method can be run without creating an instance of Hello class.
• void means no return value.
• main() is the method name.
➔ The third line is a print statement. System is a predefined class. out is a static variable for
stdout. println is a method to print a line.

2. WAP in Java to enter an integer, floating number and a string from user and display them.

import java.util.Scanner;

class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;

Scanner in = new Scanner(System.in);

Programming Technology © Er. Shiva Ram Dam, 2019 85


6. JAVA FRAMEWORK

System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer "+a);

System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float "+b);

System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string "+s);
}
}

3. WAP in Java to implement class object concept. Also make use of constructors.

public class Student {


int roll,age;

Student(){ //parameterless constructor


roll=5;
age=25;
}

Student(int x,int y){ //parameterized constructor


roll=x;
age=y;
}

void display(){
System.out.println("Roll No:" + roll+ " " +"Age: "+age);
}

public static void main(String args[]){


Student ob1=new Student();
ob1.display();
Student ob2=new Student(10,20);
ob2.display();
}
}

Exam questions:
1. What is JRE? Why do you need JRE? Explain in brief. [2017 fall]
2. Explain why JAVA is called a platform independent language? [2016 fall, 2016 fall]
3. Discuss the architecture of JVM and its component using suitable diagrams. [2017 spring]
4. Verify the statement “JVM is a platform independent engine”. [2016 spring,2013 spring]
5. Explain briefly the JDK, JVM and JRE. [2015 spring]
6. What is java class file? How does java attain platform independence? [2015 fall]
7. Write short notes on:
a. JDK,JVM and JRE [2018 spring]
b. Differentiate between JDK and JRE [2018 fall]
c. JVM and JRE [2014 spring, fall]

86 Programming Technology © Er. Shiva Ram Dam, 2019


7. JAVA EXCEPTION HANDLING

Chapter 7: Java Exception Handling [Credit: 3 hrs]

7.1. Exception
An exception (or exceptional event) is a problem that arises during the execution of a program. An
exception is an abnormal condition that arises in a code sequence at run time. When
an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out
of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

Types of Exceptions (Exception Hierarchy)


All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.
One branch is headed by Exception. This class is used for exceptional conditions that user programs
should catch. NullPointerException is an example of such an exception. Another branch, Error are
used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment
itself(JRE). StackOverflowError is an example of such an error.

1. Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible
to anticipate and recover from them, for example hardware failure, JVM crash or out of memory
error. That’s why we have a separate hierarchy of errors and we should not try to handle these
situations. Some of the common Errors are OutOfMemoryError and StackOverflowError.
2. Checked Exceptions: Checked Exceptions are exceptional scenarios that we can anticipate in a
program and try to recover from it, for example FileNotFoundException. We should catch this
exception and provide useful message to user and log it properly for debugging purpose.
Exception is the parent class of all Checked Exceptions and if we are throwing a checked
exception, we must catch it in the same method or we have to propagate it to the caller using
throws keyword.
3. Runtime Exception: Runtime Exceptions are cause by bad programming, for example trying to
retrieve an element from the Array. We should check the length of array first before trying to
retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime.
Programming Technology © Er. Shiva Ram Dam, 2019 75
7. JAVA EXCEPTION HANDLING

Runtime Exception is the parent class of all runtime exceptions. If we are throwing any runtime
exception in a method, it’s not required to specify them in the method signature throws clause.
Runtime exceptions can be avoided with better programming.

Error Vs Exception:
Both Error and Exception are derived from java.lang.Throwable in Java but main difference between
Error and Exception is kind of error they represent. java.lang.Error represent errors which are
generally cannot be handled and usually refer catastrophic failure e.g. running out of System
resources, some examples of Error in Java are java.lang.OutOfMemoryError or
Java.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError. On the other hand
java.lang.Exception represent errors which can be catch and dealt e.g. IOException which comes
while performing I/O operations i.e. reading files and directories.

Checked Vs Unchecked Exception


A checked exception is an exception that is checked (notified) by the compiler at compilation-time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored, the
programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file specified
in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
Example:

import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}

If you try to compile the above program, you will get the following exceptions.
Output:

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException;
must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

An unchecked exception is an exception that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an
API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6 th element
of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Example: Live Demo

public class Unchecked_Demo {


public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

76 Programming Technology © Er. Shiva Ram Dam, 2019


7. JAVA EXCEPTION HANDLING

If you compile and execute the above program, you will get the following exception.
Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5


at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Basic difference between Checked and Unchecked Exceptions


1. Checked Exception
The classes which directly inherit 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
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.

finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.

7.2. Handling error and exception, Catching exception


Java Exception Handling Example
Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.

// File Name : ExcepTest.java


import java.util.Scanner;

public class ExcepTest {

public static void main(String args[]) {


int a,b, q;
Scanner input= new Scanner(System.in);

Programming Technology © Er. Shiva Ram Dam, 2019 77


7. JAVA EXCEPTION HANDLING

System.out.println("enter two numbers");


a=input.nextInt();
b=input.nextInt();
//try block
try {
q=a/b;
System.out.println("Result="+q);
}
//catch block
catch(ArithmeticException e) {
System.out.println("Exception caught: division by zero");
}
}
}

At Runtime:
When we enter two numbers 10 and 5, output is as:

When we enter two numbers 10 and 0, output is as:

The finally keyword

When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters
the normal flow through the method.
finally creates a block of code that will be executed after a try/catch block has completed and before
the code following the try/catch block. The finally block will execute whether or not an exception is
thrown. The use of finally is optional.This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the beginning of a method.
import java.*;;
public class ExcepTest {
public static void main(String args[]) {
int a[]= {2,3,4};
//try block
try {
System.out.println("Array element three= "+a[3]);
}
//catch block
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown:"+e);
}
//finally block
finally{
a[0]=6;
System.out.println("First Element value: "+ a[0]);
System.out.println("Finally block executed");
}
}
}
Output:

78 Programming Technology © Er. Shiva Ram Dam, 2019


7. JAVA EXCEPTION HANDLING

The throw keyword:


The throw keyword in Java is used to explicitly throw an exception from a method or any block of
code. We can throw either checked or unchecked exception. The throw keyword is mainly used to
throw custom exceptions.

Syntax:
throw Instance

Example:
throw new ArithmeticException("/ by zero");

The flow of execution of the program stops immediately after the throw statement is executed and the
nearest enclosing try block is checked to see if it has a catch statement that matches the type of
exception. If it finds a match, control is transferred to that statement otherwise next enclosing try block
is checked and so on. If no matching catch is found, then the default exception handler will halt the
program.

Sample program 1:
import java.*;;
public class ExcepTest {
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid age");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(12);
}
catch (ArithmeticException e){
System.out.println(e);
}
}
}

Output:

Refer: https://www.youtube.com/watch?v=j9M69wdEU-0

The throws keyword:


Throws keyword is used to declare the exception. It provides information to the programmer that there
might occur an exception. So, during the call of that method, programmer must use exception
handling mechanism.

Programming Technology © Er. Shiva Ram Dam, 2019 79


7. JAVA EXCEPTION HANDLING

Sample progam:

import java.*;;
public class ExcepTest {
static void validate(int age) throws ArithmeticException
{
if(age<18)
throw new ArithmeticException("not valid age");
else
System.out.println("welcome to vote");

public static void main(String args[])


{
try
{
validate(16);
}
catch(ArithmeticException e)
{
System.out.println("caught in main."+e);
}
}
}

Output:

Refer: https://www.youtube.com/watch?v=nsJvdOrjBRA

Difference between throw and throws in Java


There are many differences between throw and throws keywords. A list of differences between throw
and throws are given below:

No. throw throws

1) Java throw keyword is used to Java throws keyword is used to declare an


explicitly throw an exception. exception.

2) Checked exception cannot be Checked exception can be propagated with


propagated using throw only. throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method() throws IOException,
SQLException.

User-Defined Exception
Java provides us facility to create our own exceptions which are basically derived classes
of Exception. For example MyException in below code extends the Exception class.
We pass the string to the constructor of the super class- Exception which is obtained using
“getMessage()” function on the object created.

80 Programming Technology © Er. Shiva Ram Dam, 2019


7. JAVA EXCEPTION HANDLING

// A Class that represents user-defined exception


class MyException extends Exception
{
public MyException(String s)
{
super(s); // Call constructor of parent Exception

}
}

// A Class that uses above MyException


public class Main
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("Exception here");
}
catch (MyException ex)
{
System.out.println("Caught:");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}
}

Output:
Caught:
Exception here

Throwable In Java :
Throwable is a super class for all types of errors and exceptions in java. This class is a member
of java.lang package. Only instances of this class or it’s sub classes are thrown by the java virtual
machine or by the throw statement. The only argument of catch block must be of this type or it’s sub
classes. If you want to create your own customized exceptions, then your class must extend this
class.
Below example shows how to use throwable.
import java.lang.Throwable;
public class ThrowableExample {
public static void main(String args[]) throws
ArithmeticException
{
ThrowableExample ob=new ThrowableExample();
ob.sum();
System.out.println("Message printed after exception
handled");
}

public void sum() //throws ArithmeticException


{
try
{
int i=90/0; //exception line
}

Programming Technology © Er. Shiva Ram Dam, 2019 81


7. JAVA EXCEPTION HANDLING

catch(Throwable e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}

List of some Built-in Exceptions


Built-in Exceptions Description
It is thrown when an exceptional condition has occurred in
ArithmeticException
an arithmetic operation.
It is thrown to indicate that an array has been accessed
ArrayIndexOutOfBoundsException with an illegal index. The index is either negative or greater
than or equal to the size of the array.
This exception is raised when we try to access a class
ClassNotFoundException
whose definition is not found.
An exception that is raised when a file is not accessible or
FileNotFoundException
does not open.
It is thrown when an input-output operation is failed or
IOException
interrupted.
It is thrown when a thread is waiting, sleeping, or doing
InterruptedException
some processing, and it is interrupted.
It is thrown when a class does not contain the field (or
NoSuchFieldException
variable) specified.

7.3. Tips on handling exception


Exceptions are useful but easily misused and abused. Here are a few tips and best practices to help
you avoid making a mess of them.
1. Prefer specific exceptions to general exceptions.
2. Never catch Throwable
3. Document Exception
Refer:
4. Use descriptive messages to ease debugging.
https://www.makeuseof.com/tag/handle-java-
5. Try not to catch and ignore exceptions. exceptions-right-way/

https://stackify.com/best-practices-exceptions-java/
6. Beware of overusing exceptions.

7.4. Debugging techniques


Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a
computer program.
1. Use of print statement:
These statements are strategically placed to show the flow of control and the values of key
variables. The output produced may make the problem obvious or to be used to successively
narrow down the problem location.
2. Tracing Variables

82 Programming Technology © Er. Shiva Ram Dam, 2019


7. JAVA EXCEPTION HANDLING

One good way to discover errors in a loop or any kind of code is to trace some key variables.
Tracing variables means watching the variables change value while the program is running. Most
programs do not output each variable’s value every time the variable changes, but being able to
see all of these variable changes can help us to debug your program.
3. Use of Java Debugger:
It is a simple command-line debugger for Java classes. The Java Debugger API allows us to
actually peek into the runtime and debug our code. The jdb is just one implementation of a
debugger that uses the API.
4. Loop Bug
The two most common kinds of loop errors are unintended infinite loops and off-by-one errors.
Infinite loops are never stopping.
Infinite Loop: A while loop, do-while loop, or for loop does not terminate as long as the controlling
Boolean expression evaluates to true. This Boolean expression normally contains a variable that
will be changed by the loop body, and usually the value of this variable eventually is changed in a
way that makes the Boolean expression false and therefore terminates the loop. However, if we
make a mistake and write our program so that the Boolean expression is always true, then the
loop will run forever. A loop that runs forever is called an infinite loop.
off-by-one error: The loop repeats the loop body one too many or one too few times. These sorts
of errors can result from carelessness in designing a controlling Boolean expression. For
example, if we use less-than when we should use less-than-or-equal, this can easily make our
loop iterate the body the wrong number of times. Use of == to test for equality in the controlling
Boolean expression of a loop can often lead to an offby-one error or an infinite loop. This sort of
equality testing can work satisfactorily for integers and characters, but is not reliable for floating-
point numbers. This is because the floating-point numbers are approximate quantities, and ==
tests for exact equality. The result of such a test is unpredictable. When comparing floating-point
numbers, always use something involving less-than or greater-than, such as <= ; do not use == or
!= . Using == or != to test floating-point numbers can produce an off-by-one error or an unintended
infinite loop or even some other type of error. Even when using integer variables, it is best to avoid
using == and != and to instead use something involving less-than or greater-than.
5. General Debugging Techniques
Tracing errors can sometimes be a difficult and time-consuming task. It is not uncommon to spend
more time debugging a piece of code than it took to write the code in the first place. If we are
having difficulties finding the source of our errors, then there are some general debugging
techniques to consider. If the program is giving incorrect output values, then we should examine
the source code, different test cases using a range of input and output values, and the logic
behind the algorithm itself.
Determining the precise cause and location of a bug is one of the first steps in fixing the error.
Examine the input and output behavior for different test cases to try to localize the error. A related
technique is to trace variables to show what code the program is executing and what values are
contained in key variables. We might also focus on code that has recently changed or code that
has had errors before.
Finally, we can also try removing code. If we comment out blocks of code and the error still
remains, then the culprit is in the uncommented code. The process can be repeated until the
location of the error can be pinpointed. The /* and */ notation is particularly useful to comment out
large blocks of code.
After the error has been fixed, it is easy to remove the comments and reactivate the code. The first
mistakes we should look for are common errors that are easy to make. Examples of common
errors include off-by-one errors, comparing floating-point types with == , adding extra semicolons
that terminate a loop early, or using == to compare strings for equality.

Programming Technology © Er. Shiva Ram Dam, 2019 83


7. JAVA EXCEPTION HANDLING

7.5. Stream, Zip file stream, Object stream and Handling files
In Java, a stream is a path along which the data flows. Every stream has a source and a destination.
We can build a complex file processing sequence using a series of simple stream operations. Two
fundamental types of streams are Reading stream and and Writing stream. A Reading stream is
used to read data from a source(file) , where as a Writing streams writes data into a source(file).

Source Program
data

Program Destination
data
Figure: Reading and Writing stream

Stream classes in java


The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes may be categorized into two groups based on the data
type on which they operate.
• Byte stream classes
Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Java provides two kinds of byte
stream classes: input stream classes and output stream classes.
• Character stream classes
Character streams can be used to read and write 16-bit Unicode characters. Like byte
streams, there are two kinds of character stream classes, namely, reader stream
classes and writer stream classes.

Zip file Stream:


Zip files are the archives that store one or more files in compressed form. The java.util.zip contains the
classes for working with zip files. Each zip file has a header which includes information like name of
the file and the compression method used like GZIP and ZIP. ZipInputStream() is used to read a Zip
file. We then need to look at the individual entries in the archive. The getNextEntry() method returns
an object of type ZipEntry that describes the entry. The read method of the ZipInputStream is modified
to return -1 at the end of the current entry.

Object Stream:
Object streams support I/O of objects. Object Stream is useful while reading and writing objects that
are created using different data types. And this is done by the process, Object Serialization
mechanism.

Sample programs on File Handling:


Example 1: Creating a new file myfile.txt in drive D: and writing into it.
The createNewFile() method is used to create a new file named by the abstract path name.
Sample Program:
import java.io.*;
public class Test
{
public static void main(String args[ ])
{

84 Programming Technology © Er. Shiva Ram Dam, 2019


7. JAVA EXCEPTION HANDLING

try
{
// Create File
File f = new File ( "D:\\myfile.txt");
if (f.createNewFile()==true)
{
System.out.println("File created.");

//Write Content
FileWriter w= new FileWriter(f);
w.write(" This is Test Data.");
w.close();
System.out.println("Data Written.");
}
else
System.out.println("File already exists");
}

catch (IOException e)
{
e.printStackTrace();
}
}
}

Example 2: Writing into an existing file

In Java, you can use FileWriter(file,true) to append new content to the end of a file.
1. All existing content will be overridden.

new FileWriter(“file”);

2. Keep the existing content and append the new content to the end of a file.

new FileWriter(“file”,true);

Sample Program:
import java.io.*;
public class Test
{
public static void main(String args[ ])
{
try
{
FileWriter w = new FileWriter ("D:\\myfile.txt");
//for appending …..("D:\\myfile.txt", true);
String content = "I Love Nepal";
w.write (content);
w.close();
System.out.println("Data Overwritten");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 85


7. JAVA EXCEPTION HANDLING

Example 3. Reading from existing file


In Java, we can use FileReader("File") to read the content of an existing file. The
BufferedReader()can be used to buffer the output stream.
Sample Program:
import java.io.BufferedReader;
import java.io.FileReader;
public class Test
{
public static void main(String args[ ])
{
try
{
FileReader f= new FileReader("D:\\myfile.txt");
BufferedReader br= new BufferedReader(f);
String data;
while((data = br.readLine()) != null)
{
System.out.println(data);
}
f.close();
}
catch (Exception e)
{
System.out.println("Error");
}
}
}

7.6. Exam Questions:


1. Differentiate error with exception. WAP to demonstrate the concepts user defined exception in
Java. [2018 spring]
2. What is checked and unchecked exception in Java? WAP to create your own exception class in
Java. [2018 fall]
3. What is exception handling? Illustrate with an example how exceptions are handled in a Java
program. [2017 fall]
4. Define error and exception in Java. What are the differences between throw, throws and
throwable in Java? [2017 spring]
http://www.xyzws.com/javafaq/what-are-differences-among-throw-throws-and-throwable/79
https://javaconceptoftheday.com/difference-between-throw-throws-and-throwable-in-java/
5. Define exception in Java. How it is handled? Explain with example. [2016 fall, spring]
6. Differentiate between throw and throws with suitable example (in java exception handling) [2015
fall]
7. Explain different streams used in Java. Write a java program to read a file called “Employee.txt”
and display it in console. [2015 spring]
8. What do you mean by user defined exceptions? WAP in Java to read a text file and display in
console. [2014 fall]
9. Define exception in Java. How it is handled? Explain with example. [2016 fall]
10. What is the difference between error and exception? Write a sample program which illustrates
“try”, “catch” and “finally” for exception handling in Java. [2013 spring]

86 Programming Technology © Er. Shiva Ram Dam, 2019


8. APPLETS AND APPLICATION

Chapter 8: Applets and Application [Credit: 3 hrs]

8.1. Fundamental concept of applet


Applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. After an applet arrives on the client, it has limited access to resources so that it
can produce a graphical user interface and run complex computations without introducing the risk of
viruses or breaching data integrity. Applets differ from console-based applications in several key
areas. Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted on a web
server.
Applets are used to make the web site more dynamic and entertaining.

Characteristics of Applet
1. Applets are small Java applications that can be accessed on an Internet server, transported over
Internet, and can be automatically installed and run as apart of a web document.
2. After a user receives an applet, the applet can produce a graphical user interface. It has limited
access to resources so that it can run complex computations without introducing the risk of viruses
or breaching data integrity.
3. Any applet in Java is a class that extends the java.applet.Applet class.
4. An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.
5. JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it. Hence, platform independent
3. Execution of applets is easy in a Web browser and does not require any installation or deployment
procedure in real-time programming (where as servlets require).
4. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
5. In GUI development, constructor, size of frame, window closing code etc. are not required (but
are required in applications).
Disadvantages:
1. Requires java plug-in

Two Types of Applet


There are two varieties of applets.
1. The first type of applets uses the Abstract Window Toolkit (AWT) to provide the graphic user
interface (or use no GUI at all). This style of applet has been available since Java was first
created.
2. The second type of applets is those based on the Swing class JApplet. Swing applets use the
Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface
than does the AWT. Thus, Swing-based applets are now the most popular. However, traditional
AWT-based applets are still used, especially when only a very simple user interface is required.
Thus, both AWT- and Swing-based applets are valid. Because JApplet inherits Applet, all the features
of Applet are also available in JApplet.

Programming Technology © Er. Shiva Ram Dam, 2019 99


8. APPLETS AND APPLICATION •

8.2. Simple applet and Applet & Applications

A Simple Java “Hello World” Applet

import java.awt.Graphics;
import java.applet.Applet;
public class Hello extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Hello World”,25,20);
}
}

1. This applet begins with two import statements. The first imports the Abstract Window Toolkit
(AWT) classes. Applets interact with the user (either directly or indirectly) through the AWT,
not through the console-based I/O classes. The AWT contains support for a window-based,
graphical user interface.

2. The second import statement imports the applet package, which contains the class Applet.
Every applet that we create must be a subclass of Applet.

3. The next line in the program declares the class Hello. This class must be declared as public,
because it will be accessed by code that is outside the program.

4. Inside Hello class, paint( ) is declared. This method is defined by the AWT and must be
overridden by the applet. paint( ) is called each time that the applet must redisplay its output.
This situation can occur for several reasons. For example, the window in which the applet is
running can be overwritten by another window and then uncovered. Or, the applet window can
be minimized and then restored. paint( ) is also called when the applet begins execution.
Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint()
method has one parameter of type Graphics. This parameter contains the graphics context,
which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required.

5. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method
outputs a string beginning at the specified X,Y location. It has the following general form:

void drawString(String message, int x, int y)

6. Here, message is the string to be output beginning at x,y. In a Java window, the upper-left
corner is location 0,0. The call to drawString( ) in the applet causes the message “Hello
World” to be displayed beginning at location 20,20.

7. Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not
begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an

100 Programming Technology © Er. Shiva Ram Dam, 2019


8. APPLETS AND APPLICATION

applet begins execution when the name of its class is passed to an applet viewer or to a
network browser.

8. After we enter the source code for Hello, compile in the same way that we have been
compiling programs. However, running Hello involves a different process. In fact, there are
two ways in which you can run an applet:

• Executing the applet within a Java-compatible web browser.

• Using an applet viewer,

Viewing the Applet:


Save the above code as Hello.java and compile it. To compile: Go to command prompt >type javac
Hello.java and press enter. You will get a class file Hello.class
Then create a html file and save it as Test.html and run it.
<html>
<body bgcolor = “yellow”>
<applet code= “Hello.class” width= “100” height = “200” >
</applet>
</body>
</html>

In commamd prompt;
C:\> appletviewer Test.html
We will get a view of applet.

Applet life cycle

1. New Born State


The life cycle of an applet begins when the applet is first loaded into browser and called the init( )
method. At this stage, new objects to the applet are created, initial values are set, images are
loaded and the colors of the images are set. An applet is initialized only once in its lifetime.
Its general form is:
Programming Technology © Er. Shiva Ram Dam, 2019 101
8. APPLETS AND APPLICATION •

public void init( )


{
//action to be performed
}

2. Running State
An Applet achieves the running state when the system calls the start( ) method. This occurs as
soon as the Applet is initialized.
General form is:
public void start( )
{
//action to be performed
}
3. Idle State
An Applet comes in Idle state when its execution has been stopped either implicitly or explicitly.
An Applet is implicitly stopped when we leave the page containing the current applets. An Applet
is explicitly stopped when we call stop( ) method to stop its execution.
General form is:
public void stop( )
{
//action to be performed
}

4. Dead state
An Applet is in dead state when it has been removed from the memory. This can be done using
destroy( ) method.
General form is:
public void destroy( )
{
//action to be performed
}

Apart from the above stages, Java Applet also possess paint( ) method. This method helps in drawing,
writing and creating colored backgrounds of the applet. It takes an argument of the graphic class. To
use the graphics, it imports the package.awt.Graphics.

102 Programming Technology © Er. Shiva Ram Dam, 2019


8. APPLETS AND APPLICATION

Methods used in Applet Life Cycle

An Applet Skeleton
Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are
defined by Applet. Default implementations for all of these methods are provided below:

Programming Technology © Er. Shiva Ram Dam, 2019 103


8. APPLETS AND APPLICATION •

The Applet classes


The Applet class defines the methods shown in following table. Applet provides all necessary support
for applet execution, such as starting and stopping. It also provides methods that load and display
images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn,
Panel extends Container, which extends Component. These classes provide support for Java’s
window-based, graphical interface. Thus, Applet provides all of the necessary support for window
based activities.

Converting Java Applet to Application and vice-versa


1. Converting a java application into java applet
The basic steps to follow to convert an application program into an applet program are:
1. Make a HTML page with appropriate tag to load the applet code.
2. Supply a subclass of Applet or Japplet class. Make this class public.
3. Eliminate the main() method.
4. Override the init() method to initialize your applet’s resources the same way the main()
method initializes the applicant’s resources. init() might be called more than once and should
be designed accordingly.

104 Programming Technology © Er. Shiva Ram Dam, 2019


8. APPLETS AND APPLICATION

5. Remove the call to setsize as setting the size of the applet is done in the HTML code with the
WIDTH and HEIGHT parameters. Also, remove the call to setDefaultCloseOpertion and
setTitle which is not relevant for applets.
6. Since the applet is diaplayed automatically, do not call show() or setVisible(true).

2. Converting a java applet into java application


1. Supply a subclass of Frame
2. Eliminate the init() method and replace it with constructor or methods.
3. Introduce setsize() and setVisible() methods.
4. Introduce a main() method.

Refer: http://www.mathcs.emory.edu/~cheung/Courses/377/Syllabus/8JDBC/GUI/Applets/applet.html

Programming Technology © Er. Shiva Ram Dam, 2019 105


8. APPLETS AND APPLICATION •

Applet Vs Application
Features Application Applet
main() method Present Not present
Execution Requires JRE Requires a browser or applet viewer
Nature Called as stand-alone application as Requires some third party tool help
application can be executed from like a browser to execute
command prompt
Restrictions Can access any data or software cannot access any thing on the
available on the system system except browser’s services
Security Does not require any security Requires highest security for the
system as they are untrusted

The html APPLET tag


The APPLET tag is used to start an applet from both an HTML document and from an applet viewer.
An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers
will allow many applets on a single page.
The syntax for a fuller form of the APPLET tag is shown below; bracketed items are optional while
code, width and height attributes are required.

<APPLET
[CODEBASE= codebase URL]
[CODE= appletFile]
[ALT= alternate text]
[NAME=appletInstanceName]
[WIDTH=pixels]
[HEIGHT=pixels]
[ALIGN=alignment]
[VSPACE= pixels]
[HSPACE=pixels] >

[<PARAM NAME= AttributeName VALUE =Attribute Value>]


[<PARAM NAME= AttributeName2 VALUE =Attribute Value >]
……………..
[HTML displayed in the absence of Java]
</APPLET>
Table below shows the different attributes of APPLET tag and their purposes:

S.NO. Attributes of Description


APPLET tag
1. CODEBASE • It species the base URL of the applet code, which is the directory

106 Programming Technology © Er. Shiva Ram Dam, 2019


8. APPLETS AND APPLICATION

that will be searched for the applet’s executable class file.


• It is optional.
2. CODE • It is a required attribute that gives the name of the file containing
applet’s compiled .class file.
• This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by
CODEBASE if set.
3. ALT • It is used to specify a short text message that should be displayed if
the browser recognizes the APPLET tag but cannot currently run
Java applets.
• It is optional.
4. NAME • It is used to specify a name for the applet instance.
• Applet must be named in order for other applets on the same page
to find them by name and communicate with them.
• To obtain an applet by name, use getApplet(), which is defined by
the AppletContext interface.
5. WIDTH and • These are required attributes that give the size (in pixels) to the
HEIGHT applet display area.
6. ALIGN • It specifies the alignment of the applet.
• The values can be: LEFT, RIGHT, TOP, BOTTM, MIDDLE,
BASELINE, TEXTTOP, ABSMIDDLE and ABSBOTTOM.
• It is optional.
7. VSPACE and • VSPACE specifies the space, in pixels, above and below the applet.
HSPACE
• HSPACE specifies the space, in pixels, on each side of the applet.
• These are optional attributes.
8. PARAM NAME • PARAM tag allows us to specify applet-specific arguments in an
HTML page.
• Applets access their attributes with the getParameter() method.

8.3. Parameters to Applet


We can pass parameters to applets using the <param> tag and retrieving the values of parameters
using getParameter() method..
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value of the
parameter respectively. For example, the param tags for passing name and age parameters looks as
shown below:
<param name=”name” value=”Ramesh” />
<param name=”age” value=”25″ />
Now, these two parameters can be accessed in the applet program using the getParameter() method
of the Applet class.
String getParameter(String param-name)
Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:

Programming Technology © Er. Shiva Ram Dam, 2019 107


8. APPLETS AND APPLICATION •

Creating a java file as MyApplet.java


import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}

Creating a HTML file as applet.html


<html>
<body bgcolor = “yellow”>
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
</body>
</html>

In the command prompt, we create a class file and run the applet viewer by commanding as:

The output is obtained as:

108 Programming Technology © Er. Shiva Ram Dam, 2019


8. APPLETS AND APPLICATION

8.4. Applet architecture


An applet is a window-based program. As such, its architecture is different from the console-based
programs. First, applets are event driven. It is important to understand in a general way that the
eventdriven architecture impacts the design of an applet.
An applet resembles a set of interrupt service routines. Here is how the process works. An applet
waits until an event occurs. The run-time system notifies the applet about an event by calling an event
handler that has been provided by the applet. Once this happens, the applet must take appropriate
action and then quickly return. This is a crucial point. For the most part, applet should not enter a
“mode” of operation in which it maintains control for an extended period. Instead, it must perform
specific actions in response to events and then return control to the run-time system. In those
situations in which applet needs to perform a repetitive task on its own (for example, displaying a
scrolling message across its window), we must start an additional thread of execution.
Second, the user initiates interaction with an applet. These interactions are sent to the applet as
events to which the applet must respond. For example, when the user clicks the mouse inside the
applet’s window, a mouse-clicked event is generated. If the user presses a key while the applet’s
window has input focus, a keypress event is generated. Applets can contain various controls, such as
push buttons and check boxes.
When the user interacts with one of these controls, an event is generated.

8.5. Applet Security policies


Because applets are designed to be loaded from a remote site and then executed locally, security
becomes vital. If a user enables Java in the browser, the browser will download all the applet code on
the web page and execute it immediately. The user never gets a chance to confirm or to stop
individual applets from running. For this reason, applets (unlike applications) are restricted in what
they can do. The applet security manager throws a SecurityException whenever an applet attempts to
violate one of the access rules. The restricted execution environment for applets is often called the
“sandbox." Applets playing in the “sandbox” cannot alter the user's system or spy on it.
In particular, when running in the sandbox:
• Applets can never run any local executable program.
• Applets cannot communicate with any host other than the server from which they were
downloaded; that server is called the originating host. This rule is often called “applets can
only phone home.” This protects applet users from applets that might try to spy on intranet
resources.
• Applets cannot read from or write to the local computer's file system.
• Applets cannot find out any information about the local computer, except for the Java version
used, the name and version of the operating system, and the characters used to separate files
(for instance, / or \), paths (such as : or ;), and lines (such as \n or \r\n). In particular, applets
cannot find out the user's name, e-mail address, and so on.
• All windows that an applet pops up carry a warning message.

To allow for different levels of security under different situations, we can use signed applets. A signed
applet carries with it a certificate that indicates the identity of the signer. Cryptographic techniques
ensure that such a certificate cannot be forged. If we trust the signer, we can choose to give the applet
additional rights.
Programs from vendors that are known to be somewhat flaky can be given access to some, but not all,
privileges.
Unknown applets can be restricted to the sandbox.
To sum up, Java has three separate mechanisms for enforcing security:
1. Program code is interpreted by the Java Virtual Machine, not executed directly.

Programming Technology © Er. Shiva Ram Dam, 2019 109


8. APPLETS AND APPLICATION •

2. A security manager checks all sensitive operations in the Java runtime library.
3. Applets can be signed to identify their origin.

Swing Vs Applet

S.No. Swing Applet

1. Swing is light weight Component. Applet is heavy weight Component.

2. Swing have look and feel according to user Applet does not provide this facility.
view you can change look and feel using
UIManager.

3. Swing used for standalone Applications. Applet needs HTML code to run the Applet.
Swing have main() method to execute the
program.

4. Swing uses MVC Model view Controller. Applet does not.

5. Swing have its own Layout like most popular Applet uses AWT Layouts like flowlayout.
Box Layout.

6. Swings have some Thread rules. Applet doesn't have any rule.

7. To execute Swing, no need of any browser To execute Applet program, we need any one
browser like: Appletviewer, web browser.

Exam Questions:
1. What is applet? Explain about the applet life cycle. [2018 spring]
2. Explain applet architecture. How can you convert applet to application? Explain with suitable
example. [2018 fall]
3. Write a code to create a simple applet in Java. Describe the differences between applet and
application. [2017 fall]
4. What is applet? Explain the lifecycle of an applet and demonstrate the same using a simple
program. [2017 spring]
5. Explain about the lifecycle of Applet? Write a simple but meaning applet program. [2016 fall]
6. What is applet? Explain about Applet architecture and security. [2016 spring]
7. How can you convert a java application into java applet? Explain with an example code for both
applet and application. [2015 spring]
8. What are Applet security policies as compared to application? Give the suitable example to
access parameter value to applet application. [2015 fall]
9. Differentiate between java application and java applet. Write a java applet to display an image.
[2014 spring]
10. What are the parameters to applets? Also describe different applet security policies. [2014 Fall]
11. How does applet differ from applications? Explain the purposes of different attributes of Applet
tags. [2013 spring]
***

110 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

Chapter 9: Event, Handling Events & Swing [Credit: 5 hrs]


9.1. Basic of Event Handling
Event, in any programming language, specifies the external effects that happen and our application
behaves according to that event. For example, an application produce an output when a user inputs
some data, or the data received from the network or it may be something else. In Java when you
works with the AWT components like button, textbox, etc (except panel, label) generates an event.
This event is handled by the listener. Event listener listens the event generated on components and
performs the corresponding action.
Event handling is fundamental to Java programming because it is integral to the creation of applets
and other types of GUI-based programs. Applets are event-driven programs that use a graphical user
interface to interact with the user. Furthermore, any program that uses a graphical user interface, such
as a Java application written for Windows, is event driven. Thus, we cannot write these types of
programs without a solid command of event handling. Events are supported by a number of packages,
including java.util, java.awt, and java.awt.event.
There are several types of events, including those generated by the mouse, the keyboard, and various
GUI controls, such as a push button, scroll bar, or check box.

9.2. Event Handling Components


Java event handling may comprise the following four components:
1. Event Sources: An Event source is the object that generates the event. For Eg, if we click a
button, an ActionEvent object is generated.
Sources for generating an event may be the components. In Java, java.awt.Component
specifies the components that may or may not generate events. These components classes
are the subclass of the above class. These event sources may be the button, combobox,
textbox etc.

2. Event Classes : Event Classes in Java are the classes defined for almost all the components
that may generate events. These events classes are named by giving the specific name .For
the component source button, the event class is ActionEvent.
Following are the list of Event Classes :
o ActionEvent : Button, TextField, List, Menu
o WindowEvent : Frame
o ItemEvent : Checkbox, List
o AdjustmentEvent : Scrollbar
o MouseEvent : Mouse
o KeyEvent : Keyboard

3. Event Listeners : Event Listeners are the Java interfaces that provides various methods to use
in the implemented class. Listeners listens the event generated by a component. In Java,
almost all components have its own listener that handles the event generated by the
component. For example, there is a Listener named ActionListener that handles the events
generated from button, textField, list, menus.

4. Event Adapters : Event Adapters classes are abstract class that provides some methods used
for avoiding the heavy coding. Adapter class is defined for the listener that has more than one
abstract methods.

Programming Technology © Er. Shiva Ram Dam, 2019 111


9. EVENT, HANDLING EVENTS & SWING

9.3. The Delegation Event Model


The Delegation Event model is one of the many techniques used to handle events in GUI (Graphical
User Interface) programming languages. The modern approach to handling events is based on the
delegation event model, which defines standard and consistent mechanisms to generate and process
events.
Its concept is quite simple: a source generates an event and sends it to one or more listeners . In this
scheme, the listener simply waits until it receives an event. Once an event is received, the listener
processes the event and then returns.
In the delegation event model, listeners must register with a source in order to receive an event
notification. Hence, notifications are sent only to listeners that want to receive them.

The Delegation Event Model has following key participants as:


Source – The source is an object on which an event occurs and the Source is responsible for
providing information of the event which has occurred to it’s handler. Java provide it as with
classes for the source object.
Listener – It is also called as event handler. The Listener is responsible for generating a
response to an event. From the java implementation point of view the listener is an object too.
The Listener waits until it has received an event and once the event is received, the listener
process the event, and then returns the result.

Following are the Steps to Handle Events


1. Declare and instantiate the event sources (or components) as buttons, menus, choices etc.
2. Implement an interface (listener) for providing the event handler that responds to event source
activity.
3. Register this event handler with event source.
4. Add the event source with the container like frame, panel etc.

112 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

9.4. Event Classes


Java core consists of different event types defined in java.awt.events. Some of the Event Classes
and Interface are:

S. No. Event Classes Description Listener Interface

1. ActionEvent generated when button is pressed, ActionListener


menu-item is selected, list-item is
double clicked

2. MouseEvent generated when mouse is dragged, MouseListener


moved, clicked, pressed or released
and also when it enters or exit a
component

3. KeyEvent generated when input is received from KeyListener


keyboard

4. ItemEvent generated when check-box or list item ItemListener


is clicked

5. TextEvent generated when value of textArea or TextListener


textField is changed

6. MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

7. WindowEvent generated when window is activated, WindowListener


deactivated, de-iconified, iconified,
opened or closed

8. ComponentEvent generated when component is hidden, ComponentEventListener


moved, resized or set visible

9. ContainerEvent generated when component is added or ContainerListener


removed from container

10. AdjustmentEvent generated when scroll bar is AdjustmentListener


manipulated

11. FocusEvent generated when component gains or FocusListener


losses keyboard focus

For more detailed study, refer: https://www.brainkart.com/article/Event-Classes---Java_10637/

Programming Technology © Er. Shiva Ram Dam, 2019 113


9. EVENT, HANDLING EVENTS & SWING

9.5. Sources of Events


Following table lists some of the user interface components that can generate the events. In addition
to these graphical user interface elements, any class derived from Component, such as Applet, can
generate events. For example, we can receive key and mouse events from an applet.

Table: Sources of Events

9.6. Event Listener Interfaces


The delegation event model has two parts: sources and listeners. Listeners are created by
implementing one or more of the interfaces defined by the java.awt.event package. When an event
occurs, the event source invokes the appropriate method defined by the listener and provides an
event object as its argument. Below table lists commonly used listener interfaces and provides a brief
description of the methods that they define.

Table: Commonly Used Event Listener Interfaces

114 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

9.7. Mouse Event handling


Handling mouse event using the delegation event model is actually quite easy. Just follow these two
steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
Remember that a source may generate several types of events. Each event must be registered
separately. Also, an object may register to receive several types of events, but it must implement all of
the interfaces that are required to receive these events.
To handle mouse events, we must implement the MouseListener and the MouseMotionListener
interfaces.
Lets us consider the below code for Mouse event handling.
// Demonstrate the mouse event handlers.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Mouse extends JFrame implements MouseListener, MouseMotionListener
{
JLabel lbl;

Mouse() //constructor here


{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
addMouseListener(this);
addMouseMotionListener(this);
lbl=new JLabel();
lbl.setBounds(20,50,200,50);
add(lbl);
}

// Handle mouse clicked


public void mouseClicked(MouseEvent e)
{
lbl.setText("Mouse Clicked " );
}

// Handle mouse entered.


public void mouseEntered(MouseEvent e)
{
lbl.setText("Mouse Entered");
}

// Handle mouse exited.


public void mouseExited(MouseEvent e)
{
lbl.setText("Mouse Exited");
}

// Handle mouse pressed.


public void mousePressed(MouseEvent e)
{
lbl.setText("Mouse Pressed");
}

// Handle mouse released.

Programming Technology © Er. Shiva Ram Dam, 2019 115


9. EVENT, HANDLING EVENTS & SWING

public void mouseReleased(MouseEvent e)


{
lbl.setText("Mouse Released");
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent e)
{
lbl.setText("Dragging mouse at " + e.getX() + ", " + e.getX());
}

// Handle mouse moved.


public void mouseMoved(MouseEvent e)
{
lbl.setText("Moving mouse at " + e.getX() + ", " + e.getY());
}

//main here
public static void main(String[] args)
{
Mouse ob= new Mouse(); //object creation
ob.setSize(500,500);
ob.setLayout(null);
ob.setVisible(true);
}
}

The Mouse class extends JFrame and implements both the MouseListener and MouseMotionListener
interfaces. These two interfaces contain methods that receive and process the various types of mouse
events. The addMouseListener() and addMouseMotionListener() methods are the members of
Component.
The above swing program displays various message according to the event generated by the mouse.
It displays “Mouse Clicked”, “Mouse Entered”, “Mouse Exited”, “Mouse Pressed”, “Mouse Released”,
and also with the coordinate values for mouse movement and mouse dragging.

9.8. Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as: JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Swing Features:
1. Light Weight − Swing components are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
2. Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider,
colorPicker, and table controls.
3. Highly Customizable − Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
4. Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at
run-time, based on available values.

116 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4) AWT provides fewer components than Swing. Swing provides more powerful components
such as tables, lists, scrollPanes,
colorChooser, tabbedPane, etc.

5) AWT doesn't follows MVC (Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.

9.9. Building GUI with swing


We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame(); //creating instance of JFrame

JButton b=new JButton ("click"); //creating instance of JButton


b.setBounds(130,100,100, 40); //x axis, y axis, width, height

f.add(b); //adding button in JFrame

f.setSize(400,500); //400 width and 500 height


f.setLayout(null); //using no layout managers
f.setVisible(true); //making the frame visible
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 117


9. EVENT, HANDLING EVENTS & SWING

9.10. Separating GUI and application code


MVC (Model-View-Controller) is a software design pattern used in software engineering. The pattern
isolates domain logic (the application logic for user) from input and presentation (GUI), permitting
independent development, testing and maintenance of each. The three different logics involved are:
Model: The model represents data and the rules that govern access to and updates of this data.
View: The view displays the contents of a model. It specifies exactly how the model data
should be presented. If the model data changes, the view must update its presentation
as needed.
Controller: The controller translates the user’s interactions with the view into actions that the model
will perform. User interaction could be button clicks or menu selections.

Every component has three characteristics: Contents, Visual Apperance, Behavior.


For instance, lets talk about a textField. It has its content, e.g. textField’s text, visual appearance, e.g.
color, size, etc and its behavior i.e. the reaction to events.
MVC pattern suggests to separate all these three sets of characteristics in three separate classes.
These classes are:
• The model that stores the contents
• The view that displays the contents, and
• The controller which handles user input.
Swing components in Java are implemented adhering to the MVC pattern. As a programmer using
Swing components, we generally do not need to think about the MVC architecture. Each User
Interface (UI) has a wrapper class (such as JButton or JTextField) that stores the model and the view.
When we want to inquire about the contents (for e.g, the text in a textField), the wrapper class asks
the model and returns the answer to us.
When we want to change the view (for e.g. move the caret position in a text field), the wrapper class
forwards that request to the view.
However, there are occasions where the wrapper class does not work hard enough on forwarding
commands. Then, we have to ask it to retrieve the model and work directly with the view- that is the
job of the look-and-feel code).

Figure: Activity Diagram to show Interaction between model, view and controller objects

118 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

Some Basic Components of Swing


Swing components are basic building blocks of an application. Swing has a wide range of various
components, including buttons, check boxes, sliders, and list boxes.

S. Components Descriptions
No.
1. JLabel JLabel is a simple component for displaying text, images or both. It
does not react to input events. As a result it cannot get the keyboard
focus.
2. JButton JButton is in implementation of a push button. It is used to trigger an
action if the user clicks on it. JButton can display a text, an icon, or
both.
3. JTextField JTextField is a text component that allows editing of a single line of
non-formatted text.
JPassword Field It is a JTextField subclass that does not show the characters that the
user types.
4. JCheckBox JCheckBox is a box with a label that has two states: on and off. If the
check box is selected, it is represented by a tick in a box. A check
box can be used to show or hide a splashscreen at startup, toggle
visibility of a toolbar etc.
5. JRadioButton JRadioButton allows the user to select a single exclusive choice
from a group of options. It is used with the ButtonGroup component.
6.
7. JSlider It is a component that lets the user graphically select a value by
sliding a knob within a bounded interval. Moving the slider’s knob,
the stateChanged() method of the slider’s ChangeListener is called.
8. JComboBox It is a component that combines a button or editable field and a drop-
down list. The user can select a value from the drop-down list, ehich
appears at the user’s request.
9. JProgressBar A progress bar is a component that is used when we process lengthy
tasks. It is animated so that the user knows that our task is
progressing. The JProgressBar component provides a horizontal or
a vertical progress bar. The initial and minimum values are 0 and the
maximum is 100.
10. JList It is a component that displays a list of objects. It allows the user to
select one or more items.
Refer: https://www.studytonight.com/java/java-swing-components.php
http://zetcode.com/tutorials/javaswingtutorial/basicswingcomponents/
https://www.javatpoint.com/java-jbutton

Programming Technology © Er. Shiva Ram Dam, 2019 119


9. EVENT, HANDLING EVENTS & SWING

Some Java Swing programs:


1. Write a simple program for handling event in Java.
Or
Write a code for mouse event delegation model with your own example.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class EventHandlingDemo extends JFrame
{
//variable declaration

private JButton btnClick;

EventHandlingDemo () //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button

btnClick = new JButton("Click Here");


add(btnClick);

//handling the event generated when used clicks the button

btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Button Clicked");
}
});
}

public static void main(String[] args)


{
EventHandlingDemo ob= new EventHandlingDemo (); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}
}

120 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

2. Write a simple program to handle mouse event in Java.


Refer note in previous pages.

3. Write a java swing program with a button and display “Hello Java” when the button is clicked.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CaseConverter extends JFrame
{
//variable declaration

private JButton btnConvert;

CaseConverter() //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button

btnConvert = new JButton("Convert Case");


add(btnConvert);

//handling the event generated when used clicks the button

btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hello Java"); //displays Hello Java in Commmand prompt

}
});
}

public static void main(String[] args)


{
CaseConverter ob= new CaseConverter(); //object creation

Programming Technology © Er. Shiva Ram Dam, 2019 121


9. EVENT, HANDLING EVENTS & SWING

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}
}

4. Write a swing application with one close button when clicked should terminate the program.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ClickClose extends JFrame
{
//variable declaration

private JButton btnClose;

ClickClose() //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button
btnClose = new JButton("Close");
add(btnClose);

//handling the event generated when used clicks the button


btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0); //closes the window

}
});
}

public static void main(String[] args)


{
ClickClose ob= new ClickClose(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}
}

122 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

5. WAP with a button; change the background color to green on clicking the button.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ChangeColor extends JFrame
{
//variable declaration

private JButton btnClick;

ChangeColor () //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button

btnClick = new JButton("Change Background color");


add(btnClick);

//handling the event generated when used clicks the button

btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getContentPane().setBackground(Color.GREEN);
}
});
}

public static void main(String[] args)


{
ChangeColor ob= new ChangeColor(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 123


9. EVENT, HANDLING EVENTS & SWING

6. Swing Application with two input boxes and a button which when clicked displays the result of two
string the textboxes to console after converting them into uppercase.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CaseConverter extends JFrame
{
//variable declaration

private JFrame frame;


private JTextField txtFirstString, txtSecondString;
private JLabel lblFirstString,lblSecondString;
private JButton btnChange;
private String result;

CaseConverter() //constructor here initializes the values when object created

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//creating label for First String

lblFirstString = new JLabel("First String"); //First Num appears in label

lblFirstString.setBounds(50, 50, 100, 20); //specifies x , y , width and height

add(lblFirstString); //adds the label

//Creating a textfield to get first String

txtFirstString = new JTextField();


txtFirstString.setBounds(200, 50, 150, 30);
add(txtFirstString);
txtFirstString.setColumns(10); // sets column size of 10

//creating label for Second String

lblSecondString = new JLabel("Second Num");

124 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

lblSecondString.setBounds(50, 80, 100, 20);


add(lblSecondString);

//Creating a textfield to get second String

txtSecondString= new JTextField();


txtSecondString.setBounds(200, 80, 150, 30);
add(txtSecondString);
txtSecondString.setColumns(10);

//Creating a button

btnChange = new JButton("Add");


add(btnChange);

//handling the event generated when used clicks the button

btnChange.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String st1=txtFirstString.getText();
String st2=txtSecondString.getText();
result=st1+st2;
System.out.println(result.toUpperCase());
}
});
}

public static void main(String[] args)


{
CaseConverter ob= new CaseConverter(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(200, 200); //setting size of Jframe

ob.setVisible(true);
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 125


9. EVENT, HANDLING EVENTS & SWING

7. WAP to create swing application to accept two numbers in two different textboxes form user and
display the sum in another textbox when user clicks the Add button.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Adder extends JFrame
{
//variable declaration

private JFrame frame;


private JTextField txtFirstNum, txtSecondNum, JTextField,txtSum;
private JLabel lblFirstNum, lblSecondNum, lblSum;
private JButton btnAdd;
private int n1,n2,sm;
private String answer;

Adder() //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//creating label for First Number

lblFirstNum = new JLabel("First Num"); //First Num appears in label

lblFirstNum.setBounds(50, 50, 100, 20); //specifies x , y , width and height

add(lblFirstNum); //adds the label

//Creating a textfield to get first number

txtFirstNum = new JTextField();


txtFirstNum.setBounds(200, 50, 150, 30);
add(txtFirstNum);
txtFirstNum.setColumns(10); // sets column size of 10

//creating label for Second Number

lblSecondNum = new JLabel("Second Num");


lblSecondNum.setBounds(50, 80, 100, 20);
add(lblSecondNum);

//Creating a textfield to get second number

txtSecondNum = new JTextField();


txtSecondNum.setBounds(200, 80, 150, 30);
add(txtSecondNum);
txtSecondNum.setColumns(10);

//Creating a label for Sum

126 Programming Technology © Er. Shiva Ram Dam, 2019


9. EVENT, HANDLING EVENTS & SWING

lblSum = new JLabel("Sum");


lblSum.setBounds(50, 200, 100, 20);
add(lblSum);

//Creating a textfield to display sum

txtSum = new JTextField();


txtSum.setBounds(200, 200, 150, 30);
add(txtSum);
txtSum.setColumns(10);

//Creating a button

btnAdd = new JButton("Add");


add(btnAdd);

//handling the event generated when used clicks the button

btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
n1=Integer.parseInt(txtFirstNum.getText());
n2=Integer.parseInt(txtSecondNum.getText());
sm=n1+n2;
answer=String.format("%d",sm);
txtSum.setText(answer);
}
});
}

public static void main(String[] args)


{
Adder f= new Adder();
f.setLayout(new FlowLayout()); //setting layout using FlowLayout object
f.setSize(200, 200); //setting size of Jframe

f.setVisible(true);
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 127


9. EVENT, HANDLING EVENTS & SWING

Exam Questions:
1. How can we build GUI with swing? Explain with an example. [2018 spring]
2. Write difference between AWT and Swing. Write a simple program for handling event in Java.
[2018 fall]
3. What is Swing? How GUI is built using swing? [2017 fall]
4. Discuss these basic components of Swing with code snippets- JButton, JTextField, JCheckBox,
JRadioButton. [2017 spring]
5. Write a swing application with two input textboxes and a button which when clicked, it should write
the result of two string in textboxes to console after converting them to Uppercase. [2016 fall]
6. What is event and event delegation model? [2016 spring]
7. What is event delegation model? Write a code for mouse event delegation model with your own
example. [2015 spring]
8. What is event delegation model? Write a program with a button; change the background color to
green on clicking the button. [2015 fall]
9. How is event handling done by swing? Write a java swing program with a button. Display “Hello
Java” when the button is clicked. [2014 spring]
10. How does Java Event Handling work? Write a swing application with one close button when
clicked, it should terminate the application. [2014 fall]
11. What is delegation event model? Is it possible to process events without using delegation event
model? Explain with an example. [2013 spring]
12. Differentiate between AWT and swing. How do we handle mouse events in Java? [2013 spring]
13. Write short notes on:
a. Delegation event model. [2018 fall]
b. Event handling in Java [2017 spring]
c. Event handling [2016 fall]
d. Swing [2016 spring]
e. Building GUI with swing [2015 spring]
f. Action listeners [2015 fall]
g. Event source, event object and event listeners with example. [2013 spring]

128 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

10. Java Server Pages (JSP)/ Sever Technology [Credit: 7 hrs]

10.1. JSP/ Servlet Technology Overview


Applets, Servlets, and Java Server Pages
When we instruct our Web browser to view a page from a Web server on the Internet, our Web
browser requests the page from the Web server, the Web server processes the request (which
may involve reading the requested page from a file on the hard drive), and then the Web server
sends the requested page to our Web browser. Our Web browser formats, or renders, the received
data to fit on our computer screen. This interaction is a specific case of the client/server model. Our
Web browser is the client program, our computer is the client computer, the remote website is the
server computer, and the Web server software running on the remote website is the server program.
In the context of a Web application, the client/server model is important because Java code can run
in two places: on the client or on the server. There are trade-offs to both approaches.
Server-based programs have easy access to information that resides on the server, such as
customer orders or inventory data. Because all of the computation is done on the server
and results are transmitted to the client as HTML, a client does not need a powerful
computer to run a server-based program.
On the other hand, a client-based program may require a more powerful client computer,
because all computation is performed locally. However, richer interaction is possible,
because the client program has access to local resources, such as the graphics display
(e.g., perhaps using Swing) or the operating system. Many systems today are constructed
using code that runs on both the client and the server to reap the benefit of both
approaches.
Web applications built with Java include: Java applets, Java servlets, and Java Server Pages (JSP).
Java applets run on the client computer.
JavaScript, which is a different language than Java despite its similar name, also runs on
the client computer as part of the Web browser.
Java servlets and Java Server Pages run on the server.
Java Server pages which are a dynamic version of Java servlets. Servlets must be compiled before they
can run, just like a normal Java program. In contrast, JSP code is embedded with the corresponding HTML
and is compiled “on the fly” into a servlet when the page is requested. This flexibility can make it
easier to develop Web applications using JSP than with Java servlets.
The following figure10.1, figure 10.2 and figure 10.3 shows that the running a Java applet, Java
Servlet and JSP program.

Figure10.1: Running a Java Applet

Programming Technology © Er. Shiva Ram Dam, 2019 129


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

Figure 10.2: Running a Java Servlet

Figure 10.3: Running a Java Server Page (JSP) Program

10.2. Servlet Life Cycle, Creating and deploying new Servlet


10.2.1. Servlet
Servlets are the Java programs that runs on the Java-enabled web server or application server.
They act as a middle layer between a requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server. They are used to handle the request obtained
from the web server, process the request, produce the response, then send response back to the
web server.
Using Servlets, we can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
The following diagram shows the position of Servlets in a Web Application.

130 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

10.2.2. Servlet advantages


Advantages of Servlet over CGI
CGI is actually an external application which is written by using any of the programming languages
like C or C++ and this is responsible for processing client requests and generating dynamic
content.
Before introduction of Java Servlet API, CGI technology was used to create dynamic web
applications. CGI technology has many drawbacks such as creating separate process for each
request, platform dependent code (C, C++), high memory usage and slow performance.
Java Servlets often serve the same purpose as programs implemented using the CGI. CGI has
several limitations such as performance, scalability, reusability, etc. that a servlet doesn’t have.
Servlets offer several advantages in comparison with the CGI.
1. Performance is significantly better. Servlets execute within the address space of a Web
server. It is not necessary to create a separate process to handle each client request.
2. Servlets are platform-independent because they are written in Java.
3. Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So, servlets are trusted.
4. The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI (Remote Method
Invocatioin) mechanisms that you have seen already.

Difference between Servlet and CGI


Basis for Comparison Common Gateway Interface Servlets
Programs are written in the Programs employed using
1. Basic
native OS. Java.
Does not rely on the
2. Platform dependency Platform dependent
platform
Processes are created
Each client request creates its
3. Creation of process depending on the type of the
own process.
client request.
Present in the form of
4. Conversion of the
executables (native to the Compiled to Java Bytecode.
script
server OS).
5. Runs on Separate process JVM
6. Security More vulnerable to attacks. Can resist attacks.
7. Speed Slower Faster
Before running the scripts it
8. Processing of script Direct
is translated and compiled.
9. Portability Cannot be ported Portable

10.2.3 . Servlet Life Cycle


Java Servlet life cycle consists of a series of events that begins when the Servlet container loads
Servlet, and ends when the container is closed down. A Servlet container is the part of a web
server or an application server that controls a Servlet by managing its life cycle.
A Servlet life cycle can be defined as the entire process from its creation till the destruction. Three
methods are central to the life cycle of a servlet: init(), service() and destroy().

Programming Technology © Er. Shiva Ram Dam, 2019 131


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

Figure: Servlet Life Cycle

a) Loading and Instantiation


Assume that a user enters a URL to a web browser. The browser then generates an HTTP
request for this URL. This request is then sent to the appropriate server. The web server
receives this HTTP request. The server maps this request to a particular servlet. The
servlet is dynamically retrieved and loaded into the address space of the server.

b) Initialization
The server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the
servlet, so, it may configure itself. The init() method is called once only.

c) Handling Request
The server invokes the service( ) method of the servlet. This method is called to process
the HTTP request (i.e. client’s request). It may also formulate an HTTP response for the
client. The servlet remains in the server’s address space and is available to process any
other HTTP requests received from clients. The service( ) method is called for each HTTP
request.

d) Destroy
The destroy() method runs only once during the lifetime of a Servlet. It signals the end of
the Servlet instance. The server calls the destroy( ) method to relinquish any resources
such as file handles that are allocated for the servlet. Important data may be saved to a
persistent store. The memory allocated for the servlet and its objects can then be garbage
collected.

10.2.4 . A simple Servlet


To create a Servlet application, we need to follow the below mentioned steps. These steps are
common for all the Web server. In our example we are using Apache Tomcat server. Apache
Tomcat is an open source web server for testing servlets and JSP technology.
After installing Tomcat Server on your machine follow the below mentioned steps :
1. Create directory structure for your application.
2. Create a Servlet
3. Compile the Servlet
4. Create Deployement Descriptor for your application
5. Start the server and deploy the application

132 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

1. Create directory structure for your application.


Create the below directory structure inside Apache-Tomcat\webapps directory.
• All HTML, static files (images, css etc) are kept directly under Web application folder.
• The web.xml (deployment descriptor) file is kept under WEB-INF folder.
• While all the Servlet classes are kept inside classes folder inside WEB-INF folder.
• Here, we make First as our application folder.

2. Create a Servlet
Open any text editor (Notepad or Notepad++), write the below code and save it as
HelloServlet.java

import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello! This is my First Servlet");
pw.close();
}
}

Let’s look closely at this program.


First, note that it imports the javax.servlet package. This package contains the classes and
interfaces required to build servlets.
Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet
class provides functionality that simplifies the creation of a servlet. For example, it provides
versions of init( ) and destroy( ), which may be used as is. We need to supply only the service (
) method. Inside HelloServlet, the service( ) method (which is inherited from GenericServlet ) is
overridden. This method handles requests from a client.
Notice that the first argument is a ServletRequest object. This enables the servlet to read data
that is provided via the client request. The second argument is a ServletResponse object. This
enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this
program, the MIME type is text/html. This indicates that the browser should interpret the
content as HTML source code.

Programming Technology © Er. Shiva Ram Dam, 2019 133


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to
the client as part of the HTTP response. Then println( ) is used to write some simple HTML
source code as the HTTP response.

3. Compile the Servlet


Compile the above HelloServlet.java file in the command prompt as:
javac HelloServlet.java
We will get HelloServlet.class file. Copy and paste it into WEB-INF/classes/ directory.

4. Create Deployement Descriptor for your application


Deployment Descriptor(DD) is an XML document that is used by Web Container to run
Servlets and JSP pages. DD is used for several important purposes such as:
• Mapping URL to Servlet class.
• Initializing parameters.
• Defining Error page.
• Security roles.
• Declaring tag libraries.
Save this file as web.xml into the WEB-INFdirectory.
<web-app>

<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

5. Start the server and deploy the application


Start the Apache Tomcat Server before executing the servlet.
Start the web browser and enter the URL as shown below:
http://localhost:8080/First/hello
or
http://127.0.0.1: 8080/First/hello
We will observe the output as:

134 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

10.2.5. The Servlet API


We need to use Servlet API (Application Programming Interface) to create servlets. Two packages
contain the classes and interfaces that are required to build servlets. These are javax.servlet and
javax.servlet.http. They constitute the Servlet API. The javax.servlet and javax.servlet.http
packages represent interfaces and classes for servlet API.
• The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
• The javax.servlet.http package contains interfaces and classes that are responsible for
http requests only.

A. The javax.servlet Package


The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate. The classes and interface in this package
are protocol independent.
The following table summarizes the core interfaces that are provided in this package. The most
significant of these is Servlet. All servlets must implement this interface or extend a class that
implements the interface. The ServletRequest and ServletResponse interfaces are also very
important.
1.Interface in javax.servlet Package:
S.No. Interfaces Description
1. Servlet Declares life cycle methods that all servlets must
implement.
2. ServletConfig Allows servlets to get initialization parameters
3. ServletContext Allows servlets to communicate with its servlet
container.
Enables servlets to log events and access information
about their environment.
4. ServletRequest Provides client request information to a servlet.
Used to read data from a client request.
5. ServletResponse Assist a servlet in sending a response to the client.
Used to write data to a client response.

Table: Some important Interfaces in javax.servlet package

2.Classes in javax.servlet Package:


The following table summarizes the core classes viz. provided in the javax.servlet package:

S.No. Classes Description


1. GenericServlet Provides a basic implementation of the Servlet
interface for protocol independent servlets.
Implements the Servlet and ServletConfig
interfaces.
2. ServletlnputStream Provides an input stream for reading binary data
from a client request.
3. ServletOutputStream Provides an output stream for sending binary data
to the client.
4. ServletException Defines a general exception, a servlet can throw
when it encounters difficulty.
Indicates a servlet error occurred.
5. UnavailableException Indicates that a servlet is not available to service
client request.
Table: Some important classes in javax.servlet package

Programming Technology © Er. Shiva Ram Dam, 2019 135


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

A.1.1. The Servlet Interface

All servlets must implement the Servlet interface. It defines the basic structure of a servlet. It is the
interface that container use to reference servlets. All servlets implement this interface, either
directly or indirectly by extending either the GenericServlet or HttpServlet class which implements
the Servlet interface.
It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life
cycle of a servlet.
A method is also provided that allows a servlet to obtain any initialization parameters. The
getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet
developer overrides the getServletInfo( ) method to provide a string with useful information (for
example, author, version, date, copyright). The server invokes this method also.

A.1.2. The ServletConfig Interface


The ServletConfig interface is implemented by the server. Servers use ServletConfig object to pass
configuration information to servlets. The configuration information contains initialization
parameters, the name of the servlet and a ServletContext object which gives servlet information
about the container.
The methods declared in this interface are:
S.No. Methods Description
1. String getlnitParameter It returns a String containing the value of a named
(String name) initialization parameter or null if specified parameter does
not exist.
2. String getServletName() It returns the name assigned to a servlet in its deployment
descriptor.
If no name is specified, this returns the servlet class name
instead.
3. ServletContext It returns a reference to the ServletContext object for the
getServletContext() associated servlet, allowing interaction with the server.
4. Enumeration It returns the name of the servlet's initialization parameters
getlnitParameterName() as an enumeration of String objects or an empty
Enumeration if no initialization parameters are specified.

A.1.3. The ServletContext Interface


The ServletContext interface provides a means for servlets to communicate with its servlet
container. This communication includes finding path information, accessing other servlets running
on the server, writing to the server log, getting MIME type of a file and so on. There is one context
per web application per Java Virtual Machine.
The ServletContext object is a container within the ServletConfig object which the web server
provides to the servlet when the servlet is initialized .
The ServletContext interface specifies the following methods:

S.No. Methods Description


1. Object setAttribute(String name) It sets the servlet container attribute with the given
name or null if the attribute doesnot exist.
2. String getMimeType(String fileName) It returns the MIME (Multi-Purpose Internet Mail Extensions)
type of a specified file or null if it is not known.
3. String getRealPath(String vpath) It returns the real path (on the server file system)
that corresponds to the virtual path vpath.
4. String getServerlnfo() It returns the name and version of the servlet
container separated by a forward slash (f).
5. void setAttribute(String It binds a specified object to a given attribute
name, Object obj) name in this servlet context.

136 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

6. void log (String msg) It writes the specified message to a servlet log file
usually an
event log.
7. void log(String msg, Throwable t) It writes the specified message msg and a stack
trace for a specified Throwable exception t to the
servlet log file.

A.1.4. ServletRequest Interface


The ServletRequest interface defines an object that encapsulates information about a single client
request. The servlet container creates a ServletRequest object and passes it as an argument to
the servlet's service () method. Data provided by the object generally includes parameter names
and values, implementation specific attributes and an input stream for reading binary data from the
request body. Some of the methods specified in it are given below :
S.No. Methods Description
1. Object getAttribute(String name) It returns the value of the named attribute as an
object, or null if the named attribute does not
exist.
2. Enumeration getAttributeNames() It returns an enumeration of all attributes
contained in the request.
3. int getContentLength() It returns the length (in bytes) of the content
being sent via the
input stream or -1 if the length is not known.
4. String getContentType() It request the MIME type of the body of the
request or null if the type is not known.
5. ServletlnputStream getlnputStream() It retrieves the body of the request as binary
data using
Servletlnputstream object.
6. String getparameter (String name) It returns the value of the specified parameter or
null if the
parameter does not exists or without a value.
7. Enumeration getParameterNames() It returns all the parameter names as
enumeration of String
objects.
8. String [ ] getParameterValues(String It returns an array of String objects containing all
name) the values of the specified parameter or null if
the parameter does not exist.
9. String getprotocol() It returns the name and version of the protocol
used by the request.
10. String getParameterAddr() It returns the IP address of the client that sent
the request.
11. String getRemoteHost() It returns the name of the client that send the
request.
12. String getScheme() It returns the name and the scheme used to
make the request.
For example : http, ftp,https etc.
13. String getServerName() It returns the name of the server that receives
the request.
14. int getServerport() It returns the port number on which the request
was received.
15 BufferedReader getReader() It retrieves the body of the request as character
data.

A.1.5. The Servlet Response Interface

The ServIetResponse interface is the response counterpart of the ServIetRequest object. It defines
an object to assist a servlet in sending MIME encoded data back to the client. The servlet container

Programming Technology © Er. Shiva Ram Dam, 2019 137


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

create a ServIetResponse object and passes it as an argument to the servlet's service () method.
The ServletResponse interface enables a servlet to formulate a response for a client.
Some of the most commonly used methods of this interface are as follows:

S.No. Methods Description


1. void It sets the MIME type of the response being sent to the
setContentType(String client. For example, in case of HTML, the MIME type should
type) be set to "text/HTML".
2. void setContentLength(int It sets the length of the content being returned by the server.
Ien) In HTTP servlets, this method sets the HTTP content -length
header.
3. ServIetOutputStream It returns a ServIetOutStream object than can be used for
getOutputStream() writing binary data into the response.
4. printWriter getWriter() It returns a PrintWriter object that can send character text in
the response.
5. String It returns the name of the charset used for the MIME body
getCharacterEncoding() sent in the response.

A.2.1. The GenericServlet CLASS

The GenericServlet class provides a basic implementation of the Servlet interface. This is an
abstract class and all subclasses should implement the service () method. This class implements
both Servlet as well as ServletConfig interface. It has the following methods in addition to those
declared in Servlet and ServletConfig interfaces.
The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
GenericServlet implements the Servlet and ServletConfig interfaces. In addition, a method to
append a string to the server log file is available. The signatures of this method are shown here:
S.No. Methods Description
1. void init () It is similar to init (ServletConfig config). This method is provided
as a convenience so that servlet developers do not have to worry
about storing the ServletConfig object.
2. void log (String msg) It writes the specified message msg to a servlet log file.
3. void log(String msg, It writes the name of the servlet, the specified message msg and
Thowable t) the stack trace t to the servlet log file

A.2.2 ServletInputStream CLASS


The ServletlnputStream class extends InputStream. It provides input stream for reading binary data
from a client request. A servlet obtains a ServletlnputStream object from the getlnputStream ()
method of ServletRequest. It defines the default constructor which does nothing.

A.2.3 ServletOutputStream CLASS


The ServletOutputStream class extends OutputStream. It provides an output stream for sending
binary data back to the client. A servlet obtains a ServletOutputStream object from the
getOutputStream () method of ServletResponse. It also has a default constructor that does
nothing. In addition, it also includes a range of print () and println () methods for sending text or
HTML.
It takes the following form
• void print(type v)
• void println(type v)
Here, type specifies the datatype int, char, float, long, String, double, boolean and v specifies the
data to be written.

138 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

A.2.4 ServletException CLASS


The javax.Servlet defines two exception classes ServletException and UnavailableException. The
ServletException is a generic exception which can be thrown by servlets encountering difficulties.
UnavailableException is a special type of servlet exception which extends the ServletException
class. The purpose of this class is to indicate to the servlet container that the servlet is either
temporarily or permanently unavailable to service client requests.

3. Reading Servlet Parameters


The ServletRequest interface includes methods that allow us to read the names and values of
parameters that are included in a client request.
Let us consider the below example that contains two files. A web page is defined in index.html,
and a servlet is defined in ReadingServletParameterDemo.java.
The HTML source code for index.html is shown in the following listing. It defines a table that
contains two labels and two text fields. One of the labels is Employee and the other is Phone.
There is also a submit button. Notice that the action parameter of the form tag specifies a URL.
The URL identifies the servlet to process the HTTP POST request.
Saved as: index.html in a folder named ReadingServletParameterDemo in webapps ( i.e.
C:\Program Files (x86)\Apache Software Foundation\Tomcat
9.0\webapps\ReadingServletParameterDemo )

<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/ReadingServletParameterDemo/parameter">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

The source code for ReadingServletParameterDemo.java. is shown in the following listing. The
service( ) method is overridden to process client requests. The getParameterNames( ) method
returns an enumeration of the parameter names. These are processed in a loop. We can see that
the parameter name and value are output to the client. The parameter value is obtained via the
getParameter( ) method.

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class ReadingServletParameterDemo extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();

Programming Technology © Er. Shiva Ram Dam, 2019 139


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

// Get enumeration of parameter names.


Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}

The web.xml file is as:


<web-app>

<servlet>
<servlet-name>demo2</servlet-name>
<servlet-class>ReadingServletParameterDemo</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>demo2</servlet-name>
<url-pattern>/parameter</url-pattern>
</servlet-mapping>

</web-app>

Step 1:
Lets us first create a folder ReadingServletParameterDemo in the webapps directory of Tomcat
(i.e. C:\Program Files (x86)\Apache Software Foundation\Tomcat 9.0\webapps).

Step 2:
Create a index.html file inside the folder with above mentioned code.

Step 3:
Write a servlet program as given above and save it as ReadingServletParameterDemo.java inside
src folder which is inside the ReadingServletParameterDemo folder. (i.e. C:\Program Files
(x86)\Apache Software Foundation\Tomcat 9.0\webapps\ReadingServletParameterDemo\src)

Step 4:
Compile the above java file in command prompt and put the ReadingServletParameterDemo.class
file inside the WEB-INF/classes directory
(i.e. C:\Program Files (x86)\Apache Software Foundation\Tomcat
9.0\webapps\ReadingServletParameterDemoDemo\WEB-INF\classes)

Step 5:
Create a web.xml file as given above in the WEB-INF directory (i.e. C:\Program Files (x86)\Apache
Software Foundation\Tomcat 9.0\webapps\ ReadingServletParameterDemoDemo \WEB-INF).

Step 6:
Start Tomcat.

Step 7:
Open a web browser and type http://localhost:8080/ReadingServletParameterDemo/index.html,
you should get as:

140 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

Step 8:
Supply the information and submit it. You should get a message as:

Assignment:

Write a code for following example using Servlet:

Username

Password

Submit Reset

B. The javax.servlet.http Package


The javax.servlet.http package supports the development of servlets that use the HTTP protocol.
The classes in this package extend the basic servlet functionality to support various HTTP specific
features, including request and response headers, different request methods, and cookies.

1.Interface in javax.servlet.http Package:

Table: Some important Interfaces in javax.servlet.http package

2.Classes in javax.servlet.http Package:

Table: Some important classes in javax.servlet.http package


Programming Technology © Er. Shiva Ram Dam, 2019 141
10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

B.1.1. The HttpServletRequest Interface

HttpServletRequest extends javax.servlet.ServletRequest and provides a number of methods that


make it easy to access specific information related to an HTTP request. The HttpServletRequest
interface enables a servlet to obtain information about a client request.
Several of its methods are shown in following table:

B.1.2. The HttpServletResponse Interface

The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.


Several constants are defined. These correspond to the different status codes that can be
assigned to an HTTP response.
For example, SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND
indicates that the requested resource is not available.
Several methods of this interface are summarized in table below.

142 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

B.1.3. The HttpSession Interface


The HttpSession interface is the core of the session tracking functionality introduced in Version 2.0
of the Servlet API. The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session.
A servlet obtains an HttpSession objects from the getSession() method of HttpServletRequest. The
putValue() and removeValue() methods bind Java objects to a particular session.
Several of its methods are summarized in Table below. All of these methods throw an
IllegalStateException if the session has already been invalidated.

B.1.4. The HttpSessionBindingEvent Interface

An HttpSessionBindingEvent is passed to the appropriate method of an


HttpSessionBindingListener when an object is bound to or unbound from an HttpSession. The
getName() method returns the name to which the bound object has been assigned, and the
getSession() method provides a reference to the session the object is being bound to.
The HttpSessionBindingListener interface is implemented by objects that need to be notified when
they are bound to or unbound from an HTTP session. The methods that are invoked when an
object is bound or unbound are:
void valueBound(HttpSessionBindingEvent e)
void valueUnbound(HttpSessionBindingEvent e)
Here, e is the event object that describes the binding.

Programming Technology © Er. Shiva Ram Dam, 2019 143


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

B.2.1. The Cookie Class


The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information. Cookies are valuable for tracking user activities. For example, assume that a user
visits an online store. A cookie can save the user’s name, address, and other information.
The user does not need to enter this data each time he or she visits the store. A servlet can write a
cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface. The
data for that cookie is then included in the header of the HTTP response that is sent to the
browser.
The names and values of cookies are stored on the user’s machine. Some of the information that is
saved for each cookie includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an
expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session
ends. Otherwise, the cookie is saved in a file on the user’s machine.
The domain and path of the cookie determine when it is included in the header of an HTTP request. If the
user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server.
Otherwise, it is not. There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value).
Here, the name and value of the cookie are supplied as arguments to the constructor.

144 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

B.2.2. The HttpServlet Class


The HttpServlet class extends GenericServlet. It is commonly used when developing servlets
that receive and process HTTP requests. The methods defined by the HttpServlet class are
summarized in Table below:

B.2.3. The HttpSessionEvent Class


// will be dealt in session management

B.2.4. The HttpSessionBindingEvent Class


// will be dealt in session management

Programming Technology © Er. Shiva Ram Dam, 2019 145


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

10.3. HTTP request handling, Session Management


The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A
servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ),
doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). The GET and POST requests are commonly
used when handling form input.

10.3.1. Handling HTTP GET Requests


The doGet() method is invoked by server through service() method to handle a HTTP GET request.
This method also handles HTTP HEAD request automatically as HEAD request is nothing but a
GET request having no body in the code for response and only includes request header fields. To
understand the working of doGet() method, let us consider a sample program to define a servlet for
handling the HTTP GET request.

Step 1: Lets us first create a folder GetRequestDemo in the webapps directory of Tomcat (i.e.
C:\Program Files (x86)\Apache Software Foundation\Tomcat 9.0\webapps).

Step 2: Create a chooser.html file inside the folder with below code:

<html>
<body>
<center>
<form name="Form1"action="http://localhost:8080/GetRequestDemo/colorchooser">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

Step 3: Write a servlet program and save it as GetRequestDemo.java inside src folder which is
inside the GetRequestDemo folder. (i.e. C:\Program Files (x86)\Apache Software
Foundation\Tomcat 9.0\webapps\GetRequestDemo\src)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetRequestDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

146 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

In the above servlet program, the doGet( ) method is overridden to process any HTTP GET
requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to
obtain the selection that was made by the user. A response is then formulated.

Step 4: Compile the above java file in command prompt and put the GetRequestDemo.class file
inside the WEB-INF/classes directory (i.e. C:\Program Files (x86)\Apache Software
Foundation\Tomcat 9.0\webapps\GetRequestDemo\WEB-INF\classes)

Step 5: Create a web.xml file as below in the WEB-INF directory (i.e. C:\Program Files
(x86)\Apache Software Foundation\Tomcat 9.0\webapps\GetRequestDemo\WEB-INF).

<web-app>

<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>GetRequestDemo</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/colorchooser</url-pattern>
</servlet-mapping>

</web-app>

Step 6: Start Tomcat.

Step 7: Open a web browser and type http://localhost:8080/GetRequestDemo/chooser.html , you


should get as:

Step 8: Select the color (say you selected Red) and submit it. You should get a message as:

Programming Technology © Er. Shiva Ram Dam, 2019 147


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

10.3.2. Handling HTTPPOST Requests


Like doGet() method, the doPost() method is invoked by server through service() method to
handle HTTP POST request. The doPost() method is used when large amount of data is required
to be passed to the server which is not possible with the help of doGet() method.
In doGet() method, parameters are appended to the URL whereas, in do Post() method
parameters are sent in separate line in the HTTP request body. The doGet( ) method is mostly
used when some information is to be retrieved from the server and the doPost() method is used
when data is to be updated on server or data is to be submitted to the server. To understand the
working of doPost() method, let us consider a sample program to define a servlet for handling the
HTTP POST request.
The steps are all as we discussed above in the HTTPGET Request.
The servlet program is:

//saved as GetPostDemo.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetPostDemo extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

The html file is: saved as chooser.html


<html>
<body>
<center>
<form name="Form1" method=”post”
action="http://localhost:8080/GetPostDemo/colorchooser">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

The web.xml file is as:

<web-app>

<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>GetPostDemo</servlet-class>

148 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

</servlet>

<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/colorchooser</url-pattern>
</servlet-mapping>

</web-app>

When we type http://localhost:8080/GetPostDemo/chooser.html , we get as:

Upon selecting the color (say we selected Green) and submitted it. we should get a message as:

10.3.3. Session Tracking

Session simply means a particular interval of time. Session Tracking is a way to maintain state
(data) of an user. It is also known as session management in servlet.
Http protocol is a stateless. It means each request is considered as the new request . So, we need
to maintain state using session tracking techniques. Each time user requests to the server, server
treats the request as the new request. So we need to maintain the state of an user to recognize to
particular user.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession
object is returned. This object can store a set of bindings that associate names with objects. The
setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings. It is important to note that session state is shared among all
the servlets that are associated with a particular client.
The following servlet illustrates how to use session state. The getSession( ) method gets the
current session. A new session is created if one does not already exist. The getAttribute( ) method
is called to obtain the object that is bound to the name “date”. That objects is a Date object that
encapsulates the date and time when this page was last accessed. (Of course, there is no such
binding when the page is first accessed.) A Date object encapsulating the current date and time is
then created. The setAttribute( ) method is called to bind the name “date” to this object.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

Programming Technology © Er. Shiva Ram Dam, 2019 149


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

// Get the HttpSession object.


HttpSession hs = request.getSession(true);

// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");

// Display date/time of last access.


Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}

// Display current date/time.


date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

When we first request this servlet, the browser displays one line with the current date and time
information. On subsequent invocations, two lines are displayed. The first line shows the date and
time when the servlet was last accessed. The second line shows the current date and time.

10.4. JSP life cycle, Writing JSP pages


10.4.1. JSP
• JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.
• Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
• JSP is a technology for developing web pages that support dynamic content which helps
developers insert java code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.
• A JSP component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application.
• Web developers write JSPs as text files that combine HTML or XHTML code, XML
elements, and embedded JSP actions and commands.
• Using JSP, we can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
• JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages and sharing information between requests, pages etc.

10.4.2. Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1. Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

150 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

2. Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation logic.

3. Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.

4. Less code than Servlet


In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.

10.4.2. JSP vs Different Technologies


JSP is one of the most widely used language over the web. Following is the list of other
advantages of using JSP over other technologies:

1. JSP vs. Active Server Pages (ASP)


The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic
or other MS specific language, so it is more powerful and easier to use. Second, it is portable
to other operating systems and non-Microsoft Web servers.

2. JSP vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.

3. JSP vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.

4. JSP vs. JavaScript


JavaScript can generate HTML dynamically on the client but can hardly interact with the web
server to perform complex tasks like database access and image processing etc.

5. JSP vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

10.4.2. JSP Life Cycle


A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
1. Compilation
2. Initialization
3. Execution
4. Cleanup

Figure: JSP Life Cycle

Programming Technology © Er. Shiva Ram Dam, 2019 151


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

1. Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was
last compiled, the JSP engine compiles the page. The compilation process involves three
steps:
• Parsing the JSP.
• Turning the JSP into a servlet.
• Compiling the servlet.

2. Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If
we need to perform JSP-specific initialization, override the jspInit() method:

public void jspInit()


{
// Initialization code...
}

Typically initialization is performed only once and as with the servlet init method, we generally
initialize database connections, open files, and create lookup tables in the jspInit method.

3. Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP. The jspService() method takes
an HttpServletRequest and an HttpServletResponse as its parameters as follows:

void _jspService(HttpServletRequest request,


HttpServletResponse response)
{
// Service handling code...
}

The jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also

4. Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use
by a container. The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. We need to override jspDestroy to perform any cleanup, such as releasing database
connections or closing open files.
The jspDestroy() method has the following form:

public void jspDestroy()


{
// Your cleanup code goes here.
}

10.4.3. JSP Syntax


1. Declaration Tag :
It is used to declare variables and methods

Syntax:-
<%! Dec var %>

Example:-
<%! int var=10; %>

152 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

Eg:
<%!
private int count=0;
private void incrementCount()
{
count++;
}
%>

2. JSP Expression :
It evaluates and convert the expression to a string. We can also access variables defined in
declarations with expression. The syntax to embed an expression is as follows:

Syntax:-

<%= expression %>

Example:-
<% num1 = num1+num2 %>

Expressions are embedded directly into the HTML. The Web browser will display the value of
the expression in place of the tag. For example, we can output the value of the count variable
in bold type with the following piece of HTML:

The value of count is <b> <%= count %> </b>

3. Java Scriplets :
It allows us to add any number of JAVA code, variables and expressions. Blocks of Java code
can be embedded in a scriptlet.

Syntax:-
<% java code %>

If we wish to output HTML within a scriptlet, then this is done using out.println(), which is used
in the same manner as System.out.println( ).The variable out is already defined for us and is of
type javax.servlet.jsp.JspWriter. Also note that System.out.println( ) will output to the console,
which is useful for debugging purposes, while out.println( ) will output to the browser. The
following scriptlet invokes the incrementCount( ) method and then outputs the value in count :

<%
out.println("The counter's value is " + count + "<br />");
incrementCount();
%>

4. JAVA Comments :
It contains the text that is added for information which has to be ignored.

Syntax:-

<% -- JSP Comments %>

5. JSP Directives
Finally, let us introduce one more JSP tag, the directive. In general terms, directives instruct
the compiler how to process a JSP program. Examples include the definition of our own tags,
including the source code of other files, and importing packages. The syntax for directives is as
follows:

Programming Technology © Er. Shiva Ram Dam, 2019 153


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

<%@
page import="java.util.*,java.sql.*"
%>

10.4.3. A Simple JSP program


Save the below as Demo.jsp and place it into the root directory under web-apps in Tomcat
directory (i.e. C:\Program Files (x86)\Apache Software Foundation\Tomcat 9.0\webapps\ROOT)

<html>
<title>
Displaying Heading Tags with JSP
</title>
<body>

<%!
private static final int LASTLEVEL = 6;
%>

<p>
This page uses JSP to display Heading Tags from
Level 1 to Level <%= LASTLEVEL %>
</p>
<%
int i;
for (i = 1; i <= LASTLEVEL; i++)
{
out.println("<H" + i + ">" +
"This text is in Heading Level " + i +
"</H" + i + ">");
}
%>
</body>
</html>

Now start Tomcat and open web-browser and navigate as: http://localhost:8080/Demo.jsp
The output observed is :

154 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

10.4.4 Handling Parameters in JSP


To make a JSP page more interactive, we can read and process the data entered in an HTML
form.
One way to read these values is to call the request.getParameter() method.This method takes a
String parameter as input that identifies the name of an HTML form element and returns the value
entered by the user for that element on the form.
For example, if there is a textbox named AuthorID, then we can retrieve the value entered in that
textbox with the following scriptlet code:
String value = request.getParameter("AuthorID");
If the user leaves the field blank, then getParameter returns an empty string.

Create a new Test.html file and save in the ROOT folder of Tomcat. This Html file uses a
EditURL.jsp in order to process request.
<html>
<head>
<title>Change Author's URL</title>
</head>
<body>
<h1>Change Author's URL</h1>
<p>
Enter the ID of the author you would like to change
along with the new URL.
</p>
<form ACTION = "EditURL1.jsp" METHOD = POST>
Author ID:
<input TYPE = "TEXT" NAME = "AuthorID" VALUE = "" SIZE = "4"
MAXLENGTH = "4">
<br/>
New URL:
<input TYPE = "TEXT" NAME = "URL"
VALUE = "http://" SIZE = "40" MAXLENGTH = "200">
<p>
<input type=submit value="Submit">
</p>
</form>
</body>
</html>

Also create another EditURL.jsp file and place it also in the ROOT folder of Tomcat. This JSP
program echoes back the data entered by the user in above html. To be careful, the name of the
JSP file must match the value supplied for the ACTION tag of the form.

<html>
<title>Edit URL: Echo submitted values</title>
<body>
<h2>Edit URL</h2>
<p>
This version of EditURL.jsp simply echoes back to the
user the values that were entered in the textboxes.
</p>
<%
String url = request.getParameter("URL");
String stringID = request.getParameter("AuthorID");
int author_id = Integer.parseInt(stringID);

Programming Technology © Er. Shiva Ram Dam, 2019 155


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

out.println("The submitted author ID is: " + author_id);


out.println("<br/>");
out.println("The submitted URL is: " + url);
%>
</body>
</html

Result:

Assignment:
Give the HTML to create a form with two elements: a textbox named FirstName that holds a
maximum of 50 characters, a Submit button. The form should submit its data to a JSP program
called Process.jsp using the POST method. Also, write the process.jsp to handle these requests.

10.4.4 JSP Implicit Objects


JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in
each page and developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables. JSP supports nine Implicit Objects which are listed
below:

1. The request object


The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time
a client requests a page the JSP engine creates a new object to represent that request. The
request object provides methods to get HTTP header information including form data, cookies,
HTTP methods etc.

156 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

2. The response object


The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as
the server creates the request object, it also creates an object to represent the response to the
client. The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP
status codes etc.

3. The out object


The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to
send content in a response. The initial JspWriter object is instantiated differently depending on
whether the page is buffered or not. Buffering can be easily turned off by using the
buffered='false' attribute of the page directive. The JspWriter object contains most of the same
methods as the java.io.PrintWriter class. However, JspWriter has some additional methods
designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.

4. The session object


The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the
same way that session objects behave under Java Servlets. The session object is used to
track client session between client requests.

5. The application object


The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object. This object is a
representation of the JSP page through its entire lifecycle. This object is created when the JSP
page is initialized and will be removed when the JSP page is removed by the jspDestroy()
method.

6. The config object


The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper
around the ServletConfig object for the generated servlet. This object allows the JSP
programmer access to the Servlet or JSP engine initialization parameters such as the paths or
file locations etc.

7. The pageContext object


The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The
pageContext object is used to represent the entire JSP page. This object is intended as a
means to access information about the page while avoiding most of the implementation details.
This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this object.

8. Page object
The Page object is an actual reference to the instance of the page. It can be thought of as an
object that represents the entire JSP page. The page object is really a direct synonym for the
this object.

9. The exception object


The exception object is a wrapper containing the exception thrown from the previous page. It
is typically used to generate an appropriate response to the error condition.

10.5. Introduction to JSP tag library


JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications. JSTL has support for common,
structural tasks such as iteration and conditionals, tags for manipulating XML documents,
internationalization tags, and SQL tags. It also provides a framework for integrating existing
custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library groups
that can be used when creating a JSP page:

Programming Technology © Er. Shiva Ram Dam, 2019 157


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

1. Core Tags
2. Formatting tags
3. SQL tags
4. XML tags
5. JSTL Functions

1. Core Tags
The core group of tags is the most frequently used JSTL tags. Following is the syntax to
include JSTL Core library in our JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2. Formatting tags

The JSTL formatting tags are used to format and display text, the date, the time, and numbers
for internationalized Web sites.
Following is the syntax to include formatting library in our JSP:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

158 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

3. SQL tags
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as
Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in our JSP:

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

4. XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
Following is the syntax to include JSTL XML library in our JSP. The JSTL XML tag library has
custom tags for interacting with XML data. This includes parsing XML, transforming XML data,
and flow control based on XPath expressions.

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

Programming Technology © Er. Shiva Ram Dam, 2019 159


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

5. JSTL Functions

JSTL includes a number of standard functions, most of which are common string manipulation
functions.
Following is the syntax to include JSTL Functions library in our JSP:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

10.6. Session Management in JSP


Session Handling becomes mandatory when a requested data need to be sustained for further
use. Since http protocol considers every request as a new one, session handling becomes
important.
The session object is used to track a client session between client requests.
JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to
identify a user across:
• a one-page request or
• visit to a website or
• store information about that user

Following are some of the methods to handle session:


• In JSP whenever a request arises the server generates a unique Session ID which is
stored in the client machine.
• Cookies store the information in the client browser
• URL rewriting the session information is appended to the end of the URL
• Hidden form fields the sessionID is embedded to GET and POST command.

160 Programming Technology © Er. Shiva Ram Dam, 2019


10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

Save the below file as session.jsp at ROOT directory of webapps in Tomcat.


<%@ page import="java.io.*,java.util.*" %>
<%
//Get session creation time and last Access time
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back";


Integer visitCount = new Integer(0);
String visitCountKey = "visitCount";
String userIDKey = new String("userID");
String userID = new String("Java2s_ID");

// Check if this is new comer on your Webpage.


if (session.isNew()){
title = "Welcome";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<body>
id:<% out.print( session.getId()); %><br/>
Creation Time:<% out.print(createTime); %><br/>
Time of Last Access:<% out.print(lastAccessTime); %><br/>
User ID:<% out.print(userID); %>
Number of visits:<% out.print(visitCount); %><br/>
</body>
</html>

Output:

Assignment:
Differentiate between JSP and Servlet.

Reference: for more study:


https://www.youtube.com/watch?v=bd50C6XUnFw
https://www.wisdomjobs.com/e-university/adv-java-tutorial-227/the-javax-dot-servlet-dot-http-package-6187.html

Exam Questions:
1. What is JSP tag library? Explain about session management. How many techniques are in
session management? [2018 spring]
2. Explain JSP and servlet. What are the advantages of JSP? [2018 fall]
Programming Technology © Er. Shiva Ram Dam, 2019 161
10. JAVA SERVER PAGES (JSP) SEVER TECHNOLOGY

3. Define JavaServer Pages Standard Tag Library JSTL0 and Http Session Interface. Explain
JSP Life Cycle. [2018 Fall]
4. Define JSP and Servlets. How are servlets created and deployed? Explain with an illustration.
[2017 fall]
5. What are the session management techniques available in JSP? Explain briefly. [2017 spring]
6. Explain HTTP requests handling and session management in JSP. [2016 fall]
7. Explain about the life cycle of JSP with a neat diagram. [2016 fall]
8. Write a JSP application that submits the basic student registration form to another page called
processRegister.jsp which should display all the records. [2016 fall]
9. Explain Servlet Life Cycle and How can you deploy Servlet in Java. [2016 spring]
10. Give the HTML to create a form with two elements: a textbox named FirstName that holds a
maximum of 50 characters, a Submit button. The form should submit its data to a JSP program
called Process.jsp using the POST method. Also, write the Process.jsp to handle these
requests. [2016 spring, 2014 fall]
11. What are the uses of session? How is it managed in JSP? Explain with example. [2015 spring]
12. Write a code for following example using Servlet:

Username

Password

Submit Reset

13. What are uses of sessions? How is it managed in JSP? Explain with examples. [2015 fall]
14. What is JSP and Servlet technology? Explain in brief about the advantages of Servlet over the
CGI technology. [2014 spring]
15. What are the interfaces of HTTP request handling? Mention each with their name and short
description. Explain in brief about servlet life cycle. [2014 spring]
16. How does JSP differ with Java Servlet? Explain the life cycle of JSP. [2014 fall]
17. Explain JSP core tags, formatting tags, XML tags and SQL tags with suitable examples.
Illustrate. [2013 spring]
18. Define session and how do we manage session in Servlet? [2013 spring]
19. Write short notes on:
a. JSP syntax [2018 spring]
b. Session Management [2017 fall]
c. Servlet Life Cycle [2017, 2015 spring]
d. JSP [2015 spring]

***

162 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

11. Database Handling [Credit: 5 hrs]

11.1. Introduction to Database


A database is an organized collection of data. There are many different strategies for organizing
data to facilitate easy access and manipulation. A database management system (DBMS) provides
mechanisms for storing, organizing, retrieving and modifying data for many users. Database
management systems allow for the access and storage of data without concern for the internal
representation of data.
Some popular relational database management systems (RDBMSs) are Microsoft SQL Server,
Oracle, Sybase, IBM DB2, Informix, PostgreSQL and MySQL. The JDK now comes with a pure-
Java RDBMS called Java DB-Oracles’s version of Apache Derby.

11.2. Server side database drivers and tools: JDBC, ODBC, SQL
JDBC and ODBC, both are the API (Application Programming Interface) that help the applications
on the client side to access the database on the server side. The RDBMS vendors provide ODBC
or JDBC drivers so that their database can be accessed by the applications on client side. The
point that fundamentally differentiates JDBC and ODBC is that JDBC is language dependent and it
is Java specific whereas, the ODBC is a language independent.

11.2.1. JDBC
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.
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 java.sql package contains classes and interfaces for JDBC API.
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). Most popular database management systems now provide
JDBC drivers. There are also many third-party JDBC drivers available.
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.

Figure: JDBC-to-database communication path

Programming Technology © Er. Shiva Ram Dam, 2019 163


11. DATABASE HANDLING

The JDBC consists of two layers. The top layer is the JDBC API. This API communicates with the
JDBC manager driver API, sending it the various SQL statements. The manager should
communicate with the various third-party drivers that actually connect to the database and return
the information from the query or perform the action specified by the query.

11.2.1. ODBC
Microsoft introduced ODBC in the year 1992. Open Database Connectivity (ODBC) is an interface
standard for accessing data and communicating with database systems, regardless of the
operating system (OS), database system (DS) or programming language. This is accomplished by
using ODBC drivers that serve as a bridge between applications and database systems.

Figure: ODBC Architecture

The functionality of ODBC involves the insertion of a middle layer, called a database driver,
between an application and the DBMS. The purpose of the database driver is to translate the
application’s data queries into commands that the DBMS understands. To access an ODBC
database, you must have the appropriate ODBC driver for the database you wish to access. To
access data provided by a data source, a connection to the data source must first be established.
All data access is managed through that connection.

11.2.2. JDBC drivers


JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1. JDBC-ODBC bridge driver (Type 1)


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.

164 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

2. Native-API driver (partially java driver)(Type 2)


The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3. Network Protocol driver (fully java driver) (Type 3)


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

Programming Technology © Er. Shiva Ram Dam, 2019 165


11. DATABASE HANDLING

4. Thin driver (fully java driver) (Type 4)


The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.

Most database vendors supply either a type 3 or type 4 drivers with their database. Furthermore, a
number of third-party companies specialize in producing drivers with better standards
conformance, support for more platforms, better performance, or, in some cases, simply better
reliability than the drivers that are provided by the database vendors.
In summary, the ultimate goal of the JDBC is to make possible the following:
• Programmers can write applications in the Java programming language to access any
database, using standard SQL statements or even specialized extensions of SQL-while
still following Java language conventions.
• Database vendors and database tool vendors can supply the low-level drivers. Thus, they
can optimize their drivers for their specific products.

11.2.3. Typical uses of JDBC


We can use JDBC in both applications and applets. In an applet, all the normal security restrictions
apply. By default, the security manager assumes that all applets written in the Java programming
language are untrusted.
In particular, applets that use JDBC are only able to open a database connection to the server from
which they are downloaded. That means the Web server and the database server must be the
same machine, which is not a typical setup. Of course, the Web server can have a proxy service
that routes database traffic to another machine. With signed applets, this restriction can be
loosened.
Applications, on the other hand, have complete freedom to access remote database servers. If we
implement a traditional client/server program, it probably makes more sense to use an application,
not an applet, for database access.

166 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

However, the world is moving away from client/server and toward a "three-tier model" or even
more advanced "n-tier models." In the three-tier model, the client does not make database calls.
Instead, it calls on a middleware layer on the server that in turn makes the database queries. The
three-tier model has a couple of advantages. It separates visual presentation (on the client) from
the business logic (in the middle tier) and the raw data (in the database). Therefore, it becomes
possible to access the same data and the same business rules from multiple clients, such as a
Java application or applet or a web form.
Communication between the client and middle tier can occur through HTTP (when we use a web
browser as the client), RMI (when we use an application or applet), or another mechanism. JDBC
is used to manage the communication between the middle tier and the back-end database.
Following figure shows the basic architecture.

Figure: 3-Tier Architecture

SQL is the industry-standard approach to accessing relational databases. JDBC supports SQL, enabling
developers to use a wide range of database formats without knowing the specifics of the underlying
database. JDBC also supports the use of database queries specific to a database format.
The JDBC class library’s approach to accessing databases with SQL is comparable to existing database-
development techniques, so interacting with an SQL database by using JDBC isn’t much different than using
traditional database tools. Java programmers who already have some database experience can hit the ground
running with JDBC. The JDBC library includes classes for each of the tasks commonly associated with
database usage:
• Making a connection to a database
• Creating a statement using SQL
• Executing that SQL query in the database
• Viewing the resulting records
These JDBC classes are all part of the java.sql package.

11.2.4. Database Drivers


Java programs that use JDBC classes can follow the familiar programming model of issuing SQL
statements and processing the resulting data. The format of the database and the platform it was
prepared on do not matter.
A driver manager makes the platform and database independence possible. The classes of the
JDBC class library are largely dependent on driver managers , which keep track of the drivers
required to access database records. We’ll need a different driver for each database format that’s
used in a program, and sometimes we might need several drivers for versions of the same format.
Java DB includes its own driver. JDBC also includes a driver that bridges JDBC and another
databaseconnectivity standard, ODBC.
The JDBC-ODBC bridge allows JDBC drivers to be used as ODBC drivers by converting JDBC
method calls into ODBC function calls.
Using the JDBC-ODBC bridge requires three things:
• The JDBC-ODBC bridge driver included with Java: sun.jdbc.odbc.JdbcOdbcDriver
• An ODBC driver
• An ODBC data source that has been associated with the driver using software such as the
ODBC Data Source Administrator.

Programming Technology © Er. Shiva Ram Dam, 2019 167


11. DATABASE HANDLING

11.3. Creating connection to database


Following Figure lists the JDBC driver names and database URL formats of several popular
RDBMSs.

Fig: Popular JDBC database URL formats

The getConnection() method of DriverManager class is used to establish connection with the
database, which attempts to connect to the database specified by its URL.

Syntax:
Connection ConnectionObject =DriverManager.getConnection(
“jdbc:<subprotocol>:<subname>”, “Username”, “password”
Eg:
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:myDatabase","system","password");
Where:
con is a connection object. It enables program to create SQL statements that manipulate
databases.
The URL locates the database (possibly on a network or in the local file system of the
computer).
The URL "jdbc:oracle:thin:@localhost:1521:myDatabase" specifies the protocol for
communication (jdbc), the sub protocol for communication ( oracle) and the location of the
database (//localhost:1521:myDatabase, where localhost is the host running the Oracle server
, 1521 is default Oracle running port and myDatabase is the database name).
Method getConnection() takes three arguments-a String that specifies the database URL, a
String that specifies the username and a String that specifies the password.
An exception handling mechanism is required for data connection. If the DriverManager cannot
connect to the database, method getConnection throws a SQLException (package java.sql).

168 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

11.4. Java Database Connectivity (Steps)


There are 5 steps to connect any java application with the database using JDBC. These steps are:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection

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.
Eg:
Class.forName("oracle.jdbc.driver.OracleDriver");

2. Create connection
The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax:
“jdbc:<subprotocol>:<subname>”, “Username”, “password”
Eg:
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:myDatabase","system","password");

3. Create statement
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Eg:
Statement stm=con.createStatement();
4. Execute queries
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.
Eg:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next( ))
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5. Close connection
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Eg:
con.close( );

Programming Technology © Er. Shiva Ram Dam, 2019 169


11. DATABASE HANDLING

Sample program 1:
WAP in Java to display all the data from the EMPLOYEE table in Oracle database.

import java.sql.*;
public class OracleCon
{
public static void main(String args[]){
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:myDatabase","admin","admin");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


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

//step5 close the connection object


con.close();

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

170 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

Sample program 2:
WAP in Java to select the Auth_ID, Auth_FName, Auth_LName, Auth_Address and
Auth_PhoneNo form table “AuthorDetail” of “Writer” database and display the content in console.
//Saved as DisplayAuthor.java
import java.sql.*;
import java.util.* ;
public class DisplayAuthor
{
public static void main( String args[] )
{
try
{
//Register the database driver
Class.forName("com.mysql.jdbc.Driver");

// create the connection object


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/writer", "root", " " );

// create the statement object


Statement stm = con.createStatement();

// execute query
ResultSet rst = stm.executeQuery(
"SELECT Auth_ID, Auth_FName, Auth_LName, Auth_Address,Auth_PhoneNo FROM
AuthorDetail");

// process query results


ResultSetMetaData mtd = rst.getMetaData();
int numberOfColumns = mtd.getColumnCount();

System.out.println( "Authors Table of Writer Database:\n" );

for ( int i = 1; i <= numberOfColumns; i++ )


{
System.out.printf( "%-8s\t", mtd.getColumnName( i ) );
}
System.out.println();

while ( rst.next() )
{
for ( int i = 1; i <= numberOfColumns; i++ )
{
System.out.printf( "%-8s\t", rst.getObject( i ) );
}
System.out.println();
}

rst.close();
stm.close();
con.close();

catch ( SQLException sq )
{
sq.printStackTrace();
}
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 171


11. DATABASE HANDLING

Sample Program 3:
For the table given below, write SQL statements for performing the following task, and also write
Java program.
a. Create the table “student”.
b. Insert one row with values for each field.
c. Display name, address and DOB for the person whose DOB is greater than 2000.
ID Name Address Gender DOB
1 Ram Pokhara Male 2002
2 Gita Kathmandu Female 1995

SQL statements for table creation and data insertion:

CREATE database IF NOT EXISTS myDatabase;

USE myDatabase;

DROP TABLE if exists Student;

CREATE TABLE Student (


id int NOT NULL,
name varchar (50),
address varchar(50),
gender varchar(20),
dob varchar(20),
primary key (id));

INSERT into Student values (001, 'Ram', 'Pokhara', ‘Male’, 2002);


INSERT into Student values (002, 'Ram', 'Kathmandu', ‘Female’, 1995);

SELECT name, address, dob FROM Students WHERE dob>2000;

If Java program asked:

//saved as DataAccessExample.java

//1. Import the packages

import java.sql.*;

public class DataAccessExample


{
public static void main(String args[])
{
Connection conn=null;
Statement stmt=null;

try
{

//2. Register the database driver


Class.forName("com.mysql.jdbc.Driver");

//3. Connect the database layer

172 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

conn=DriverManager.getConnection("jdbc:mysql://localhost/myDatabase","root",
"root");

//4. Create and run query


stmt=conn.createStatement();
String sql;
sql="SELECT name, address, dob FROM Students WHERE dob>2000";
ResultSet rs=stmt.executeQuery(sql);

//5. Retrieve data from the resultset


System.out.println("Results:");

while (rs.next())
{
String name= rs.getString("name");
String address= rs.getString("address");
int dob=rs.getInt("dob");

//now displaying data values


System.out.println("Name:"+name);
System.out.println("Address:"+address);
System.out.println("DOB:"+dob);
}

//6. Releasing resources


rs.close();
stmt.close();
conn.close();
}

catch(Exception e)
{
e.printStackTrace();
}
}
}

11.5. Creating statement for executing queries


The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Connection objects can be used to create statement objects. A Connection method
createStatement( ) is used to obtain an object that implements interface Statement (package
java.sql). The program uses the Statement object to submit SQL statements to the database.

Eg:

Statement stm=con.createStatement( );

Where:
stm and con are objects of Statement and Connection
createStatement() is a method.

Programming Technology © Er. Shiva Ram Dam, 2019 173


11. DATABASE HANDLING

11.5.1 Types of JDBC statements


While working with database, we can use different types of statements. The JDBC provides
different interfaces for this purpose. They are: Statement, CallableStatement, and
PreparedStatement interfaces. These interfaces define the methods and properties which facilitate
us to send database commands and obtain data from the database. Furthermore, these interfaces
helps to deal with datatype incompatibility between Java and the datatype used.

Following table provides a summary of each interface’s purpose to decide on the interface to use.

S.No. Interface Description


1. Statement • It is used for general –purpose access to the database.
• Useful when we are using static SQL statements at runtime.
• The Statement interface cannot accept parameters.
2. PreparedStatement • It is preferable when SQL statements are used many times.
• The PreparedStatement interface accepts input parameters at
runtime.
3. CallableStatement • It is preferable when we use the database stored procedures.
• The CallableStatement interface can also accept input
parameters at runtime.

1. Statement
Used to implement simple SQL statements with no parameter.

Eg;

statement = connection.createStatement();

2. PreparedStatement
Extends Statement
Used for precompiling SQL statements that might contain input parameters.
Eg:
PreparedStatement pstmt = null;
String SQL = " SELECT authorID, firstName, lastName FROM authors ";
pstmt = conn.prepareStatement(SQL);

3. CallableStatement
Extends PreparedStatement.
Used to execute stored procedures that may contain both input and output parameters.

Suppose we have a store procedure getAuthor in MySql to retrieve authors.

DELIMITER $$
DROP PROCEDURE IF EXISTS getAuthor $$
CREATE PROCEDURE getAuthor
(OUT authorID int, OUT FirstName VARCHAR(255), OUT LastName VARCHAR(255))
BEGIN
SELECT authorID, firstName, lastName FROM authors;
END $$

In order to call those store procedure in program.

CallableStatement cs = null;
cs = this.conn.prepareCall("{call getAuthor()}");
ResultSet rs = cs.executeQuery();

174 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

Three types of parameters exist: IN, OUT, and INOUT

11.5.2 Operations with ResultSet


A ResultSet is a Java object that contains the results of executing an SQL query. In other words, it
contains the rows that satisfy the conditions of the query.
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
The data stored in a ResultSet object is retrieved through a set of get methods that allows access
to the various columns of the current row. The ResultSet.next( ) method is used to move to the
next row of the ResultSet, making it the current row.
The general form of a result set is a table with column headings and the corresponding values
returned by a query. For example, if your query is SELECT a, b, c FROM Table1, our result set will
have the following form:

a b c
---------- ------------ -----------
123 Bikash 20500.25
456 Ramesh 30600.75
567 Manashi 50800.45

The following code fragment is an example of executing an SQL statement that will return a
collection of rows, with column a as an int, column b as a String, and column c as a float:

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
// retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}

Reference for MySQL installation:


https://www.youtube.com/watch?v=WuBcTJnIuzo

For downloading MySQL:


https://dev.mysql.com/downloads/file/?id=487685

Programming Technology © Er. Shiva Ram Dam, 2019 175


11. DATABASE HANDLING

11.6. JDBC vs ODBC


S.No. Basis JDBC ODBC

1. Definition Java Database Community (JDBC) Open Database Connectivity (ODBC)


is basically an application is basically a standard application
programming interphase for the programming interphase for
Java programming language to communicating and accessing
determine the client’s database database management systems
access features

2. Architecture The basic JDBC architecture The ODBC architecture mainly


supports both two-tier and three consists of four components viz. The
tire layer processing DB models driver, Driver Manager, API, and Data
but mainly it consists of two layers Source
of architecture viz. JDBC API and
JDBC Driver API

3. Simplicity In case of JDBC, coding is the In the case of ODBC, it handles


initial step of programming different complex situations and
complex queries and it is easier queries to produce the proper
than programming machine level outputs. So, it is
basically an advanced version of
coding and other different
approaches. Thus, it is much more
complex than JDBC

4. Language Being implemented on Java, JDBC In the case of ODBC, it can be


dependency can only be enhanced and implemented for any languages viz.
implemented on java languages C, C++, Java etc.

5. Platform In the case of JDBC, it can be In the case of ODBC, it can be


dependency executed on any platforms executed only in windows based
platforms

6. Mode of In the case of JDBC, it mainly runs In the case of ODBC, it is mainly
Operation on the Java Programming implemented on Visual Basic
language and can be compiled language and thus the code needs to
directly at the runtime be interpreted and then it can be
executed

7. Security In the case of JDBC, since users In the case of ODBC, being more
normally don’t have access to the user interactive server it is prone to
core system settings, hence the user errors. Thus, from the security
violations and security gaps can be perspective, JDBC would be a better
corrected quickly choice

8. Support There is also a lot of community Although it is costly, they provide a


support for JDBC and its users. larger range of community and paid
support. Normally all the ODBC
versions use to provide long-term
customer support

176 Programming Technology © Er. Shiva Ram Dam, 2019


11. DATABASE HANDLING

Exam Questions:
1. Why JDBC driver is required to connect java application to database? WAP in Java to select
the Auth_ID, Auth_FName, Auth_LName, Auth_Address and Auth_ PhoneNo from the table
Author Detail of Writer database and display the content in console. [2018 spring]
2. What is ResultSet? How can you use ResultSet in database application? [2018 spring]
3. What are the APIs to connect database in java? Write the advantages of API. [2018 fall]
4. Illustrate with an example, how database is connected using JDBC. [2017 fall]
5. How to connect the Database in Java, discuss with code snippets. [2017 spring]
6. Define server side database. Explain the types of Server side database drives and tools. [2016
fall]
7. What are the types of JDBC statements available? Explain with example. [2016 spring]
8. What is JDBC? Explain different drivers used in JDBC. [2015 spring]
9. How can you access data from database server to your application using JAVA where
database name is db_Inventory and table is tbl_Customer? [2015 fall]
10. Differentiate between JDBC and ODBC. For the table given below, write SQL statements for
performing the following task: [2014 spring]
a. Create the table “student”.
b. Insert one row with values for each field.
c. Display name, address and DOB for the person whose DOB is greater than 2000.
ID Name Address Gender DOB
1 Ram Pokhara Male 2002
2 Gita Kathmandu Female 1995

11. What are the types of JDBC statements available? Explain with example. [2014 fall]
12. Illustrate with code how JDBC is used to connect the program with the database. [2014 fall]
13. Differentiate JDBC with ODBC. [2013 spring]
14. Explain the process of JDBC-to-database communication path. Show the Java connection
code to connect database using JDBC driver. [2013 spring]
15. Write short notes on:
a. Server side database drivers. [2017 fall]
b. Steps for connecting database in JDBC [2015 spring]

***

Programming Technology © Er. Shiva Ram Dam, 2019 177


11. DATABASE HANDLING

Database Connection Sample: Step by Step


1. Create a database MyDatabase in Ms-Access.
2. Open Ms-Access> blank>database> MyDatabase
3. Create a table: “Info”.
4. Put the attributes as:

5. Write the code as;


6. For mapping the database;
7. My computer>File> control panel> Administrative tools> ODB-DataSource (32 bits)>System
DSN> Add>
8. Select Microsoft Access Driver (*mdb, *accb) >Finish.
9. Data Source Name: MyDatbase
10. Select the database in the Directories (i.e. in the desktop here)
11. Ok
12. Ok

178 Programming Technology © Er. Shiva Ram Dam, 2019


Project 1: Building Calculator using swing in Java

1. Simple Calculator
Steps:
1. Create a new java project Mycalculator
2. Right click MyCalculator >Java > others> Window Builder> Swing Designer> Application
Window
3. Give the form Name as Firstcalculator and Package as Firstcalculator
4. You will get a code window as:

Click the Design tab. You will get as below:

5. Design the calculator as shown above.

Programming Technology © Er. Shiva Ram Dam, 2019 179


Project 1: Building Calculator using swing in Java

6. Click on Absolute Layout and Click on the form. You do not need to drag.
7. Click on JTextField and put it in the form as:

Change the properties as:


Variable : txtDisplay
Font : Tahoma 20 Bold

8. Click JButton and put it on the form. Change the properties of this button:
Variable : btn7
Text :7
Font : Tahoma 20 Bold

9. Similary Design the form as below:

180 Programming Technology © Er. Shiva Ram Dam, 2019


Project 1: Building Calculator using swing in Java

In the properties; make as :


For Controls Variable Text Font
JTextField txtDisplay
JButton btn9 9 Tahoma 20 Bold
JButton btn8 8 Tahoma 20 Bold
JButton btn7 7 Tahoma 20 Bold
JButton btn6 6 Tahoma 20 Bold
JButton btn5 5 Tahoma 20 Bold
JButton btn4 4 Tahoma 20 Bold
JButton btn3 3 Tahoma 20 Bold
JButton btn2 2 Tahoma 20 Bold
JButton btn1 1 Tahoma 20 Bold
JButton btn0 0 Tahoma 20 Bold
JButton btnDot Tahoma 20 Bold
.
JButton btnPlusMinus +- Tahoma 20 Bold
JButton btnDivide / Tahoma 20 Bold
JButton btnMultiply * Tahoma 20 Bold
JButton btnMinus - Tahoma 20 Bold
JButton btnPlus + Tahoma 20 Bold
JButton btnBack CE Tahoma 20 Bold
JButton btnClear C Tahoma 20 Bold
JButton btnEqual = Tahoma 20 Bold

10. You will the source code as:

import java.awt.EventQueue;
………………………..
public class Cvacalculator {
private JFrame frame;
………………………………………………..
public static void main(String[] args) {
…………………………………………….
}
});
}

public Cvacalculator() {
initialize();
}
private void initialize() {
……………………………………………………..
………………………………………………………
btnPlus.setBounds(218, 294, 59, 59);
frame.getContentPane().add(btnPlus);
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 181


Project 1: Building Calculator using swing in Java

11. Right Click on Button 7 > Add Button Handler > action > action performed. You will get as
below:

JButton btn7 = new JButton("7");


btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

………………………………..
Write the code here..
………………………………..

}
});
btn7.setFont(new Font("Tahoma", Font.BOLD, 20));
btn7.setBounds(29, 91, 59, 59);
frame.getContentPane().add(btn7);

12. Write the below code in the “Write the code here..” part:

String EnterNumber =txtDisplay.getText() + btn7.getText();


txtDisplay.setText(EnterNumber);

13. Run the program, click 7 repeatedly, you will get it as:

14. Similarly, Double click on 8, and copy paste the code you wrote in step 12 and edit as:

btn8 = new JButton("8");


btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String EnterNumber =txtDisplay.getText() + btn8.getText();


txtDisplay.setText(EnterNumber);

}
});
btn8.setFont(new Font("Tahoma", Font.BOLD, 20));
btn8.setBounds(91, 91, 59, 59);
frame.getContentPane().add(btn8);

15. Similarly, do the step 14 for all other buttons: 9,4,5,6,1,2,3,0 and dot.

16. Run your application. You should be able to input all the digits:

182 Programming Technology © Er. Shiva Ram Dam, 2019


Project 1: Building Calculator using swing in Java

17. Change the alignment of the txtDisplay button as:

18. For the clear button C, Double click and write the shaded code as below:

btnClear = new JButton("C");


btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

txtDisplay.setText(null);

}
});
btnClear.setFont(new Font("Tahoma", Font.BOLD, 20));
btnClear.setBounds(285, 156, 59, 59);
frame.getContentPane().add(btnClear);

19. Declare global variables as:

public class Cvacalculator {

private JFrame frame;


private JTextField txtDisplay;

double firstnum;
double secondnum;
double result;
String operations;
String answer;

20. Double click on “/” button and write shaded code as:

btnDivide = new JButton("/");


btnDivide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");

Programming Technology © Er. Shiva Ram Dam, 2019 183


Project 1: Building Calculator using swing in Java

operations = "/";
}
});
btnDivide.setFont(new Font("Tahoma", Font.BOLD, 20));
btnDivide.setBounds(218, 91, 59, 59);
frame.getContentPane().add(btnDivide);

21. Similary, copy the above highlighted code and do it for x,+ and –buttons. The code goes as
below:

btnMultiply = new JButton("x");


btnMultiply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="x";
}
});
btnMultiply.setFont(new Font("Tahoma", Font.BOLD, 20));
btnMultiply.setBounds(218, 156, 59, 59);
frame.getContentPane().add(btnMultiply);

btnMinus = new JButton("-");


btnMinus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="-";
}
});
btnMinus.setFont(new Font("Tahoma", Font.BOLD, 20));
btnMinus.setBounds(218, 223, 59, 59);
frame.getContentPane().add(btnMinus);

btnPlus = new JButton("+");


btnPlus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="+";
}
});
btnPlus.setFont(new Font("Tahoma", Font.BOLD, 20));
btnPlus.setBounds(218, 294, 59, 59);
frame.getContentPane().add(btnPlus);

22. Now for +- button, Double click on it and write the code as below:

btnPlusMinus = new JButton("+-");


btnPlusMinus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double ops=Double.parseDouble(String.valueOf(txtDisplay.getText()));
ops=ops*(-1);
txtDisplay.setText(String.valueOf(ops));
}
});
btnPlusMinus.setFont(new Font("Tahoma", Font.BOLD, 20));
btnPlusMinus.setBounds(154, 294, 59, 59);

184 Programming Technology © Er. Shiva Ram Dam, 2019


Project 1: Building Calculator using swing in Java

frame.getContentPane().add(btnPlusMinus);

23. Double click the CE button and code as below:

btnBack = new JButton("CE");


btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String backspace=null;

if(txtDisplay.getText().length()>0){
StringBuilder strB= new StringBuilder(txtDisplay.getText());
strB.deleteCharAt(txtDisplay.getText().length()-1);
backspace=strB.toString();
txtDisplay.setText(backspace);
}

}
});
btnBack.setFont(new Font("Tahoma", Font.BOLD, 20));
btnBack.setBounds(285, 91, 59, 59);
frame.getContentPane().add(btnBack);

24. Double click the = button and code as below:

btnEqual = new JButton("=");


btnEqual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String answer;
secondnum=Double.parseDouble(txtDisplay.getText());
if (operations=="+")
{
result=firstnum+secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}
else if (operations=="-")
{
result=firstnum-secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}
else if (operations=="x")
{
result=firstnum*secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}
else if (operations=="/")
{
result=firstnum/secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}

}
});
btnEqual.setFont(new Font("Tahoma", Font.BOLD, 20));
btnEqual.setBounds(285, 223, 54, 130);
frame.getContentPane().add(btnEqual);

Programming Technology © Er. Shiva Ram Dam, 2019 185


Project 1: Building Calculator using swing in Java

25. The complete code for this calculator project is as:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;

public class Cvacalculator {

private JFrame frame;


private JTextField txtDisplay;

double firstnum;
double secondnum;
double result;
String operations;
String answer;

private JButton btn8;


private JButton btn9;
private JButton btnDivide;
private JButton btnBack;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btnMultiply;
private JButton btnClear;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btnMinus;
private JButton btnEqual;
private JButton btn0;
private JButton btnDot;
private JButton btnPlusMinus;
private JButton btnPlus;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Cvacalculator window = new Cvacalculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
186 Programming Technology © Er. Shiva Ram Dam, 2019
Project 1: Building Calculator using swing in Java

public Cvacalculator() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 380, 436);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

txtDisplay = new JTextField();


txtDisplay.setHorizontalAlignment(SwingConstants.RIGHT);
txtDisplay.setFont(new Font("Tahoma", Font.BOLD, 20));
txtDisplay.setBounds(29, 19, 315, 53);
frame.getContentPane().add(txtDisplay);
txtDisplay.setColumns(10);

// first row

JButton btn7 = new JButton("7");


btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String EnterNumber =txtDisplay.getText() +


btn7.getText();
txtDisplay.setText(EnterNumber);
}
});
btn7.setFont(new Font("Tahoma", Font.BOLD, 20));
btn7.setBounds(29, 91, 59, 59);
frame.getContentPane().add(btn7);

btn8 = new JButton("8");


btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String EnterNumber =txtDisplay.getText() +


btn8.getText();
txtDisplay.setText(EnterNumber);

}
});
btn8.setFont(new Font("Tahoma", Font.BOLD, 20));
btn8.setBounds(91, 91, 59, 59);
frame.getContentPane().add(btn8);

btn9 = new JButton("9");


btn9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber =txtDisplay.getText() +
btn9.getText();
txtDisplay.setText(EnterNumber);
}
});
btn9.setFont(new Font("Tahoma", Font.BOLD, 20));
btn9.setBounds(154, 91, 59, 59);
frame.getContentPane().add(btn9);

Programming Technology © Er. Shiva Ram Dam, 2019 187


Project 1: Building Calculator using swing in Java

btnDivide = new JButton("/");


btnDivide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="/";
}
});
btnDivide.setFont(new Font("Tahoma", Font.BOLD, 20));
btnDivide.setBounds(218, 91, 59, 59);
frame.getContentPane().add(btnDivide);

btnBack = new JButton("CE");


btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String backspace=null;

if(txtDisplay.getText().length()>0){
StringBuilder strB= new
StringBuilder(txtDisplay.getText());

strB.deleteCharAt(txtDisplay.getText().length()-1);
backspace=strB.toString();
txtDisplay.setText(backspace);
}

}
});
btnBack.setFont(new Font("Tahoma", Font.BOLD, 20));
btnBack.setBounds(285, 91, 59, 59);
frame.getContentPane().add(btnBack);

// Second row

btn4 = new JButton("4");


btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber =txtDisplay.getText() +
btn4.getText();
txtDisplay.setText(EnterNumber);
}
});
btn4.setFont(new Font("Tahoma", Font.BOLD, 20));
btn4.setBounds(29, 156, 59, 59);
frame.getContentPane().add(btn4);

btn5 = new JButton("5");


btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber =txtDisplay.getText() +
btn5.getText();
txtDisplay.setText(EnterNumber);
}
});
btn5.setFont(new Font("Tahoma", Font.BOLD, 20));
btn5.setBounds(91, 156, 59, 59);
frame.getContentPane().add(btn5);

btn6 = new JButton("6");


btn6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

188 Programming Technology © Er. Shiva Ram Dam, 2019


Project 1: Building Calculator using swing in Java

String EnterNumber =txtDisplay.getText() +


btn6.getText();
txtDisplay.setText(EnterNumber);
}
});
btn6.setFont(new Font("Tahoma", Font.BOLD, 20));
btn6.setBounds(154, 156, 59, 59);
frame.getContentPane().add(btn6);

btnMultiply = new JButton("x");


btnMultiply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="x";
}
});
btnMultiply.setFont(new Font("Tahoma", Font.BOLD, 20));
btnMultiply.setBounds(218, 156, 59, 59);
frame.getContentPane().add(btnMultiply);

btnClear = new JButton("C");


btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtDisplay.setText(null);

}
});
btnClear.setFont(new Font("Tahoma", Font.BOLD, 20));
btnClear.setBounds(285, 156, 59, 59);
frame.getContentPane().add(btnClear);

// Third row

btn1 = new JButton("1");


btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber =txtDisplay.getText() +
btn1.getText();
txtDisplay.setText(EnterNumber);
}
});
btn1.setFont(new Font("Tahoma", Font.BOLD, 20));
btn1.setBounds(29, 223, 59, 59);
frame.getContentPane().add(btn1);

btn2 = new JButton("2");


btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber =txtDisplay.getText() +
btn2.getText();
txtDisplay.setText(EnterNumber);
}
});
btn2.setFont(new Font("Tahoma", Font.BOLD, 20));
btn2.setBounds(91, 223, 59, 59);
frame.getContentPane().add(btn2);

btn3 = new JButton("3");


btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

Programming Technology © Er. Shiva Ram Dam, 2019 189


Project 1: Building Calculator using swing in Java

String EnterNumber =txtDisplay.getText() +


btn3.getText();
txtDisplay.setText(EnterNumber);
}
});
btn3.setFont(new Font("Tahoma", Font.BOLD, 20));
btn3.setBounds(154, 223, 59, 59);
frame.getContentPane().add(btn3);

btnMinus = new JButton("-");


btnMinus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="-";
}
});
btnMinus.setFont(new Font("Tahoma", Font.BOLD, 20));
btnMinus.setBounds(218, 223, 59, 59);
frame.getContentPane().add(btnMinus);

btnEqual = new JButton("=");


btnEqual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String answer;
secondnum=Double.parseDouble(txtDisplay.getText());
if (operations=="+")
{
result=firstnum+secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}
else if (operations=="-")
{
result=firstnum-secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}
else if (operations=="x")
{
result=firstnum*secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}
else if (operations=="/")
{
result=firstnum/secondnum;
answer=String.format("%.2f",result);
txtDisplay.setText(answer);
}

}
});
btnEqual.setFont(new Font("Tahoma", Font.BOLD, 20));
btnEqual.setBounds(285, 223, 54, 130);
frame.getContentPane().add(btnEqual);

// Last row

btn0 = new JButton("0");


btn0.addActionListener(new ActionListener() {

190 Programming Technology © Er. Shiva Ram Dam, 2019


Project 1: Building Calculator using swing in Java

public void actionPerformed(ActionEvent e) {


String EnterNumber =txtDisplay.getText() +
btn0.getText();
txtDisplay.setText(EnterNumber);
}
});
btn0.setFont(new Font("Tahoma", Font.BOLD, 20));
btn0.setBounds(29, 294, 59, 59);
frame.getContentPane().add(btn0);

btnDot = new JButton(".");


btnDot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber =txtDisplay.getText() +
btnDot.getText();
txtDisplay.setText(EnterNumber);
}
});
btnDot.setFont(new Font("Tahoma", Font.BOLD, 20));
btnDot.setBounds(91, 294, 59, 59);
frame.getContentPane().add(btnDot);

btnPlusMinus = new JButton("+-");


btnPlusMinus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double
ops=Double.parseDouble(String.valueOf(txtDisplay.getText()));
ops=ops*(-1);
txtDisplay.setText(String.valueOf(ops));
}
});
btnPlusMinus.setFont(new Font("Tahoma", Font.BOLD, 20));
btnPlusMinus.setBounds(154, 294, 59, 59);
frame.getContentPane().add(btnPlusMinus);

btnPlus = new JButton("+");


btnPlus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum=Double.parseDouble(txtDisplay.getText());
txtDisplay.setText("");
operations="+";
}
});
btnPlus.setFont(new Font("Tahoma", Font.BOLD, 20));
btnPlus.setBounds(218, 294, 59, 59);
frame.getContentPane().add(btnPlus);
}
}

26. Now run the program, your calculator is ready to be executed.


27. Build the jar file for your calculator.
28. Submit your Project-1, “Building Calculator in Java”.

Programming Technology © Er. Shiva Ram Dam, 2019 191


Project 1: Building Calculator using swing in Java

192 Programming Technology © Er. Shiva Ram Dam, 2019


Swing Programs in Java

Some Java Swing programs:


1. Write a simple program for handling event in Java.
Or
Write a simple program to handle mouse event in Java.
Or
Write a code for mouse event delegation model with your own example.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class EventHandlingDemo extends JFrame
{
//variable declaration

private JButton btnClick;

EventHandlingDemo () //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button

btnClick = new JButton("Click Here");


add(btnClick);

//handling the event generated when used clicks the button

btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Button Clicked");
}
});
}

public static void main(String[] args)


{
EventHandlingDemo ob= new EventHandlingDemo (); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 193


Swing Programs in Java

2. Write a java swing program with a button and display “Hello Java” when the button is clicked.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CaseConverter extends JFrame
{
//variable declaration

private JButton btnConvert;

CaseConverter() //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button

btnConvert = new JButton("Convert Case");


add(btnConvert);

//handling the event generated when used clicks the button

btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hello Java"); //displays Hello Java in Commmand prompt

}
});
}

public static void main(String[] args)


{
CaseConverter ob= new CaseConverter(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);

194 Programming Technology © Er. Shiva Ram Dam, 2019


Swing Programs in Java

}
}

3. Write a swing application with one close button when clicked should terminate the program.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ClickClose extends JFrame
{
//variable declaration

private JButton btnClose;

ClickClose() //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button
btnClose = new JButton("Close");
add(btnClose);

//handling the event generated when used clicks the button


btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0); //closes the window

}
});
}

public static void main(String[] args)


{
ClickClose ob= new ClickClose(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}
}

Programming Technology © Er. Shiva Ram Dam, 2019 195


Swing Programs in Java

4. WAP with a button; change the background color to green on clicking the button.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ChangeColor extends JFrame
{
//variable declaration

private JButton btnClick;

ChangeColor () //constructor here initializes the values when object created

{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//Creating a button

btnClick = new JButton("Change Background color");


add(btnClick);

//handling the event generated when used clicks the button

btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getContentPane().setBackground(Color.GREEN);
}
});
}

public static void main(String[] args)


{
ChangeColor ob= new ChangeColor(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(400, 400); //setting size of Jframe

ob.setVisible(true);
}

196 Programming Technology © Er. Shiva Ram Dam, 2019


Swing Programs in Java

5. Swing Application with two input boxes and a button which when clicked displays the result of two
string the textboxes to console after converting them into uppercase.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CaseConverter extends JFrame
{
//variable declaration

private JFrame frame;


private JTextField txtFirstString, txtSecondString;
private JLabel lblFirstString,lblSecondString;
private JButton btnChange;
private String result;

CaseConverter() //constructor here initializes the values when object created

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed

//creating label for First String

lblFirstString = new JLabel("First String"); //First Num appears in label

lblFirstString.setBounds(50, 50, 100, 20); //specifies x , y , width and height

add(lblFirstString); //adds the label

//Creating a textfield to get first String

txtFirstString = new JTextField();


txtFirstString.setBounds(200, 50, 150, 30);
add(txtFirstString);
txtFirstString.setColumns(10); // sets column size of 10

//creating label for Second String

Programming Technology © Er. Shiva Ram Dam, 2019 197


Swing Programs in Java

lblSecondString = new JLabel("Second Num");


lblSecondString.setBounds(50, 80, 100, 20);
add(lblSecondString);

//Creating a textfield to get second String

txtSecondString= new JTextField();


txtSecondString.setBounds(200, 80, 150, 30);
add(txtSecondString);
txtSecondString.setColumns(10);

//Creating a button

btnChange = new JButton("Add");


add(btnChange);

//handling the event generated when used clicks the button

btnChange.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String st1=txtFirstString.getText();
String st2=txtSecondString.getText();
result=st1+st2;
System.out.println(result.toUpperCase());
}
});
}

public static void main(String[] args)


{
CaseConverter ob= new CaseConverter(); //object creation

ob.setLayout(new FlowLayout()); //setting layout using FlowLayout object

ob.setSize(200, 200); //setting size of Jframe

ob.setVisible(true);
}
}

198 Programming Technology © Er. Shiva Ram Dam, 2019


Swing Programs in Java

6. WAP to create swing application to accept two numbers in two different textboxes form user and
display the sum in another textbox when user clicks the Add button.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Adder extends JFrame
{
//variable declaration

private JFrame frame;


private JTextField txtFirstNum, txtSecondNum, JTextField,txtSum;
private JLabel lblFirstNum, lblSecondNum, lblSum;
private JButton btnAdd;
private int n1,n2,sm;
private String answer;

Adder() //constructor here initializes the values when object created

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed


//creating label for First Number

lblFirstNum = new JLabel("First Num"); //First Num appears in label

lblFirstNum.setBounds(50, 50, 100, 20); //specifies x , y , width and height

add(lblFirstNum); //adds the label

//Creating a textfield to get first number

txtFirstNum = new JTextField();


txtFirstNum.setBounds(200, 50, 150, 30);
add(txtFirstNum);
txtFirstNum.setColumns(10); // sets column size of 10

//creating label for Second Number

lblSecondNum = new JLabel("Second Num");


lblSecondNum.setBounds(50, 80, 100, 20);
add(lblSecondNum);

//Creating a textfield to get second number

txtSecondNum = new JTextField();


txtSecondNum.setBounds(200, 80, 150, 30);
add(txtSecondNum);
txtSecondNum.setColumns(10);

Programming Technology © Er. Shiva Ram Dam, 2019 199


Swing Programs in Java

//Creating a label for Sum

lblSum = new JLabel("Sum");


lblSum.setBounds(50, 200, 100, 20);
add(lblSum);

//Creating a textfield to display sum

txtSum = new JTextField();


txtSum.setBounds(200, 200, 150, 30);
add(txtSum);
txtSum.setColumns(10);

//Creating a button

btnAdd = new JButton("Add");


add(btnAdd);

//handling the event generated when used clicks the button

btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
n1=Integer.parseInt(txtFirstNum.getText());
n2=Integer.parseInt(txtSecondNum.getText());
sm=n1+n2;
answer=String.format("%d",sm);
txtSum.setText(answer);
}
});
}

public static void main(String[] args)


{
Adder f= new Adder();
f.setLayout(new FlowLayout()); //setting layout using FlowLayout object
f.setSize(200, 200); //setting size of Jframe

f.setVisible(true);
}
}

200 Programming Technology © Er. Shiva Ram Dam, 2019


Course Plan-2020 Spring
Level: Bachelor Sub: Programming Technology
Faculty: Computer Lecturer: Er. Shiva Ram Dam
Semester: II/II Total Credit hours: 46
S.No. Chapter/ Topics Remarks
LESSON 1: INTRODUCTION (Credit: 3 hrs)

Day 1 1. Programming languages, Programming paradigms: POP,


OOP,
Day 2 2. Programming paradigms: AOP, SOP, IDE, Components of
Visual programming
Day 3 3. Application object, window object, view object,
document object
Day 4 4. Document view architecture, Virtual machines, Runtime
environment

LESSON 2: PROGRAMMING ARCHITECTURE (Credit: 3 hrs)

Day 5 1. MVC, N-tier Architecture


Day 6 2. Client-server Model
Day 7 3. Comparison of 2/3/N-tier architecture, Thin Vs Thick
clients

LESSON 4: .NET FRAMEWORK (Credit: 4 hrs)

Day 8 1. .net framework, CLR, CLS, CTS


Day 9 2. Base class library, intermediate language
Day 10 3. JIT, garbage collection, WCF, WPF

LESSON 3: ELEMENTS OF .NET LANGUAGES (Credit: 4 hrs)

Day 11 1. C# language, Tokens of C# programs


Day 12 2. C# statements, objects, classes,
Day 13 3. C# arrays and strings
Day 14 4. Programming session
Day 15 5. System collection, delegates and events
Day 16 6. Indexes, attributes, versioning
Day 17 7. .net librarires, I/O,namespace system, windows form

LESSON 5: WEB & DATABASE PROGRAMMING WITH .NET (Credit: 3 hrs)

Day 18 1. ASP, Seven key pillars, ASP lifecycle


Day 19 2. ASP.net and database application
Day 20 3. ADO.net
Day 21 4. Programming session
LESSON 6: JAVA FRAMEWORK (Credit: 2 hrs)

Day 22 1. Java language, JVM, JRE, JDK

LESSON 7: JAVA EXCEPTION HANDLING (Credit: 3 hrs)

Day 23 1. Exception and errors, Exception handling


Day 24 2. Try, catch, throw, throws and finally
Day 25 3. Debugging techniques, Tips on exception handling
Day 26 4. Streams, File Handling in Java

LESSON 8: APPLETS AND APPLICATION (Credit: 3 hrs)

Day 27 1. Applets, Applet architecture


Day 28 2. Applet lifecycle
Day 29 3. Parameters to applet, applet security policies

LESSON 9: EVENT, EVENT HANDLING & SWING (Credit: 5 hrs)

Day 30 1. Events, Event handling, Delegation Model


Day 31 2. Individual events , separating GUI and application code
Day 32 3. Advance event handling
Day 33 4. Swing, Building GUI with Swing
Day 34 5. Building application with swing

LESSON 10: JAVA SERVER PAGES (JSP)/ SERVER TECHNOLOGY (Credit: 7 hrs)

Day 35 1. JSP/Servlet Technology Overview


Day 36 2. Servlet Life Cycle, Creating and deploying new Servlet
Day 37 3. HTTP Request handling, Session Management
Day 38 4. JSP lifecycle, Writing JSP pages
Day 39 5. Introduction to JSP Tag library
Day 40 6. Practical session
Day 41 7. Practical session

LESSON 11: DATABASE HANDLING (Credit: 6 hrs)

Day 42 1. Sever-side database drivers and tools: JDBC, ODBC, SQL


Day 43 2. Creating database connection
Day 44 3. Creating statement, operations with ResultSet
Day 45 4. Types of statement, Data source objects and visual data
manipulation
Day 46 5. Efficient data accesses

You might also like