PT FullNote
PT FullNote
Technology
INTRODUCTION 1
1
PROGRAMMING ARCHITECTURE 13
2
.NET FRAMEWORK 55
4
JAVA FRAMEWORK 83
6
14 LAB WORKS
1. INTRODUCTION
Programmin
g Language
Low-level High-level
Object
Machine Assembly Procedural
oriented
• 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.
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
Assignment 5:
Mention the features, advantages and disadvantages of EOP
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
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.
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.
Advantages of VP
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.
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.
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.
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.
Reference: http://findbestvideos.blogspot.com/2009/11/documentview-fumdamentals.html
https://docs.microsoft.com/en-us/cpp/mfc/document-view-architecture?view=vs-2019
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.
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.
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***
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.
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.
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.
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.
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.
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.
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
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
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.
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/
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.
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
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]
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
• 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.
in interface
for foreach goto if implicit in (generic int
modifier)
Contextual Keywords
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.
Example:
char s, ch;
int a, b, c;
float pi, sal;
double percent;
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”
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':
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:
The following image shows how the system allocates the memory for the above string
variable.
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();
}
}
}
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
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
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.
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
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
2. Relational Operators
These operators perform basic comparisons. Following table shows all the relational operators
supported by C#.
> 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.
<= 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#.
&& Called Logical AND operator. Returns True if both (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 −
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 –
& Binary AND Operator copies a bit to the result (A & B) = 12, which is 0000
^ Binary XOR Operator copies the bit if it is set (A ^ B) = 49, which is 0011
in one operand but not both. 0001
5. Assignment Operators
There are following assignment operators supported by C# −
=C^2
6. Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? : supported by C#.
& Returns the address of an &a; returns actual address of the variable.
variable.
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");
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;
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();
}
}
}
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.
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;
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 };
Output:
Print array:
1
2
3
4
5
6
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.
• 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].
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.
Sample program:
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:
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;
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
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";
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:
class Test
{
static void Main(string[] args)
{
Program ob1=new Program(); //object creation
ob1.getdata();
ob1.showdata();
Console.ReadKey();
}
}
}
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
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
using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.Write("Content: ");
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:
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");
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadKey();
}
}
}
Output:
Array ArrayList
Array uses the Vector array to store the
ArrayList uses the LinkedList to store the elements.
elements
It will not lead to Runtime exception It leads to the Run time error exception.
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()
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.
namespace Learning_Events_in_CSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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:
using System;
namespace Test_Program_for_teaching
{
public class StringDataStore
{
public string[] strArr = new string[5]; // internal data storage
set
{
if (index < 0 && index >= strArr.Length)
throw new IndexOutOfRangeException("Cannot store more than 10
objects");
strArr[index] = value;
}
}
}
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.
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)]
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
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.
Following are the commonly used namespaces that contains useful classes and interfaces and
defined in Framework Class Library.
Namespaces Description
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.
Sample Program:
using System;
using System.Collections.Generic;
using System.Linq;
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.
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();
}
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();
}
3. Design a form and write visual C# program that accepts any three numbers and displays the
largest among them.
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();
}
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;
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);
}
}
}
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]
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]
Advantages of .NET
• Object-oriented programming
• Language independence
• Efficient data access
• Code sharing
• Support for services
CLS
Framework
Class
Library
CLR
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.
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.
• 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.
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.
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.
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
• 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.
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.
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.
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.
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.
4. The native code is executed in the context of the managed CLR, along with any other running applications
or processes.
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.
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
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#.
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.
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.
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.
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.
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.
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.
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.
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.
Features:
a) They generate their own interface.
b) They retain their state
c) They fire server-side events.
• 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.
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>
<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> </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.
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/
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.
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
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) :
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);
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();
}
}
Refer: https://www.guru99.com/insert-update-delete-asp-net.html
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.
CommandType.Text is the default. So we may not specify it, and write the above code simply as:
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.
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.
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();
}
}
}
}
}
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]
Java Environment
The programming environment of Java consists of three components mainly:
1. JDK
2. JRE
3. JVM
• 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.
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.
➔ 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;
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.
void display(){
System.out.println("Roll No:" + roll+ " " +"Age: "+age);
}
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]
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.
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.
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
If you compile and execute the above program, you will get the following exception.
Output
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.
At Runtime:
When we enter two numbers 10 and 5, output is as:
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:
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
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");
Output:
Refer: https://www.youtube.com/watch?v=nsJvdOrjBRA
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.
}
}
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");
}
catch(Throwable e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
https://stackify.com/best-practices-exceptions-java/
6. Beware of overusing exceptions.
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.
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
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.
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();
}
}
}
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();
}
}
}
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
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:
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
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:
In commamd prompt;
C:\> appletviewer Test.html
We will get a view of applet.
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.
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:
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).
Refer: http://www.mathcs.emory.edu/~cheung/Courses/377/Syllabus/8JDBC/GUI/Applets/applet.html
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
<APPLET
[CODEBASE= codebase URL]
[CODE= appletFile]
[ALT= alternate text]
[NAME=appletInstanceName]
[WIDTH=pixels]
[HEIGHT=pixels]
[ALIGN=alignment]
[VSPACE= pixels]
[HSPACE=pixels] >
In the command prompt, we create a class file and run the applet viewer by commanding as:
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.
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
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.
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]
***
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.
//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.
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.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame(); //creating instance of JFrame
Figure: Activity Diagram to show Interaction between model, view and controller objects
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
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class EventHandlingDemo extends JFrame
{
//variable declaration
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Button Clicked");
}
});
}
ob.setVisible(true);
}
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hello Java"); //displays Hello Java in Commmand prompt
}
});
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnClose = new JButton("Close");
add(btnClose);
}
});
}
ob.setVisible(true);
}
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getContentPane().setBackground(Color.GREEN);
}
});
}
ob.setVisible(true);
}
}
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
//Creating a 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());
}
});
}
ob.setVisible(true);
}
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//creating label for First Number
//Creating a 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);
}
});
}
f.setVisible(true);
}
}
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]
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.
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();
}
}
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.
<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>
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.
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.
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
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:
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
<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();
<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:
Step 8:
Supply the information and submit it. You should get a message as:
Assignment:
Username
Password
Submit Reset
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();
}
}
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 8: Select the color (say you selected Red) and submit it. You should get a message as:
//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();
}
}
<web-app>
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>GetPostDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/colorchooser</url-pattern>
</servlet-mapping>
</web-app>
Upon selecting the color (say we selected Green) and submitted it. we should get a message as:
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 {
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
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.
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.
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.
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:
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:
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:
Syntax:-
<%! Dec var %>
Example:-
<%! int var=10; %>
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:-
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:
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:-
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:
<%@
page import="java.util.*,java.sql.*"
%>
<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 :
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);
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.
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.
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:
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:
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:
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.
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:
Output:
Assignment:
Differentiate between JSP and Servlet.
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]
***
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.
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.
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.
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.
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.
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.
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).
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( );
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");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
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");
// execute query
ResultSet rst = stm.executeQuery(
"SELECT Auth_ID, Auth_FName, Auth_LName, Auth_Address,Auth_PhoneNo FROM
AuthorDetail");
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();
}
}
}
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
USE myDatabase;
//saved as DataAccessExample.java
import java.sql.*;
try
{
conn=DriverManager.getConnection("jdbc:mysql://localhost/myDatabase","root",
"root");
while (rs.next())
{
String name= rs.getString("name");
String address= rs.getString("address");
int dob=rs.getInt("dob");
catch(Exception e)
{
e.printStackTrace();
}
}
}
Eg:
Statement stm=con.createStatement( );
Where:
stm and con are objects of Statement and Connection
createStatement() is a method.
Following table provides a summary of each interface’s purpose to decide on the interface to use.
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.
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 $$
CallableStatement cs = null;
cs = this.conn.prepareCall("{call getAuthor()}");
ResultSet rs = cs.executeQuery();
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:
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
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]
***
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:
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:
8. Click JButton and put it on the form. Change the properties of this button:
Variable : btn7
Text :7
Font : Tahoma 20 Bold
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);
}
}
11. Right Click on Button 7 > Add Button Handler > action > action performed. You will get as
below:
………………………………..
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:
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.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:
18. For the clear button C, Double click and write the shaded code as below:
txtDisplay.setText(null);
}
});
btnClear.setFont(new Font("Tahoma", Font.BOLD, 20));
btnClear.setBounds(285, 156, 59, 59);
frame.getContentPane().add(btnClear);
double firstnum;
double secondnum;
double result;
String operations;
String answer;
20. Double click on “/” button and write shaded code as:
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);
21. Similary, copy the above highlighted code and do it for x,+ and –buttons. The code goes as
below:
22. Now for +- button, Double click on it and write the code as below:
frame.getContentPane().add(btnPlusMinus);
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);
}
});
btnEqual.setFont(new Font("Tahoma", Font.BOLD, 20));
btnEqual.setBounds(285, 223, 54, 130);
frame.getContentPane().add(btnEqual);
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;
double firstnum;
double secondnum;
double result;
String operations;
String answer;
/**
* 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);
// first row
}
});
btn8.setFont(new Font("Tahoma", Font.BOLD, 20));
btn8.setBounds(91, 91, 59, 59);
frame.getContentPane().add(btn8);
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
}
});
btnClear.setFont(new Font("Tahoma", Font.BOLD, 20));
btnClear.setBounds(285, 156, 59, 59);
frame.getContentPane().add(btnClear);
// Third row
}
});
btnEqual.setFont(new Font("Tahoma", Font.BOLD, 20));
btnEqual.setBounds(285, 223, 54, 130);
frame.getContentPane().add(btnEqual);
// Last row
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class EventHandlingDemo extends JFrame
{
//variable declaration
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Button Clicked");
}
});
}
ob.setVisible(true);
}
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hello Java"); //displays Hello Java in Commmand prompt
}
});
}
ob.setVisible(true);
}
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnClose = new JButton("Close");
add(btnClose);
}
});
}
ob.setVisible(true);
}
}
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
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //for exit when window closed
//Creating a button
btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getContentPane().setBackground(Color.GREEN);
}
});
}
ob.setVisible(true);
}
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
//Creating a 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());
}
});
}
ob.setVisible(true);
}
}
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
//Creating a 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);
}
});
}
f.setVisible(true);
}
}
LESSON 10: JAVA SERVER PAGES (JSP)/ SERVER TECHNOLOGY (Credit: 7 hrs)